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