Skip to main content

blyte_agent/
shell.rs

1//! Where commands actually run. A seam, not a hardcoded `bash -lc`.
2//!
3//! # Why this is a trait
4//!
5//! The model-facing `bash` tool must mean the same thing regardless of whether execution lands
6//! on the host, inside a container, or on another machine. Baking the target into the tool --
7//! or worse, into the prompt -- is how the previous harness produced its most expensive class
8//! of bug: dependencies lived in a container, the worker was *told in prose* to reach them via
9//! `./run-in-container`, and when that instruction went missing it edited the host while its
10//! verification ran in the sandbox. Nothing was wrong with the tool; the environment was a
11//! convention rather than a property.
12//!
13//! With a seam there is nothing to instruct and nothing to forget. A deployment composes the
14//! executor; the model sees `bash` either way. This is the shape DeepSeek's harness settled on
15//! (`ctx.shell` backed by `bash-local` or `bash-sandbox`, `ctx.sandbox` by `sandbox-local` or
16//! `sandbox-ssh`) and it is right for the same reason.
17//!
18//! It also makes the environment probe honest: [`Shell::available_binaries`] runs *through* the
19//! executor, so a container deployment reports what is reachable inside the container rather
20//! than what happens to be installed on the host.
21
22use std::io::{Read, Write};
23use std::path::{Path, PathBuf};
24use std::process::{Child, ChildStdin, Command, Stdio};
25use std::sync::atomic::{AtomicBool, Ordering};
26use std::sync::mpsc::{self, Receiver, RecvTimeoutError};
27use std::sync::{Arc, Mutex};
28use std::time::{Duration, Instant};
29
30use crate::sandbox::Profile;
31
32/// Variables the harness itself uses, never passed to the commands it runs: provider credentials
33/// (the model could otherwise read them with `env`) and blyte's own configuration (a
34/// `BLYTE_MODEL` in the environment broke the repository's provider tests). Every variable named
35/// `BLYTE_*` is removed as well, except `BLYTE_SESSION`: an interactive session's id, which the
36/// dispatches it starts must inherit so the usage log can attribute them. Container commands never
37/// inherit the host environment.
38pub const HARNESS_ENV: &[&str] = &[
39    "GEMINI_API_KEY",
40    "GOOGLE_API_KEY",
41    "ANTHROPIC_API_KEY",
42    "OLLAMA_API_KEY",
43    "OLLAMA_HOST",
44    "OPENAI_API_KEY",
45    "OPENAI_BASE_URL",
46    "OPENROUTER_API_KEY",
47];
48
49const CREDENTIAL_SEGMENTS: &[&str] = &[
50    "TOKEN",
51    "SECRET",
52    "SECRETS",
53    "PASSWORD",
54    "PASSWD",
55    "PASS",
56    "KEY",
57    "CREDENTIAL",
58    "CREDENTIALS",
59    "AUTH",
60    "COOKIE",
61    "SESSION",
62];
63
64/// Whole names that select credentials without looking like one: the AWS profile variables pick a
65/// profile in ~/.aws, which the sandbox denies (a passed profile makes boto fail on it).
66const CREDENTIAL_NAMES: &[&str] = &["AWS_PROFILE", "AWS_DEFAULT_PROFILE"];
67
68static PASS_ENV: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();
69
70/// True when the upper-cased name is one of `CREDENTIAL_NAMES`, or, split on `_`,
71/// has a credential segment, or the value contains a URL with inline credentials.
72pub fn credential_like(name: &str, value: &str) -> bool {
73    let upper = name.to_ascii_uppercase();
74    if CREDENTIAL_NAMES.contains(&upper.as_str()) {
75        return true;
76    }
77    if upper
78        .split('_')
79        .any(|seg| CREDENTIAL_SEGMENTS.contains(&seg))
80    {
81        return true;
82    }
83    has_inline_credentials(value)
84}
85
86fn has_inline_credentials(value: &str) -> bool {
87    let mut rest = value;
88    while let Some(idx) = rest.find("://") {
89        let after_scheme = &rest[idx + 3..];
90        let len = after_scheme
91            .find(|c: char| c == '/' || c.is_whitespace())
92            .unwrap_or(after_scheme.len());
93        let authority_prefix = &after_scheme[..len];
94        if let Some((userinfo, _)) = authority_prefix.split_once('@') {
95            if let Some((_user, pass)) = userinfo.split_once(':') {
96                if !pass.is_empty() {
97                    return true;
98                }
99            }
100        }
101        rest = after_scheme;
102    }
103    false
104}
105
106/// Process-wide allow-list of environment variable names to keep even if they look like credentials.
107///
108/// Calling this a second time is a no-op.
109pub fn set_pass_env(names: Vec<String>) {
110    let _ = PASS_ENV.set(names);
111}
112
113/// The sorted names of current process environment variables withheld by the credential filter.
114pub fn withheld_env() -> Vec<String> {
115    let pass_env = PASS_ENV.get();
116    let mut withheld = Vec::new();
117    for (key, val) in std::env::vars_os() {
118        let name = key.to_string_lossy();
119        if HARNESS_ENV.iter().any(|&h| h == name.as_ref()) {
120            continue;
121        }
122        if name.starts_with("BLYTE_") {
123            continue;
124        }
125        if let Some(passed) = pass_env {
126            if passed.iter().any(|p| p == name.as_ref()) {
127                continue;
128            }
129        }
130        let value = val.to_string_lossy();
131        if credential_like(&name, &value) {
132            withheld.push(name.into_owned());
133        }
134    }
135    withheld.sort();
136    withheld.dedup();
137    withheld
138}
139
140fn scrub_harness(cmd: &mut Command) {
141    for name in HARNESS_ENV {
142        cmd.env_remove(name);
143    }
144    for (name, _) in std::env::vars_os() {
145        let n = name.to_string_lossy();
146        if n.starts_with("BLYTE_") && n != "BLYTE_SESSION" {
147            cmd.env_remove(&name);
148        }
149    }
150}
151
152/// Remove the harness's own variables and credential-looking variables from a command about to run on this machine.
153fn scrub(cmd: &mut Command) {
154    scrub_harness(cmd);
155    for name in withheld_env() {
156        cmd.env_remove(name);
157    }
158}
159
160#[derive(Debug, Clone, PartialEq, Eq)]
161pub struct Output {
162    pub stdout: String,
163    pub stderr: String,
164    pub exit_code: i32,
165}
166
167impl Output {
168    /// stdout and stderr as the model should see them: interleaved is not reconstructable
169    /// after the fact, so stdout first then stderr, which is how a terminal usually reads.
170    pub fn merged(&self) -> String {
171        format!("{}{}", self.stdout, self.stderr)
172    }
173}
174
175pub trait Shell: Send + Sync {
176    /// Run a command to completion. Blocking by contract -- see `tools` for why.
177    fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String>;
178
179    /// Run a command the **model** issued. Where the executor keeps a persistent session, its
180    /// `cd` and `export` carry over to the model's next command, as in a terminal. The default
181    /// is `exec`: a fresh process in `cwd`.
182    fn exec_user(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
183        self.exec(command, cwd, timeout)
184    }
185
186    fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
187        let _ = (command, cwd, timeout);
188        Err("this shell cannot run a command outside the sandbox".into())
189    }
190
191    /// Human-readable description of where commands land, for the system prompt.
192    /// A worker that knows it is inside a container does not go looking for the host.
193    fn describe(&self) -> String;
194
195    /// Which binaries exist **in the execution environment**, not on the orchestrator's host.
196    fn available_binaries(&self, cwd: &Path, candidates: &[&'static str]) -> Vec<String> {
197        // One probe rather than N: a remote or containerised shell pays a round trip per call,
198        // and sixteen of them before the first turn is a poor way to start.
199        let probe = candidates
200            .iter()
201            .map(|b| format!("command -v {b} >/dev/null 2>&1 && echo {b}"))
202            .collect::<Vec<_>>()
203            .join("; ");
204        match self.exec(&probe, cwd, Duration::from_secs(30)) {
205            Ok(o) => o
206                .stdout
207                .lines()
208                .map(|l| l.trim().to_string())
209                .filter(|l| !l.is_empty())
210                .collect(),
211            Err(_) => Vec::new(),
212        }
213    }
214}
215
216/// Cooperative cancellation handle that terminates an active command's process group.
217#[derive(Debug, Default)]
218pub struct CancelHandle {
219    cancelled: AtomicBool,
220    active_pgid: Mutex<Option<i32>>,
221}
222
223impl CancelHandle {
224    pub fn new() -> Self {
225        Self::default()
226    }
227
228    pub fn is_cancelled(&self) -> bool {
229        self.cancelled.load(Ordering::SeqCst)
230    }
231
232    pub fn flag(&self) -> &AtomicBool {
233        &self.cancelled
234    }
235
236    pub fn cancel(&self) {
237        let pgid = {
238            let guard = self.active_pgid.lock().unwrap_or_else(|e| e.into_inner());
239            self.cancelled.store(true, Ordering::SeqCst);
240            *guard
241        };
242        #[cfg(unix)]
243        if let Some(pgid) = pgid {
244            if pgid > 0 {
245                unsafe {
246                    libc::kill(-pgid, libc::SIGKILL);
247                }
248            }
249        }
250        #[cfg(not(unix))]
251        let _ = pgid;
252    }
253
254    fn register_pgid(&self, pgid: i32) -> bool {
255        let mut guard = self.active_pgid.lock().unwrap_or_else(|e| e.into_inner());
256        if self.cancelled.load(Ordering::SeqCst) {
257            return false;
258        }
259        *guard = Some(pgid);
260        true
261    }
262
263    fn clear_pgid(&self) {
264        let mut guard = self.active_pgid.lock().unwrap_or_else(|e| e.into_inner());
265        *guard = None;
266    }
267}
268
269fn kill_child_group(child: &mut Child) {
270    // On Unix, kill the entire process group with a negative PGID.
271    // This ensures all child and grandchild processes are terminated simultaneously,
272    // releasing standard stream pipe handles so reader threads unblock promptly.
273    #[cfg(unix)]
274    {
275        let pgid = child.id() as i32;
276        if pgid > 0 {
277            unsafe {
278                libc::kill(-pgid, libc::SIGKILL);
279            }
280        } else {
281            let _ = child.kill();
282        }
283    }
284    #[cfg(not(unix))]
285    {
286        let _ = child.kill();
287    }
288    let _ = child.wait();
289}
290
291pub const POLL_START: Duration = Duration::from_millis(1);
292
293/// How long to sleep before checking a child again, and the interval to use next time:
294/// 1 ms doubling to 50 ms, never longer than the time left before the deadline.
295pub fn poll_backoff(current: Duration, remaining: Duration) -> (Duration, Duration) {
296    (
297        current.min(remaining),
298        (current * 2).min(Duration::from_millis(50)),
299    )
300}
301
302/// Executes a command with timeout enforcement, pipe draining, and process group isolation.
303///
304/// # Arguments
305///
306/// * `cmd` - The prepared [`Command`] ready to be configured and spawned.
307/// * `timeout` - Maximum duration allowed before the process and its descendants are terminated.
308///
309/// # Returns
310///
311/// Returns an [`Output`] containing collected stdout, stderr, and the process exit code,
312/// or an error message if the process cannot be spawned or waited on. On timeout, returns
313/// exit code 124 with a notice appended to stderr.
314fn exec_command(cmd: Command, timeout: Duration) -> Result<Output, String> {
315    exec_command_cancellable(cmd, timeout, None)
316}
317
318fn exec_command_cancellable(
319    mut cmd: Command,
320    timeout: Duration,
321    cancel: Option<&CancelHandle>,
322) -> Result<Output, String> {
323    use std::process::Stdio;
324
325    if cancel.is_some_and(CancelHandle::is_cancelled) {
326        return Err("command cancelled".into());
327    }
328
329    // The deadline is ENFORCED, not advisory.
330    // stdin is null so commands that read input (e.g. bare python, git commit, prompts)
331    // do not block forever on an unattended terminal.
332    cmd.stdin(Stdio::null())
333        .stdout(Stdio::piped())
334        .stderr(Stdio::piped());
335
336    // Place the spawned command in its own process group on Unix.
337    // Without this, background grandchildren (e.g., `(sleep 30) & wait`) stay alive
338    // when the immediate child is killed, keeping pipe handles open and causing
339    // the reader threads to hang indefinitely.
340    #[cfg(unix)]
341    {
342        use std::os::unix::process::CommandExt;
343        cmd.process_group(0);
344    }
345
346    let mut child = cmd
347        .spawn()
348        .map_err(|e| format!("cannot run command: {e}"))?;
349
350    if let Some(handle) = cancel {
351        if !handle.register_pgid(child.id() as i32) {
352            kill_child_group(&mut child);
353            return Err("command cancelled".into());
354        }
355    }
356
357    // Drained on background threads: a command that fills the pipe buffer deadlocks against
358    // a parent that only reads after waiting, which turns a noisy command into a hang.
359    let mut so = child.stdout.take().ok_or("no stdout")?;
360    let mut se = child.stderr.take().ok_or("no stderr")?;
361    let t_out = std::thread::spawn(move || {
362        let mut b = String::new();
363        let _ = so.read_to_string(&mut b);
364        b
365    });
366    let t_err = std::thread::spawn(move || {
367        let mut b = String::new();
368        let _ = se.read_to_string(&mut b);
369        b
370    });
371
372    let deadline = std::time::Instant::now() + timeout;
373    let mut poll = POLL_START;
374    let mut was_cancelled = false;
375    let status = loop {
376        match child.try_wait().map_err(|e| format!("wait failed: {e}"))? {
377            Some(s) => break Some(s),
378            None if cancel.is_some_and(CancelHandle::is_cancelled) => {
379                was_cancelled = true;
380                kill_child_group(&mut child);
381                break None;
382            }
383            None if std::time::Instant::now() >= deadline => {
384                kill_child_group(&mut child);
385                break None;
386            }
387            None => {
388                let remaining = deadline.saturating_duration_since(Instant::now());
389                let (sleep, next) = poll_backoff(poll, remaining);
390                std::thread::sleep(sleep);
391                poll = next;
392            }
393        }
394    };
395
396    if let Some(handle) = cancel {
397        handle.clear_pgid();
398    }
399
400    let stdout = t_out.join().unwrap_or_default();
401    let stderr = t_err.join().unwrap_or_default();
402
403    if was_cancelled {
404        return Err("command cancelled".into());
405    }
406
407    match status {
408        Some(s) => Ok(Output {
409            stdout,
410            stderr,
411            exit_code: s.code().unwrap_or(-1),
412        }),
413        // Reported as a failure the model can act on, with the output captured so far --
414        // a killed command that returns nothing tells it only that something went wrong.
415        None => Ok(Output {
416            stdout,
417            stderr: format!("{stderr}\n[killed by blyte after {}s]", timeout.as_secs()),
418            exit_code: 124, // conventional timeout code, as GNU timeout(1) uses
419        }),
420    }
421}
422
423/// Commands run on this machine, in the workspace directory.
424#[derive(Debug, Default, Clone, PartialEq, Eq)]
425pub struct LocalShell {
426    pub profile: Option<Profile>,
427}
428
429#[allow(non_upper_case_globals)]
430pub const LocalShell: LocalShell = LocalShell { profile: None };
431
432impl LocalShell {
433    /// Creates an unsandboxed local shell.
434    pub fn new() -> Self {
435        Self { profile: None }
436    }
437
438    /// Creates a local shell sandboxed with the given profile.
439    pub fn sandboxed(profile: impl Into<Profile>) -> Self {
440        Self {
441            profile: Some(profile.into()),
442        }
443    }
444
445    fn build_command(&self, command: &str, cwd: &Path) -> Result<Command, String> {
446        let full_command = inherited_path_prefix() + command;
447        let command = full_command.as_str();
448        let mut cmd = match &self.profile {
449            Some(Profile::Seatbelt(profile)) => {
450                let mut c = Command::new("/usr/bin/sandbox-exec");
451                c.args(["-p", profile, "bash", "-lc", command]);
452                c
453            }
454            Some(Profile::Landlock(paths)) => {
455                #[cfg(target_os = "linux")]
456                {
457                    let mut c = Command::new("bash");
458                    c.arg("-lc").arg(command);
459                    crate::sandbox::landlock_pre_exec(&mut c, paths, None, false)
460                        .map_err(|e| e.to_string())?;
461                    c
462                }
463                #[cfg(not(target_os = "linux"))]
464                {
465                    let _ = paths;
466                    return Err(std::io::Error::new(
467                        std::io::ErrorKind::Unsupported,
468                        "Landlock is only supported on Linux",
469                    )
470                    .to_string());
471                }
472            }
473            Some(Profile::LandlockOffline(paths)) => {
474                #[cfg(target_os = "linux")]
475                {
476                    let mut c = Command::new("bash");
477                    c.arg("-lc").arg(command);
478                    crate::sandbox::landlock_pre_exec(&mut c, paths, None, true)
479                        .map_err(|e| e.to_string())?;
480                    c
481                }
482                #[cfg(not(target_os = "linux"))]
483                {
484                    let _ = paths;
485                    return Err(std::io::Error::new(
486                        std::io::ErrorKind::Unsupported,
487                        "Landlock is only supported on Linux",
488                    )
489                    .to_string());
490                }
491            }
492            Some(Profile::LandlockConfined {
493                write,
494                read,
495                block_tcp,
496            }) => {
497                #[cfg(target_os = "linux")]
498                {
499                    let mut c = Command::new("bash");
500                    c.arg("-lc").arg(command);
501                    crate::sandbox::landlock_pre_exec(&mut c, write, Some(read), *block_tcp)
502                        .map_err(|e| e.to_string())?;
503                    c
504                }
505                #[cfg(not(target_os = "linux"))]
506                {
507                    let _ = (write, read, block_tcp);
508                    return Err(std::io::Error::new(
509                        std::io::ErrorKind::Unsupported,
510                        "Landlock is only supported on Linux",
511                    )
512                    .to_string());
513                }
514            }
515            None => {
516                let mut c = Command::new("bash");
517                c.arg("-lc").arg(command);
518                c
519            }
520        };
521        cmd.current_dir(cwd);
522        scrub(&mut cmd);
523        Ok(cmd)
524    }
525}
526
527impl Shell for LocalShell {
528    fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
529        let cmd = self.build_command(command, cwd)?;
530        exec_command(cmd, timeout)
531    }
532
533    fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
534        let full_command = inherited_path_prefix() + command;
535        let mut cmd = Command::new("bash");
536        cmd.arg("-lc").arg(&full_command);
537        cmd.current_dir(cwd);
538        scrub_harness(&mut cmd);
539        exec_command(cmd, timeout)
540    }
541
542    fn describe(&self) -> String {
543        "Commands run directly on this machine, in the workspace directory.".into()
544    }
545}
546
547/// A [`LocalShell`] whose running command can be stopped via a [`CancelHandle`].
548#[derive(Debug, Clone)]
549pub struct CancellableLocalShell {
550    pub inner: LocalShell,
551    pub cancel: Arc<CancelHandle>,
552}
553
554impl Shell for CancellableLocalShell {
555    fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
556        let cmd = self.inner.build_command(command, cwd)?;
557        exec_command_cancellable(cmd, timeout, Some(&self.cancel))
558    }
559
560    fn describe(&self) -> String {
561        self.inner.describe()
562    }
563}
564
565/// Commands run inside an already-running container via `docker exec`.
566///
567/// The case the previous harness handled with a prose instruction. Here the model still calls
568/// `bash` and cannot route around it, because there is no host shell in its tool surface.
569#[derive(Debug, Clone)]
570pub struct ContainerShell {
571    pub container_id: String,
572    /// Where the workspace is mounted inside the container.
573    pub workdir: PathBuf,
574}
575
576impl ContainerShell {
577    fn build_command(&self, command: &str) -> Command {
578        let mut cmd = Command::new("docker");
579        cmd.args(["exec", "-i", "-w"])
580            .arg(&self.workdir)
581            .arg(&self.container_id)
582            .args(["bash", "-lc", command]);
583        cmd
584    }
585}
586
587impl Shell for ContainerShell {
588    fn exec(&self, command: &str, _cwd: &Path, timeout: Duration) -> Result<Output, String> {
589        exec_command(self.build_command(command), timeout)
590    }
591
592    fn describe(&self) -> String {
593        format!(
594            "Commands run inside the project container at {}. Project dependencies are \
595             installed there, not on the host.",
596            self.workdir.display()
597        )
598    }
599}
600
601/// A [`ContainerShell`] whose running command can be stopped via a [`CancelHandle`].
602#[derive(Debug, Clone)]
603pub struct CancellableContainerShell {
604    pub inner: ContainerShell,
605    pub cancel: Arc<CancelHandle>,
606}
607
608impl Shell for CancellableContainerShell {
609    fn exec(&self, command: &str, _cwd: &Path, timeout: Duration) -> Result<Output, String> {
610        exec_command_cancellable(
611            self.inner.build_command(command),
612            timeout,
613            Some(&self.cancel),
614        )
615    }
616
617    fn describe(&self) -> String {
618        self.inner.describe()
619    }
620}
621
622/// Single-quote for a POSIX shell.
623fn quote(s: &str) -> String {
624    format!("'{}'", s.replace('\'', r"'\''"))
625}
626
627/// macOS `path_helper` in the login profile reorders PATH.
628pub fn inherited_path_prefix() -> String {
629    match std::env::var("PATH") {
630        Ok(path) if !path.is_empty() => format!("export PATH={}:\"$PATH\"; ", quote(&path)),
631        _ => String::new(),
632    }
633}
634
635/// How to start a session's shell: a login shell, as `bash -lc` gives today.
636#[derive(Debug, Clone)]
637pub enum Launcher {
638    /// `bash -l` on this machine, starting in `root`, optionally sandboxed under a profile.
639    Local {
640        root: PathBuf,
641        profile: Option<Profile>,
642    },
643    /// `bash -l` inside a running container, starting in `workdir`.
644    Container {
645        container_id: String,
646        workdir: PathBuf,
647    },
648}
649
650impl Launcher {
651    fn command(&self) -> std::io::Result<Command> {
652        match self {
653            Launcher::Local { root, profile } => {
654                let mut c = match profile {
655                    Some(Profile::Seatbelt(p)) => {
656                        let mut cmd = Command::new("/usr/bin/sandbox-exec");
657                        cmd.args(["-p", p, "bash", "-l"]);
658                        cmd
659                    }
660                    Some(Profile::Landlock(paths)) => {
661                        #[cfg(target_os = "linux")]
662                        {
663                            let mut cmd = Command::new("bash");
664                            cmd.arg("-l");
665                            crate::sandbox::landlock_pre_exec(&mut cmd, paths, None, false)?;
666                            cmd
667                        }
668                        #[cfg(not(target_os = "linux"))]
669                        {
670                            let _ = paths;
671                            return Err(std::io::Error::new(
672                                std::io::ErrorKind::Unsupported,
673                                "Landlock is only supported on Linux",
674                            ));
675                        }
676                    }
677                    Some(Profile::LandlockOffline(paths)) => {
678                        #[cfg(target_os = "linux")]
679                        {
680                            let mut cmd = Command::new("bash");
681                            cmd.arg("-l");
682                            crate::sandbox::landlock_pre_exec(&mut cmd, paths, None, true)?;
683                            cmd
684                        }
685                        #[cfg(not(target_os = "linux"))]
686                        {
687                            let _ = paths;
688                            return Err(std::io::Error::new(
689                                std::io::ErrorKind::Unsupported,
690                                "Landlock is only supported on Linux",
691                            ));
692                        }
693                    }
694                    Some(Profile::LandlockConfined {
695                        write,
696                        read,
697                        block_tcp,
698                    }) => {
699                        #[cfg(target_os = "linux")]
700                        {
701                            let mut cmd = Command::new("bash");
702                            cmd.arg("-l");
703                            crate::sandbox::landlock_pre_exec(
704                                &mut cmd,
705                                write,
706                                Some(read),
707                                *block_tcp,
708                            )?;
709                            cmd
710                        }
711                        #[cfg(not(target_os = "linux"))]
712                        {
713                            let _ = (write, read, block_tcp);
714                            return Err(std::io::Error::new(
715                                std::io::ErrorKind::Unsupported,
716                                "Landlock is only supported on Linux",
717                            ));
718                        }
719                    }
720                    None => {
721                        let mut cmd = Command::new("bash");
722                        cmd.arg("-l");
723                        cmd
724                    }
725                };
726                c.current_dir(root);
727                scrub(&mut c);
728                Ok(c)
729            }
730            Launcher::Container {
731                container_id,
732                workdir,
733            } => {
734                let mut c = Command::new("docker");
735                c.args(["exec", "-i", "-w"])
736                    .arg(workdir)
737                    .arg(container_id)
738                    .args(["bash", "-l"]);
739                Ok(c)
740            }
741        }
742    }
743
744    /// The process-per-command executor this launcher replaces, used whenever a session
745    /// cannot start.
746    fn fallback(&self) -> Box<dyn Shell> {
747        match self {
748            Launcher::Local { profile, .. } => match profile {
749                Some(p) => Box::new(LocalShell::sandboxed(p.clone())),
750                None => Box::new(LocalShell),
751            },
752            Launcher::Container {
753                container_id,
754                workdir,
755            } => Box::new(ContainerShell {
756                container_id: container_id.clone(),
757                workdir: workdir.clone(),
758            }),
759        }
760    }
761}
762
763/// How a session command ended.
764pub enum RunResult {
765    Done(Output),
766    /// The deadline passed; the session must be killed. Paths hold what the command wrote.
767    TimedOut {
768        out: String,
769        err: String,
770    },
771    /// The shell ended before reporting (e.g. the command ran `exit`).
772    Died {
773        out: String,
774        err: String,
775    },
776}
777
778/// One long-lived `bash -l`. A command arrives through a heredoc read by the `read` builtin; its
779/// stdout and stderr go to their own files and come back with one `printf` behind a header of
780/// byte lengths. Only the command itself runs as a process: the previous protocol spawned about
781/// six helpers per command (`base64`, `tr`, `rm`), about 25 ms on macOS.
782pub struct Session {
783    child: Child,
784    stdin: ChildStdin,
785    chunks: Receiver<Vec<u8>>,
786    buf: Vec<u8>,
787    tmp: String,
788    next: u64,
789    nonce: String,
790}
791
792const READY: &str = "__BLYTE_READY__ ";
793
794/// A per-process token for heredoc delimiters, so no command or file content can end one early.
795fn nonce() -> String {
796    let t = std::time::SystemTime::now()
797        .duration_since(std::time::UNIX_EPOCH)
798        .map(|d| d.as_nanos())
799        .unwrap_or(0);
800    format!("{t:x}{:x}", std::process::id())
801}
802
803enum ReadErr {
804    Timeout,
805    Closed,
806}
807
808impl Session {
809    pub fn start(launcher: &Launcher) -> Result<Session, String> {
810        let mut cmd = launcher
811            .command()
812            .map_err(|e| format!("cannot start a shell session: {e}"))?;
813        cmd.stdin(Stdio::piped())
814            .stdout(Stdio::piped())
815            .stderr(Stdio::null());
816        #[cfg(unix)]
817        {
818            use std::os::unix::process::CommandExt;
819            cmd.process_group(0);
820        }
821        let mut child = cmd
822            .spawn()
823            .map_err(|e| format!("cannot start a shell session: {e}"))?;
824        let stdin = child.stdin.take().ok_or("no stdin")?;
825        let mut stdout = child.stdout.take().ok_or("no stdout")?;
826        let (tx, rx) = mpsc::channel();
827        std::thread::spawn(move || {
828            let mut chunk = vec![0u8; 64 * 1024];
829            loop {
830                match stdout.read(&mut chunk) {
831                    Ok(0) | Err(_) => break,
832                    Ok(n) => {
833                        if tx.send(chunk[..n].to_vec()).is_err() {
834                            break;
835                        }
836                    }
837                }
838            }
839        });
840        let mut s = Session {
841            child,
842            stdin,
843            chunks: rx,
844            buf: Vec::new(),
845            tmp: String::new(),
846            next: 0,
847            nonce: nonce(),
848        };
849        let init = match launcher {
850            Launcher::Local { .. } => inherited_path_prefix(),
851            Launcher::Container { .. } => String::new(),
852        };
853        s.send(&format!(
854            "{init}__blyte_t=$(mktemp -d 2>/dev/null || {{ mkdir -p /tmp/blyte.$$ && echo /tmp/blyte.$$; }}); \
855             echo \"__BLYTE_READY__ $__blyte_t\"\n",
856        ))?;
857        let deadline = Instant::now() + Duration::from_secs(30);
858        loop {
859            match s.read_line(deadline) {
860                Ok(l) if l.starts_with(READY) => {
861                    s.tmp = l[READY.len()..].trim().to_string();
862                    return Ok(s);
863                }
864                Ok(_) => continue, // profile output on stdout
865                Err(_) => {
866                    s.kill();
867                    return Err("the shell session did not start".into());
868                }
869            }
870        }
871    }
872
873    fn send(&mut self, script: &str) -> Result<(), String> {
874        self.stdin
875            .write_all(script.as_bytes())
876            .and_then(|_| self.stdin.flush())
877            .map_err(|e| format!("the shell session closed: {e}"))
878    }
879
880    fn fill(&mut self, deadline: Instant) -> Result<(), ReadErr> {
881        match self
882            .chunks
883            .recv_timeout(deadline.saturating_duration_since(Instant::now()))
884        {
885            Ok(c) => {
886                self.buf.extend_from_slice(&c);
887                Ok(())
888            }
889            Err(RecvTimeoutError::Timeout) => Err(ReadErr::Timeout),
890            Err(RecvTimeoutError::Disconnected) => Err(ReadErr::Closed),
891        }
892    }
893
894    /// The next line of session output, without its newline.
895    fn read_line(&mut self, deadline: Instant) -> Result<String, ReadErr> {
896        loop {
897            if let Some(i) = self.buf.iter().position(|&b| b == b'\n') {
898                let line: Vec<u8> = self.buf.drain(..=i).collect();
899                return Ok(String::from_utf8_lossy(&line[..i]).into_owned());
900            }
901            self.fill(deadline)?;
902        }
903    }
904
905    /// Exactly `n` bytes of session output.
906    fn read_exact(&mut self, n: usize, deadline: Instant) -> Result<Vec<u8>, ReadErr> {
907        while self.buf.len() < n {
908            self.fill(deadline)?;
909        }
910        Ok(self.buf.drain(..n).collect())
911    }
912
913    /// Kill the session and everything it started.
914    pub fn kill(&mut self) {
915        #[cfg(unix)]
916        {
917            let pgid = self.child.id() as i32;
918            if pgid > 0 {
919                unsafe {
920                    libc::kill(-pgid, libc::SIGKILL);
921                }
922            }
923        }
924        let _ = self.child.kill();
925        let _ = self.child.wait();
926    }
927
928    /// Run `command` to completion. `cwd: Some(dir)` runs it in a subshell in `dir`, so nothing
929    /// it does persists; `None` runs it in the session itself, so `cd` and `export` carry over.
930    pub fn run(&mut self, command: &str, cwd: Option<&Path>, timeout: Duration) -> RunResult {
931        let id = self.next;
932        self.next += 1;
933        let (out, err) = (
934            format!("{}/{id}.o", self.tmp),
935            format!("{}/{id}.e", self.tmp),
936        );
937        let (qo, qe, qt) = (quote(&out), quote(&err), quote(&self.tmp));
938        let delim = format!("__BLYTE_CMD_{id}_{}__", self.nonce);
939        let body = match cwd {
940            Some(d) => format!(
941                "( cd {} && eval \"$__blyte_c\" )",
942                quote(&d.to_string_lossy())
943            ),
944            None => "eval \"$__blyte_c\"".to_string(),
945        };
946        // `|| true` on the protocol's own reads: a model's `set -e` must not end the session
947        // because `read` reports end of input. LC_ALL=C makes `${#var}` count bytes; the
948        // model's LC_ALL is put back afterwards.
949        // Recreate tmp before each command so output redirects succeed even if a command deleted it.
950        let script = format!(
951            "IFS= read -r -d '' __blyte_c <<'{delim}' || true\n{command}\n{delim}\n\
952             [ -d {qt} ] || mkdir -p {qt} 2>/dev/null; {body} </dev/null >{qo} 2>{qe}; __blyte_r=$?; \
953             IFS= read -r -d '' __blyte_o <{qo} || true; \
954             IFS= read -r -d '' __blyte_e <{qe} || true; \
955             __blyte_l=${{LC_ALL-__blyte_unset__}}; LC_ALL=C; \
956             printf '__BLYTE_{id}__ %s %s %s\\n%s%s' \"$__blyte_r\" \"${{#__blyte_o}}\" \
957             \"${{#__blyte_e}}\" \"$__blyte_o\" \"$__blyte_e\"; \
958             if [ \"$__blyte_l\" = __blyte_unset__ ]; then unset LC_ALL; else LC_ALL=$__blyte_l; fi; \
959             unset __blyte_c __blyte_o __blyte_e __blyte_l\n"
960        );
961        if self.send(&script).is_err() {
962            return RunResult::Died { out, err };
963        }
964        let marker = format!("__BLYTE_{id}__ ");
965        let deadline = Instant::now() + timeout;
966        let fail = |e: ReadErr, out: String, err: String| match e {
967            ReadErr::Timeout => RunResult::TimedOut { out, err },
968            ReadErr::Closed => RunResult::Died { out, err },
969        };
970        let header = loop {
971            match self.read_line(deadline) {
972                Ok(l) => {
973                    if let Some(rest) = l.strip_prefix(&marker) {
974                        break rest.to_string();
975                    }
976                }
977                Err(e) => return fail(e, out, err),
978            }
979        };
980        let mut f = header.split(' ');
981        let exit_code = f.next().and_then(|x| x.parse().ok()).unwrap_or(-1);
982        let no: usize = f.next().and_then(|x| x.parse().ok()).unwrap_or(0);
983        let ne: usize = f.next().and_then(|x| x.parse().ok()).unwrap_or(0);
984        match self.read_exact(no + ne, deadline) {
985            Ok(bytes) => RunResult::Done(Output {
986                stdout: String::from_utf8_lossy(&bytes[..no]).into_owned(),
987                stderr: String::from_utf8_lossy(&bytes[no..]).into_owned(),
988                exit_code,
989            }),
990            Err(e) => fail(e, out, err),
991        }
992    }
993
994    /// Remove the session's scratch directory, then end it.
995    fn close(&mut self) {
996        let _ = self.send(&format!("rm -rf {}; exit 0\n", quote(&self.tmp)));
997        let deadline = Instant::now() + Duration::from_millis(300);
998        while Instant::now() < deadline {
999            if let Ok(Some(_)) = self.child.try_wait() {
1000                return;
1001            }
1002            std::thread::sleep(Duration::from_millis(10));
1003        }
1004        self.kill();
1005    }
1006}
1007
1008/// Commands through persistent sessions instead of a process each: one session for the
1009/// harness's own commands (each in a fresh subshell in the directory asked for, never affected
1010/// by the model's) and one for the model's `bash` (its `cd` and `export` carry over). Falls back
1011/// to a process per command, exactly as [`LocalShell`] / [`ContainerShell`], when a session
1012/// cannot start.
1013///
1014/// A `docker exec` per call cost 60-110 ms and a container `edit` about 300 ms; a session round
1015/// trip costs a few milliseconds (harness_bench, 2026-09-24).
1016pub struct PersistentShell {
1017    launcher: Launcher,
1018    harness: Mutex<Option<Session>>,
1019    user: Mutex<Option<Session>>,
1020    fallback: Box<dyn Shell>,
1021}
1022
1023impl PersistentShell {
1024    pub fn new(launcher: Launcher) -> Self {
1025        let fallback = launcher.fallback();
1026        Self {
1027            launcher,
1028            harness: Mutex::new(None),
1029            user: Mutex::new(None),
1030            fallback,
1031        }
1032    }
1033
1034    pub fn local(root: PathBuf) -> Self {
1035        Self::new(Launcher::Local {
1036            root,
1037            profile: None,
1038        })
1039    }
1040
1041    pub fn local_sandboxed(root: PathBuf, profile: impl Into<Profile>) -> Self {
1042        Self::new(Launcher::Local {
1043            root,
1044            profile: Some(profile.into()),
1045        })
1046    }
1047
1048    pub fn sandboxed(root: PathBuf, profile: impl Into<Profile>) -> Self {
1049        Self::local_sandboxed(root, profile)
1050    }
1051
1052    pub fn container(container_id: String, workdir: PathBuf) -> Self {
1053        Self::new(Launcher::Container {
1054            container_id,
1055            workdir,
1056        })
1057    }
1058
1059    /// Whether the harness session is (or can be) running. False means every call falls back.
1060    pub fn is_persistent(&self) -> bool {
1061        let mut g = self.harness.lock().unwrap_or_else(|e| e.into_inner());
1062        if g.is_none() {
1063            *g = Session::start(&self.launcher).ok();
1064        }
1065        g.is_some()
1066    }
1067
1068    /// Run through `slot`'s session, starting it if needed. `None` when no session can start.
1069    fn run(
1070        &self,
1071        slot: &Mutex<Option<Session>>,
1072        command: &str,
1073        cwd: Option<&Path>,
1074        timeout: Duration,
1075    ) -> Option<Result<Output, String>> {
1076        let mut g = slot.lock().unwrap_or_else(|e| e.into_inner());
1077        if g.is_none() {
1078            *g = Session::start(&self.launcher).ok();
1079        }
1080        let session = g.as_mut()?;
1081        let (out, err, note, code) = match session.run(command, cwd, timeout) {
1082            RunResult::Done(o) => return Some(Ok(o)),
1083            RunResult::TimedOut { out, err } => (
1084                out,
1085                err,
1086                format!("\n[killed by blyte after {}s]", timeout.as_secs()),
1087                124,
1088            ),
1089            RunResult::Died { out, err } => (
1090                out,
1091                err,
1092                "[the shell exited; the next command starts a fresh shell in the workspace root]"
1093                    .to_string(),
1094                1,
1095            ),
1096        };
1097        session.kill();
1098        *g = None;
1099        drop(g);
1100        // What the command wrote before it was cut short, read through a fresh process.
1101        let cat = |p: &str| {
1102            self.fallback
1103                .exec(
1104                    &format!("cat -- {q} 2>/dev/null; rm -f -- {q}", q = quote(p)),
1105                    Path::new("/"),
1106                    Duration::from_secs(30),
1107                )
1108                .map(|o| o.stdout)
1109                .unwrap_or_default()
1110        };
1111        let (stdout, stderr) = (cat(&out), cat(&err));
1112        Some(Ok(Output {
1113            stdout,
1114            stderr: format!("{stderr}{note}"),
1115            exit_code: code,
1116        }))
1117    }
1118}
1119
1120impl Shell for PersistentShell {
1121    fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
1122        self.run(&self.harness, command, Some(cwd), timeout)
1123            .unwrap_or_else(|| self.fallback.exec(command, cwd, timeout))
1124    }
1125
1126    fn exec_user(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
1127        self.run(&self.user, command, None, timeout)
1128            .unwrap_or_else(|| self.fallback.exec(command, cwd, timeout))
1129    }
1130
1131    fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
1132        self.fallback.exec_host(command, cwd, timeout)
1133    }
1134
1135    fn describe(&self) -> String {
1136        format!(
1137            "{} Your `bash` commands share one shell session: `cd` and `export` carry over to \
1138             later commands. File tools always resolve paths from the workspace root.",
1139            self.fallback.describe()
1140        )
1141    }
1142}
1143
1144impl Drop for PersistentShell {
1145    fn drop(&mut self) {
1146        for slot in [&self.harness, &self.user] {
1147            if let Some(mut s) = slot.lock().unwrap_or_else(|e| e.into_inner()).take() {
1148                s.close();
1149            }
1150        }
1151    }
1152}