use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{self, Receiver, RecvTimeoutError};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use crate::sandbox::Profile;
pub const HARNESS_ENV: &[&str] = &[
"GEMINI_API_KEY",
"GOOGLE_API_KEY",
"ANTHROPIC_API_KEY",
"OLLAMA_API_KEY",
"OLLAMA_HOST",
"OPENAI_API_KEY",
"OPENAI_BASE_URL",
"OPENROUTER_API_KEY",
];
const CREDENTIAL_SEGMENTS: &[&str] = &[
"TOKEN",
"SECRET",
"SECRETS",
"PASSWORD",
"PASSWD",
"PASS",
"KEY",
"CREDENTIAL",
"CREDENTIALS",
"AUTH",
"COOKIE",
"SESSION",
];
const CREDENTIAL_NAMES: &[&str] = &["AWS_PROFILE", "AWS_DEFAULT_PROFILE"];
static PASS_ENV: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();
pub fn credential_like(name: &str, value: &str) -> bool {
let upper = name.to_ascii_uppercase();
if CREDENTIAL_NAMES.contains(&upper.as_str()) {
return true;
}
if upper
.split('_')
.any(|seg| CREDENTIAL_SEGMENTS.contains(&seg))
{
return true;
}
has_inline_credentials(value)
}
fn has_inline_credentials(value: &str) -> bool {
let mut rest = value;
while let Some(idx) = rest.find("://") {
let after_scheme = &rest[idx + 3..];
let len = after_scheme
.find(|c: char| c == '/' || c.is_whitespace())
.unwrap_or(after_scheme.len());
let authority_prefix = &after_scheme[..len];
if let Some((userinfo, _)) = authority_prefix.split_once('@') {
if let Some((_user, pass)) = userinfo.split_once(':') {
if !pass.is_empty() {
return true;
}
}
}
rest = after_scheme;
}
false
}
pub fn set_pass_env(names: Vec<String>) {
let _ = PASS_ENV.set(names);
}
pub fn withheld_env() -> Vec<String> {
let pass_env = PASS_ENV.get();
let mut withheld = Vec::new();
for (key, val) in std::env::vars_os() {
let name = key.to_string_lossy();
if HARNESS_ENV.iter().any(|&h| h == name.as_ref()) {
continue;
}
if name.starts_with("BLYTE_") {
continue;
}
if let Some(passed) = pass_env {
if passed.iter().any(|p| p == name.as_ref()) {
continue;
}
}
let value = val.to_string_lossy();
if credential_like(&name, &value) {
withheld.push(name.into_owned());
}
}
withheld.sort();
withheld.dedup();
withheld
}
fn scrub_harness(cmd: &mut Command) {
for name in HARNESS_ENV {
cmd.env_remove(name);
}
for (name, _) in std::env::vars_os() {
let n = name.to_string_lossy();
if n.starts_with("BLYTE_") && n != "BLYTE_SESSION" {
cmd.env_remove(&name);
}
}
}
fn scrub(cmd: &mut Command) {
scrub_harness(cmd);
for name in withheld_env() {
cmd.env_remove(name);
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Output {
pub stdout: String,
pub stderr: String,
pub exit_code: i32,
}
impl Output {
pub fn merged(&self) -> String {
format!("{}{}", self.stdout, self.stderr)
}
}
pub trait Shell: Send + Sync {
fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String>;
fn exec_user(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
self.exec(command, cwd, timeout)
}
fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
let _ = (command, cwd, timeout);
Err("this shell cannot run a command outside the sandbox".into())
}
fn describe(&self) -> String;
fn available_binaries(&self, cwd: &Path, candidates: &[&'static str]) -> Vec<String> {
let probe = candidates
.iter()
.map(|b| format!("command -v {b} >/dev/null 2>&1 && echo {b}"))
.collect::<Vec<_>>()
.join("; ");
match self.exec(&probe, cwd, Duration::from_secs(30)) {
Ok(o) => o
.stdout
.lines()
.map(|l| l.trim().to_string())
.filter(|l| !l.is_empty())
.collect(),
Err(_) => Vec::new(),
}
}
}
#[derive(Debug, Default)]
pub struct CancelHandle {
cancelled: AtomicBool,
active_pgid: Mutex<Option<i32>>,
}
impl CancelHandle {
pub fn new() -> Self {
Self::default()
}
pub fn is_cancelled(&self) -> bool {
self.cancelled.load(Ordering::SeqCst)
}
pub fn flag(&self) -> &AtomicBool {
&self.cancelled
}
pub fn cancel(&self) {
let pgid = {
let guard = self.active_pgid.lock().unwrap_or_else(|e| e.into_inner());
self.cancelled.store(true, Ordering::SeqCst);
*guard
};
#[cfg(unix)]
if let Some(pgid) = pgid {
if pgid > 0 {
unsafe {
libc::kill(-pgid, libc::SIGKILL);
}
}
}
#[cfg(not(unix))]
let _ = pgid;
}
fn register_pgid(&self, pgid: i32) -> bool {
let mut guard = self.active_pgid.lock().unwrap_or_else(|e| e.into_inner());
if self.cancelled.load(Ordering::SeqCst) {
return false;
}
*guard = Some(pgid);
true
}
fn clear_pgid(&self) {
let mut guard = self.active_pgid.lock().unwrap_or_else(|e| e.into_inner());
*guard = None;
}
}
fn kill_child_group(child: &mut Child) {
#[cfg(unix)]
{
let pgid = child.id() as i32;
if pgid > 0 {
unsafe {
libc::kill(-pgid, libc::SIGKILL);
}
} else {
let _ = child.kill();
}
}
#[cfg(not(unix))]
{
let _ = child.kill();
}
let _ = child.wait();
}
pub const POLL_START: Duration = Duration::from_millis(1);
pub fn poll_backoff(current: Duration, remaining: Duration) -> (Duration, Duration) {
(
current.min(remaining),
(current * 2).min(Duration::from_millis(50)),
)
}
fn exec_command(cmd: Command, timeout: Duration) -> Result<Output, String> {
exec_command_cancellable(cmd, timeout, None)
}
fn exec_command_cancellable(
mut cmd: Command,
timeout: Duration,
cancel: Option<&CancelHandle>,
) -> Result<Output, String> {
use std::process::Stdio;
if cancel.is_some_and(CancelHandle::is_cancelled) {
return Err("command cancelled".into());
}
cmd.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
cmd.process_group(0);
}
let mut child = cmd
.spawn()
.map_err(|e| format!("cannot run command: {e}"))?;
if let Some(handle) = cancel {
if !handle.register_pgid(child.id() as i32) {
kill_child_group(&mut child);
return Err("command cancelled".into());
}
}
let mut so = child.stdout.take().ok_or("no stdout")?;
let mut se = child.stderr.take().ok_or("no stderr")?;
let t_out = std::thread::spawn(move || {
let mut b = String::new();
let _ = so.read_to_string(&mut b);
b
});
let t_err = std::thread::spawn(move || {
let mut b = String::new();
let _ = se.read_to_string(&mut b);
b
});
let deadline = std::time::Instant::now() + timeout;
let mut poll = POLL_START;
let mut was_cancelled = false;
let status = loop {
match child.try_wait().map_err(|e| format!("wait failed: {e}"))? {
Some(s) => break Some(s),
None if cancel.is_some_and(CancelHandle::is_cancelled) => {
was_cancelled = true;
kill_child_group(&mut child);
break None;
}
None if std::time::Instant::now() >= deadline => {
kill_child_group(&mut child);
break None;
}
None => {
let remaining = deadline.saturating_duration_since(Instant::now());
let (sleep, next) = poll_backoff(poll, remaining);
std::thread::sleep(sleep);
poll = next;
}
}
};
if let Some(handle) = cancel {
handle.clear_pgid();
}
let stdout = t_out.join().unwrap_or_default();
let stderr = t_err.join().unwrap_or_default();
if was_cancelled {
return Err("command cancelled".into());
}
match status {
Some(s) => Ok(Output {
stdout,
stderr,
exit_code: s.code().unwrap_or(-1),
}),
None => Ok(Output {
stdout,
stderr: format!("{stderr}\n[killed by blyte after {}s]", timeout.as_secs()),
exit_code: 124, }),
}
}
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct LocalShell {
pub profile: Option<Profile>,
}
#[allow(non_upper_case_globals)]
pub const LocalShell: LocalShell = LocalShell { profile: None };
impl LocalShell {
pub fn new() -> Self {
Self { profile: None }
}
pub fn sandboxed(profile: impl Into<Profile>) -> Self {
Self {
profile: Some(profile.into()),
}
}
fn build_command(&self, command: &str, cwd: &Path) -> Result<Command, String> {
let full_command = inherited_path_prefix() + command;
let command = full_command.as_str();
let mut cmd = match &self.profile {
Some(Profile::Seatbelt(profile)) => {
let mut c = Command::new("/usr/bin/sandbox-exec");
c.args(["-p", profile, "bash", "-lc", command]);
c
}
Some(Profile::Landlock(paths)) => {
#[cfg(target_os = "linux")]
{
let mut c = Command::new("bash");
c.arg("-lc").arg(command);
crate::sandbox::landlock_pre_exec(&mut c, paths, None, false)
.map_err(|e| e.to_string())?;
c
}
#[cfg(not(target_os = "linux"))]
{
let _ = paths;
return Err(std::io::Error::new(
std::io::ErrorKind::Unsupported,
"Landlock is only supported on Linux",
)
.to_string());
}
}
Some(Profile::LandlockOffline(paths)) => {
#[cfg(target_os = "linux")]
{
let mut c = Command::new("bash");
c.arg("-lc").arg(command);
crate::sandbox::landlock_pre_exec(&mut c, paths, None, true)
.map_err(|e| e.to_string())?;
c
}
#[cfg(not(target_os = "linux"))]
{
let _ = paths;
return Err(std::io::Error::new(
std::io::ErrorKind::Unsupported,
"Landlock is only supported on Linux",
)
.to_string());
}
}
Some(Profile::LandlockConfined {
write,
read,
block_tcp,
}) => {
#[cfg(target_os = "linux")]
{
let mut c = Command::new("bash");
c.arg("-lc").arg(command);
crate::sandbox::landlock_pre_exec(&mut c, write, Some(read), *block_tcp)
.map_err(|e| e.to_string())?;
c
}
#[cfg(not(target_os = "linux"))]
{
let _ = (write, read, block_tcp);
return Err(std::io::Error::new(
std::io::ErrorKind::Unsupported,
"Landlock is only supported on Linux",
)
.to_string());
}
}
None => {
let mut c = Command::new("bash");
c.arg("-lc").arg(command);
c
}
};
cmd.current_dir(cwd);
scrub(&mut cmd);
Ok(cmd)
}
}
impl Shell for LocalShell {
fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
let cmd = self.build_command(command, cwd)?;
exec_command(cmd, timeout)
}
fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
let full_command = inherited_path_prefix() + command;
let mut cmd = Command::new("bash");
cmd.arg("-lc").arg(&full_command);
cmd.current_dir(cwd);
scrub_harness(&mut cmd);
exec_command(cmd, timeout)
}
fn describe(&self) -> String {
"Commands run directly on this machine, in the workspace directory.".into()
}
}
#[derive(Debug, Clone)]
pub struct CancellableLocalShell {
pub inner: LocalShell,
pub cancel: Arc<CancelHandle>,
}
impl Shell for CancellableLocalShell {
fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
let cmd = self.inner.build_command(command, cwd)?;
exec_command_cancellable(cmd, timeout, Some(&self.cancel))
}
fn describe(&self) -> String {
self.inner.describe()
}
}
#[derive(Debug, Clone)]
pub struct ContainerShell {
pub container_id: String,
pub workdir: PathBuf,
}
impl ContainerShell {
fn build_command(&self, command: &str) -> Command {
let mut cmd = Command::new("docker");
cmd.args(["exec", "-i", "-w"])
.arg(&self.workdir)
.arg(&self.container_id)
.args(["bash", "-lc", command]);
cmd
}
}
impl Shell for ContainerShell {
fn exec(&self, command: &str, _cwd: &Path, timeout: Duration) -> Result<Output, String> {
exec_command(self.build_command(command), timeout)
}
fn describe(&self) -> String {
format!(
"Commands run inside the project container at {}. Project dependencies are \
installed there, not on the host.",
self.workdir.display()
)
}
}
#[derive(Debug, Clone)]
pub struct CancellableContainerShell {
pub inner: ContainerShell,
pub cancel: Arc<CancelHandle>,
}
impl Shell for CancellableContainerShell {
fn exec(&self, command: &str, _cwd: &Path, timeout: Duration) -> Result<Output, String> {
exec_command_cancellable(
self.inner.build_command(command),
timeout,
Some(&self.cancel),
)
}
fn describe(&self) -> String {
self.inner.describe()
}
}
fn quote(s: &str) -> String {
format!("'{}'", s.replace('\'', r"'\''"))
}
pub fn inherited_path_prefix() -> String {
match std::env::var("PATH") {
Ok(path) if !path.is_empty() => format!("export PATH={}:\"$PATH\"; ", quote(&path)),
_ => String::new(),
}
}
#[derive(Debug, Clone)]
pub enum Launcher {
Local {
root: PathBuf,
profile: Option<Profile>,
},
Container {
container_id: String,
workdir: PathBuf,
},
}
impl Launcher {
fn command(&self) -> std::io::Result<Command> {
match self {
Launcher::Local { root, profile } => {
let mut c = match profile {
Some(Profile::Seatbelt(p)) => {
let mut cmd = Command::new("/usr/bin/sandbox-exec");
cmd.args(["-p", p, "bash", "-l"]);
cmd
}
Some(Profile::Landlock(paths)) => {
#[cfg(target_os = "linux")]
{
let mut cmd = Command::new("bash");
cmd.arg("-l");
crate::sandbox::landlock_pre_exec(&mut cmd, paths, None, false)?;
cmd
}
#[cfg(not(target_os = "linux"))]
{
let _ = paths;
return Err(std::io::Error::new(
std::io::ErrorKind::Unsupported,
"Landlock is only supported on Linux",
));
}
}
Some(Profile::LandlockOffline(paths)) => {
#[cfg(target_os = "linux")]
{
let mut cmd = Command::new("bash");
cmd.arg("-l");
crate::sandbox::landlock_pre_exec(&mut cmd, paths, None, true)?;
cmd
}
#[cfg(not(target_os = "linux"))]
{
let _ = paths;
return Err(std::io::Error::new(
std::io::ErrorKind::Unsupported,
"Landlock is only supported on Linux",
));
}
}
Some(Profile::LandlockConfined {
write,
read,
block_tcp,
}) => {
#[cfg(target_os = "linux")]
{
let mut cmd = Command::new("bash");
cmd.arg("-l");
crate::sandbox::landlock_pre_exec(
&mut cmd,
write,
Some(read),
*block_tcp,
)?;
cmd
}
#[cfg(not(target_os = "linux"))]
{
let _ = (write, read, block_tcp);
return Err(std::io::Error::new(
std::io::ErrorKind::Unsupported,
"Landlock is only supported on Linux",
));
}
}
None => {
let mut cmd = Command::new("bash");
cmd.arg("-l");
cmd
}
};
c.current_dir(root);
scrub(&mut c);
Ok(c)
}
Launcher::Container {
container_id,
workdir,
} => {
let mut c = Command::new("docker");
c.args(["exec", "-i", "-w"])
.arg(workdir)
.arg(container_id)
.args(["bash", "-l"]);
Ok(c)
}
}
}
fn fallback(&self) -> Box<dyn Shell> {
match self {
Launcher::Local { profile, .. } => match profile {
Some(p) => Box::new(LocalShell::sandboxed(p.clone())),
None => Box::new(LocalShell),
},
Launcher::Container {
container_id,
workdir,
} => Box::new(ContainerShell {
container_id: container_id.clone(),
workdir: workdir.clone(),
}),
}
}
}
pub enum RunResult {
Done(Output),
TimedOut {
out: String,
err: String,
},
Died {
out: String,
err: String,
},
}
pub struct Session {
child: Child,
stdin: ChildStdin,
chunks: Receiver<Vec<u8>>,
buf: Vec<u8>,
tmp: String,
next: u64,
nonce: String,
}
const READY: &str = "__BLYTE_READY__ ";
fn nonce() -> String {
let t = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
format!("{t:x}{:x}", std::process::id())
}
enum ReadErr {
Timeout,
Closed,
}
impl Session {
pub fn start(launcher: &Launcher) -> Result<Session, String> {
let mut cmd = launcher
.command()
.map_err(|e| format!("cannot start a shell session: {e}"))?;
cmd.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null());
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
cmd.process_group(0);
}
let mut child = cmd
.spawn()
.map_err(|e| format!("cannot start a shell session: {e}"))?;
let stdin = child.stdin.take().ok_or("no stdin")?;
let mut stdout = child.stdout.take().ok_or("no stdout")?;
let (tx, rx) = mpsc::channel();
std::thread::spawn(move || {
let mut chunk = vec![0u8; 64 * 1024];
loop {
match stdout.read(&mut chunk) {
Ok(0) | Err(_) => break,
Ok(n) => {
if tx.send(chunk[..n].to_vec()).is_err() {
break;
}
}
}
}
});
let mut s = Session {
child,
stdin,
chunks: rx,
buf: Vec::new(),
tmp: String::new(),
next: 0,
nonce: nonce(),
};
let init = match launcher {
Launcher::Local { .. } => inherited_path_prefix(),
Launcher::Container { .. } => String::new(),
};
s.send(&format!(
"{init}__blyte_t=$(mktemp -d 2>/dev/null || {{ mkdir -p /tmp/blyte.$$ && echo /tmp/blyte.$$; }}); \
echo \"__BLYTE_READY__ $__blyte_t\"\n",
))?;
let deadline = Instant::now() + Duration::from_secs(30);
loop {
match s.read_line(deadline) {
Ok(l) if l.starts_with(READY) => {
s.tmp = l[READY.len()..].trim().to_string();
return Ok(s);
}
Ok(_) => continue, Err(_) => {
s.kill();
return Err("the shell session did not start".into());
}
}
}
}
fn send(&mut self, script: &str) -> Result<(), String> {
self.stdin
.write_all(script.as_bytes())
.and_then(|_| self.stdin.flush())
.map_err(|e| format!("the shell session closed: {e}"))
}
fn fill(&mut self, deadline: Instant) -> Result<(), ReadErr> {
match self
.chunks
.recv_timeout(deadline.saturating_duration_since(Instant::now()))
{
Ok(c) => {
self.buf.extend_from_slice(&c);
Ok(())
}
Err(RecvTimeoutError::Timeout) => Err(ReadErr::Timeout),
Err(RecvTimeoutError::Disconnected) => Err(ReadErr::Closed),
}
}
fn read_line(&mut self, deadline: Instant) -> Result<String, ReadErr> {
loop {
if let Some(i) = self.buf.iter().position(|&b| b == b'\n') {
let line: Vec<u8> = self.buf.drain(..=i).collect();
return Ok(String::from_utf8_lossy(&line[..i]).into_owned());
}
self.fill(deadline)?;
}
}
fn read_exact(&mut self, n: usize, deadline: Instant) -> Result<Vec<u8>, ReadErr> {
while self.buf.len() < n {
self.fill(deadline)?;
}
Ok(self.buf.drain(..n).collect())
}
pub fn kill(&mut self) {
#[cfg(unix)]
{
let pgid = self.child.id() as i32;
if pgid > 0 {
unsafe {
libc::kill(-pgid, libc::SIGKILL);
}
}
}
let _ = self.child.kill();
let _ = self.child.wait();
}
pub fn run(&mut self, command: &str, cwd: Option<&Path>, timeout: Duration) -> RunResult {
let id = self.next;
self.next += 1;
let (out, err) = (
format!("{}/{id}.o", self.tmp),
format!("{}/{id}.e", self.tmp),
);
let (qo, qe, qt) = (quote(&out), quote(&err), quote(&self.tmp));
let delim = format!("__BLYTE_CMD_{id}_{}__", self.nonce);
let body = match cwd {
Some(d) => format!(
"( cd {} && eval \"$__blyte_c\" )",
quote(&d.to_string_lossy())
),
None => "eval \"$__blyte_c\"".to_string(),
};
let script = format!(
"IFS= read -r -d '' __blyte_c <<'{delim}' || true\n{command}\n{delim}\n\
[ -d {qt} ] || mkdir -p {qt} 2>/dev/null; {body} </dev/null >{qo} 2>{qe}; __blyte_r=$?; \
IFS= read -r -d '' __blyte_o <{qo} || true; \
IFS= read -r -d '' __blyte_e <{qe} || true; \
__blyte_l=${{LC_ALL-__blyte_unset__}}; LC_ALL=C; \
printf '__BLYTE_{id}__ %s %s %s\\n%s%s' \"$__blyte_r\" \"${{#__blyte_o}}\" \
\"${{#__blyte_e}}\" \"$__blyte_o\" \"$__blyte_e\"; \
if [ \"$__blyte_l\" = __blyte_unset__ ]; then unset LC_ALL; else LC_ALL=$__blyte_l; fi; \
unset __blyte_c __blyte_o __blyte_e __blyte_l\n"
);
if self.send(&script).is_err() {
return RunResult::Died { out, err };
}
let marker = format!("__BLYTE_{id}__ ");
let deadline = Instant::now() + timeout;
let fail = |e: ReadErr, out: String, err: String| match e {
ReadErr::Timeout => RunResult::TimedOut { out, err },
ReadErr::Closed => RunResult::Died { out, err },
};
let header = loop {
match self.read_line(deadline) {
Ok(l) => {
if let Some(rest) = l.strip_prefix(&marker) {
break rest.to_string();
}
}
Err(e) => return fail(e, out, err),
}
};
let mut f = header.split(' ');
let exit_code = f.next().and_then(|x| x.parse().ok()).unwrap_or(-1);
let no: usize = f.next().and_then(|x| x.parse().ok()).unwrap_or(0);
let ne: usize = f.next().and_then(|x| x.parse().ok()).unwrap_or(0);
match self.read_exact(no + ne, deadline) {
Ok(bytes) => RunResult::Done(Output {
stdout: String::from_utf8_lossy(&bytes[..no]).into_owned(),
stderr: String::from_utf8_lossy(&bytes[no..]).into_owned(),
exit_code,
}),
Err(e) => fail(e, out, err),
}
}
fn close(&mut self) {
let _ = self.send(&format!("rm -rf {}; exit 0\n", quote(&self.tmp)));
let deadline = Instant::now() + Duration::from_millis(300);
while Instant::now() < deadline {
if let Ok(Some(_)) = self.child.try_wait() {
return;
}
std::thread::sleep(Duration::from_millis(10));
}
self.kill();
}
}
pub struct PersistentShell {
launcher: Launcher,
harness: Mutex<Option<Session>>,
user: Mutex<Option<Session>>,
fallback: Box<dyn Shell>,
}
impl PersistentShell {
pub fn new(launcher: Launcher) -> Self {
let fallback = launcher.fallback();
Self {
launcher,
harness: Mutex::new(None),
user: Mutex::new(None),
fallback,
}
}
pub fn local(root: PathBuf) -> Self {
Self::new(Launcher::Local {
root,
profile: None,
})
}
pub fn local_sandboxed(root: PathBuf, profile: impl Into<Profile>) -> Self {
Self::new(Launcher::Local {
root,
profile: Some(profile.into()),
})
}
pub fn sandboxed(root: PathBuf, profile: impl Into<Profile>) -> Self {
Self::local_sandboxed(root, profile)
}
pub fn container(container_id: String, workdir: PathBuf) -> Self {
Self::new(Launcher::Container {
container_id,
workdir,
})
}
pub fn is_persistent(&self) -> bool {
let mut g = self.harness.lock().unwrap_or_else(|e| e.into_inner());
if g.is_none() {
*g = Session::start(&self.launcher).ok();
}
g.is_some()
}
fn run(
&self,
slot: &Mutex<Option<Session>>,
command: &str,
cwd: Option<&Path>,
timeout: Duration,
) -> Option<Result<Output, String>> {
let mut g = slot.lock().unwrap_or_else(|e| e.into_inner());
if g.is_none() {
*g = Session::start(&self.launcher).ok();
}
let session = g.as_mut()?;
let (out, err, note, code) = match session.run(command, cwd, timeout) {
RunResult::Done(o) => return Some(Ok(o)),
RunResult::TimedOut { out, err } => (
out,
err,
format!("\n[killed by blyte after {}s]", timeout.as_secs()),
124,
),
RunResult::Died { out, err } => (
out,
err,
"[the shell exited; the next command starts a fresh shell in the workspace root]"
.to_string(),
1,
),
};
session.kill();
*g = None;
drop(g);
let cat = |p: &str| {
self.fallback
.exec(
&format!("cat -- {q} 2>/dev/null; rm -f -- {q}", q = quote(p)),
Path::new("/"),
Duration::from_secs(30),
)
.map(|o| o.stdout)
.unwrap_or_default()
};
let (stdout, stderr) = (cat(&out), cat(&err));
Some(Ok(Output {
stdout,
stderr: format!("{stderr}{note}"),
exit_code: code,
}))
}
}
impl Shell for PersistentShell {
fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
self.run(&self.harness, command, Some(cwd), timeout)
.unwrap_or_else(|| self.fallback.exec(command, cwd, timeout))
}
fn exec_user(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
self.run(&self.user, command, None, timeout)
.unwrap_or_else(|| self.fallback.exec(command, cwd, timeout))
}
fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
self.fallback.exec_host(command, cwd, timeout)
}
fn describe(&self) -> String {
format!(
"{} Your `bash` commands share one shell session: `cd` and `export` carry over to \
later commands. File tools always resolve paths from the workspace root.",
self.fallback.describe()
)
}
}
impl Drop for PersistentShell {
fn drop(&mut self) {
for slot in [&self.harness, &self.user] {
if let Some(mut s) = slot.lock().unwrap_or_else(|e| e.into_inner()).take() {
s.close();
}
}
}
}