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