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
140pub const MODEL_SHELL_ENV: &str = "BLYTE_MODEL_SHELL";
141
142pub fn model_shell_refusal_message(command: &str) -> String {
143    format!(
144        "error: blyte {command} writes a record only the user or the harness may write, and cannot be run from a model's shell"
145    )
146}
147
148fn scrub_harness(cmd: &mut Command) {
149    cmd.env_remove(MODEL_SHELL_ENV);
150    for name in HARNESS_ENV {
151        cmd.env_remove(name);
152    }
153    for (name, _) in std::env::vars_os() {
154        let n = name.to_string_lossy();
155        if n.starts_with("BLYTE_") && n != "BLYTE_SESSION" {
156            cmd.env_remove(&name);
157        }
158    }
159}
160
161/// Remove the harness's own variables and credential-looking variables from a command about to run on this machine.
162fn scrub(cmd: &mut Command) {
163    scrub_harness(cmd);
164    for name in withheld_env() {
165        cmd.env_remove(name);
166    }
167}
168
169#[derive(Debug, Clone, PartialEq, Eq)]
170pub struct Output {
171    pub stdout: String,
172    pub stderr: String,
173    pub exit_code: i32,
174}
175
176impl Output {
177    /// stdout and stderr as the model should see them: interleaved is not reconstructable
178    /// after the fact, so stdout first then stderr, which is how a terminal usually reads.
179    pub fn merged(&self) -> String {
180        format!("{}{}", self.stdout, self.stderr)
181    }
182}
183
184pub trait Shell: Send + Sync {
185    /// Run a command to completion. Blocking by contract -- see `tools` for why.
186    fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String>;
187
188    /// Run a command the **model** issued. Where the executor keeps a persistent session, its
189    /// `cd` and `export` carry over to the model's next command, as in a terminal. The default
190    /// is `exec`: a fresh process in `cwd`.
191    fn exec_user(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
192        self.exec(command, cwd, timeout)
193    }
194
195    fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
196        let _ = (command, cwd, timeout);
197        Err("this shell cannot run a command outside the sandbox".into())
198    }
199
200    /// Human-readable description of where commands land, for the system prompt.
201    /// A worker that knows it is inside a container does not go looking for the host.
202    fn describe(&self) -> String;
203
204    /// Which binaries exist **in the execution environment**, not on the orchestrator's host.
205    fn available_binaries(&self, cwd: &Path, candidates: &[&'static str]) -> Vec<String> {
206        // One probe rather than N: a remote or containerised shell pays a round trip per call,
207        // and sixteen of them before the first turn is a poor way to start.
208        let probe = candidates
209            .iter()
210            .map(|b| format!("command -v {b} >/dev/null 2>&1 && echo {b}"))
211            .collect::<Vec<_>>()
212            .join("; ");
213        match self.exec(&probe, cwd, Duration::from_secs(30)) {
214            Ok(o) => o
215                .stdout
216                .lines()
217                .map(|l| l.trim().to_string())
218                .filter(|l| !l.is_empty())
219                .collect(),
220            Err(_) => Vec::new(),
221        }
222    }
223}
224
225/// Cooperative cancellation handle that terminates an active command's process group.
226#[derive(Debug, Default)]
227pub struct CancelHandle {
228    cancelled: AtomicBool,
229    active_pgid: Mutex<Option<i32>>,
230}
231
232impl CancelHandle {
233    pub fn new() -> Self {
234        Self::default()
235    }
236
237    pub fn is_cancelled(&self) -> bool {
238        self.cancelled.load(Ordering::SeqCst)
239    }
240
241    pub fn flag(&self) -> &AtomicBool {
242        &self.cancelled
243    }
244
245    pub fn cancel(&self) {
246        let pgid = {
247            let guard = self.active_pgid.lock().unwrap_or_else(|e| e.into_inner());
248            self.cancelled.store(true, Ordering::SeqCst);
249            *guard
250        };
251        #[cfg(unix)]
252        if let Some(pgid) = pgid {
253            if pgid > 0 {
254                unsafe {
255                    libc::kill(-pgid, libc::SIGKILL);
256                }
257            }
258        }
259        #[cfg(not(unix))]
260        let _ = pgid;
261    }
262
263    fn register_pgid(&self, pgid: i32) -> bool {
264        let mut guard = self.active_pgid.lock().unwrap_or_else(|e| e.into_inner());
265        if self.cancelled.load(Ordering::SeqCst) {
266            return false;
267        }
268        *guard = Some(pgid);
269        true
270    }
271
272    fn clear_pgid(&self) {
273        let mut guard = self.active_pgid.lock().unwrap_or_else(|e| e.into_inner());
274        *guard = None;
275    }
276}
277
278fn kill_child_group(child: &mut Child) {
279    // On Unix, kill the entire process group with a negative PGID.
280    // This ensures all child and grandchild processes are terminated simultaneously,
281    // releasing standard stream pipe handles so reader threads unblock promptly.
282    #[cfg(unix)]
283    {
284        let pgid = child.id() as i32;
285        if pgid > 0 {
286            unsafe {
287                libc::kill(-pgid, libc::SIGKILL);
288            }
289        } else {
290            let _ = child.kill();
291        }
292    }
293    #[cfg(not(unix))]
294    {
295        let _ = child.kill();
296    }
297    let _ = child.wait();
298}
299
300pub const POLL_START: Duration = Duration::from_millis(1);
301
302/// How long to sleep before checking a child again, and the interval to use next time:
303/// 1 ms doubling to 50 ms, never longer than the time left before the deadline.
304pub fn poll_backoff(current: Duration, remaining: Duration) -> (Duration, Duration) {
305    (
306        current.min(remaining),
307        (current * 2).min(Duration::from_millis(50)),
308    )
309}
310
311/// Executes a command with timeout enforcement, pipe draining, and process group isolation.
312///
313/// # Arguments
314///
315/// * `cmd` - The prepared [`Command`] ready to be configured and spawned.
316/// * `timeout` - Maximum duration allowed before the process and its descendants are terminated.
317///
318/// # Returns
319///
320/// Returns an [`Output`] containing collected stdout, stderr, and the process exit code,
321/// or an error message if the process cannot be spawned or waited on. On timeout, returns
322/// exit code 124 with a notice appended to stderr.
323fn exec_command(cmd: Command, timeout: Duration) -> Result<Output, String> {
324    exec_command_cancellable(cmd, timeout, None)
325}
326
327fn exec_command_cancellable(
328    mut cmd: Command,
329    timeout: Duration,
330    cancel: Option<&CancelHandle>,
331) -> Result<Output, String> {
332    use std::process::Stdio;
333
334    if cancel.is_some_and(CancelHandle::is_cancelled) {
335        return Err("command cancelled".into());
336    }
337
338    // The deadline is ENFORCED, not advisory.
339    // stdin is null so commands that read input (e.g. bare python, git commit, prompts)
340    // do not block forever on an unattended terminal.
341    cmd.stdin(Stdio::null())
342        .stdout(Stdio::piped())
343        .stderr(Stdio::piped());
344
345    // Place the spawned command in its own process group on Unix.
346    // Without this, background grandchildren (e.g., `(sleep 30) & wait`) stay alive
347    // when the immediate child is killed, keeping pipe handles open and causing
348    // the reader threads to hang indefinitely.
349    #[cfg(unix)]
350    {
351        use std::os::unix::process::CommandExt;
352        cmd.process_group(0);
353    }
354
355    let mut child = cmd
356        .spawn()
357        .map_err(|e| format!("cannot run command: {e}"))?;
358
359    if let Some(handle) = cancel {
360        if !handle.register_pgid(child.id() as i32) {
361            kill_child_group(&mut child);
362            return Err("command cancelled".into());
363        }
364    }
365
366    // Drained on background threads: a command that fills the pipe buffer deadlocks against
367    // a parent that only reads after waiting, which turns a noisy command into a hang.
368    let mut so = child.stdout.take().ok_or("no stdout")?;
369    let mut se = child.stderr.take().ok_or("no stderr")?;
370    let t_out = std::thread::spawn(move || {
371        let mut b = String::new();
372        let _ = so.read_to_string(&mut b);
373        b
374    });
375    let t_err = std::thread::spawn(move || {
376        let mut b = String::new();
377        let _ = se.read_to_string(&mut b);
378        b
379    });
380
381    let deadline = std::time::Instant::now() + timeout;
382    let mut poll = POLL_START;
383    let mut was_cancelled = false;
384    let status = loop {
385        match child.try_wait().map_err(|e| format!("wait failed: {e}"))? {
386            Some(s) => break Some(s),
387            None if cancel.is_some_and(CancelHandle::is_cancelled) => {
388                was_cancelled = true;
389                kill_child_group(&mut child);
390                break None;
391            }
392            None if std::time::Instant::now() >= deadline => {
393                kill_child_group(&mut child);
394                break None;
395            }
396            None => {
397                let remaining = deadline.saturating_duration_since(Instant::now());
398                let (sleep, next) = poll_backoff(poll, remaining);
399                std::thread::sleep(sleep);
400                poll = next;
401            }
402        }
403    };
404
405    if let Some(handle) = cancel {
406        handle.clear_pgid();
407    }
408
409    let stdout = t_out.join().unwrap_or_default();
410    let stderr = t_err.join().unwrap_or_default();
411
412    if was_cancelled {
413        return Err("command cancelled".into());
414    }
415
416    match status {
417        Some(s) => Ok(Output {
418            stdout,
419            stderr,
420            exit_code: s.code().unwrap_or(-1),
421        }),
422        // Reported as a failure the model can act on, with the output captured so far --
423        // a killed command that returns nothing tells it only that something went wrong.
424        None => Ok(Output {
425            stdout,
426            stderr: format!("{stderr}\n[killed by blyte after {}s]", timeout.as_secs()),
427            exit_code: 124, // conventional timeout code, as GNU timeout(1) uses
428        }),
429    }
430}
431
432/// Commands run on this machine, in the workspace directory.
433#[derive(Debug, Default, Clone, PartialEq, Eq)]
434pub struct LocalShell {
435    pub profile: Option<Profile>,
436}
437
438#[allow(non_upper_case_globals)]
439pub const LocalShell: LocalShell = LocalShell { profile: None };
440
441impl LocalShell {
442    /// Creates an unsandboxed local shell.
443    pub fn new() -> Self {
444        Self { profile: None }
445    }
446
447    /// Creates a local shell sandboxed with the given profile.
448    pub fn sandboxed(profile: impl Into<Profile>) -> Self {
449        Self {
450            profile: Some(profile.into()),
451        }
452    }
453
454    fn build_command(&self, command: &str, cwd: &Path) -> Result<Command, String> {
455        let full_command = inherited_path_prefix() + command;
456        let command = full_command.as_str();
457        let mut cmd = match &self.profile {
458            Some(Profile::Seatbelt(profile)) => {
459                let mut c = Command::new("/usr/bin/sandbox-exec");
460                c.args(["-p", profile, "bash", "-lc", command]);
461                c
462            }
463            Some(Profile::Landlock(paths)) => {
464                #[cfg(target_os = "linux")]
465                {
466                    let mut c = Command::new("bash");
467                    c.arg("-lc").arg(command);
468                    crate::sandbox::landlock_pre_exec(&mut c, paths, None, false)
469                        .map_err(|e| e.to_string())?;
470                    c
471                }
472                #[cfg(not(target_os = "linux"))]
473                {
474                    let _ = paths;
475                    return Err(std::io::Error::new(
476                        std::io::ErrorKind::Unsupported,
477                        "Landlock is only supported on Linux",
478                    )
479                    .to_string());
480                }
481            }
482            Some(Profile::LandlockOffline(paths)) => {
483                #[cfg(target_os = "linux")]
484                {
485                    let mut c = Command::new("bash");
486                    c.arg("-lc").arg(command);
487                    crate::sandbox::landlock_pre_exec(&mut c, paths, None, true)
488                        .map_err(|e| e.to_string())?;
489                    c
490                }
491                #[cfg(not(target_os = "linux"))]
492                {
493                    let _ = paths;
494                    return Err(std::io::Error::new(
495                        std::io::ErrorKind::Unsupported,
496                        "Landlock is only supported on Linux",
497                    )
498                    .to_string());
499                }
500            }
501            Some(Profile::LandlockConfined {
502                write,
503                read,
504                block_tcp,
505            }) => {
506                #[cfg(target_os = "linux")]
507                {
508                    let mut c = Command::new("bash");
509                    c.arg("-lc").arg(command);
510                    crate::sandbox::landlock_pre_exec(&mut c, write, Some(read), *block_tcp)
511                        .map_err(|e| e.to_string())?;
512                    c
513                }
514                #[cfg(not(target_os = "linux"))]
515                {
516                    let _ = (write, read, block_tcp);
517                    return Err(std::io::Error::new(
518                        std::io::ErrorKind::Unsupported,
519                        "Landlock is only supported on Linux",
520                    )
521                    .to_string());
522                }
523            }
524            None => {
525                let mut c = Command::new("bash");
526                c.arg("-lc").arg(command);
527                c
528            }
529        };
530        cmd.current_dir(cwd);
531        scrub(&mut cmd);
532        Ok(cmd)
533    }
534}
535
536impl Shell for LocalShell {
537    fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
538        let cmd = self.build_command(command, cwd)?;
539        exec_command(cmd, timeout)
540    }
541
542    fn exec_user(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
543        let mut cmd = self.build_command(command, cwd)?;
544        cmd.env(MODEL_SHELL_ENV, "1");
545        exec_command(cmd, timeout)
546    }
547
548    fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
549        let full_command = inherited_path_prefix() + command;
550        let mut cmd = Command::new("bash");
551        cmd.arg("-lc").arg(&full_command);
552        cmd.current_dir(cwd);
553        scrub_harness(&mut cmd);
554        cmd.env(MODEL_SHELL_ENV, "1");
555        exec_command(cmd, timeout)
556    }
557
558    fn describe(&self) -> String {
559        "Commands run directly on this machine, in the workspace directory.".into()
560    }
561}
562
563/// A [`LocalShell`] whose running command can be stopped via a [`CancelHandle`].
564#[derive(Debug, Clone)]
565pub struct CancellableLocalShell {
566    pub inner: LocalShell,
567    pub cancel: Arc<CancelHandle>,
568}
569
570impl Shell for CancellableLocalShell {
571    fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
572        let cmd = self.inner.build_command(command, cwd)?;
573        exec_command_cancellable(cmd, timeout, Some(&self.cancel))
574    }
575
576    fn exec_user(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
577        let mut cmd = self.inner.build_command(command, cwd)?;
578        cmd.env(MODEL_SHELL_ENV, "1");
579        exec_command_cancellable(cmd, timeout, Some(&self.cancel))
580    }
581
582    fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
583        let full_command = inherited_path_prefix() + command;
584        let mut cmd = Command::new("bash");
585        cmd.arg("-lc").arg(&full_command);
586        cmd.current_dir(cwd);
587        scrub_harness(&mut cmd);
588        cmd.env(MODEL_SHELL_ENV, "1");
589        exec_command_cancellable(cmd, timeout, Some(&self.cancel))
590    }
591
592    fn describe(&self) -> String {
593        self.inner.describe()
594    }
595}
596
597/// Commands run inside an already-running container via `docker exec`.
598///
599/// The case the previous harness handled with a prose instruction. Here the model still calls
600/// `bash` and cannot route around it, because there is no host shell in its tool surface.
601#[derive(Debug, Clone)]
602pub struct ContainerShell {
603    pub container_id: String,
604    /// Where the workspace is mounted inside the container.
605    pub workdir: PathBuf,
606}
607
608impl ContainerShell {
609    fn build_command(&self, command: &str, model_shell: bool) -> Command {
610        let mut cmd = Command::new("docker");
611        cmd.args(["exec", "-i"]);
612        if model_shell {
613            cmd.args(["-e", "BLYTE_MODEL_SHELL=1"]);
614        }
615        cmd.arg("-w")
616            .arg(&self.workdir)
617            .arg(&self.container_id)
618            .args(["bash", "-lc", command]);
619        cmd
620    }
621}
622
623impl Shell for ContainerShell {
624    fn exec(&self, command: &str, _cwd: &Path, timeout: Duration) -> Result<Output, String> {
625        exec_command(self.build_command(command, false), timeout)
626    }
627
628    fn exec_user(&self, command: &str, _cwd: &Path, timeout: Duration) -> Result<Output, String> {
629        exec_command(self.build_command(command, true), timeout)
630    }
631
632    fn describe(&self) -> String {
633        format!(
634            "Commands run inside the project container at {}. Project dependencies are \
635             installed there, not on the host.",
636            self.workdir.display()
637        )
638    }
639}
640
641/// A [`ContainerShell`] whose running command can be stopped via a [`CancelHandle`].
642#[derive(Debug, Clone)]
643pub struct CancellableContainerShell {
644    pub inner: ContainerShell,
645    pub cancel: Arc<CancelHandle>,
646}
647
648impl Shell for CancellableContainerShell {
649    fn exec(&self, command: &str, _cwd: &Path, timeout: Duration) -> Result<Output, String> {
650        exec_command_cancellable(
651            self.inner.build_command(command, false),
652            timeout,
653            Some(&self.cancel),
654        )
655    }
656
657    fn exec_user(&self, command: &str, _cwd: &Path, timeout: Duration) -> Result<Output, String> {
658        exec_command_cancellable(
659            self.inner.build_command(command, true),
660            timeout,
661            Some(&self.cancel),
662        )
663    }
664
665    fn describe(&self) -> String {
666        self.inner.describe()
667    }
668}
669
670/// Single-quote for a POSIX shell.
671fn quote(s: &str) -> String {
672    format!("'{}'", s.replace('\'', r"'\''"))
673}
674
675/// macOS `path_helper` in the login profile reorders PATH.
676pub fn inherited_path_prefix() -> String {
677    match std::env::var("PATH") {
678        Ok(path) if !path.is_empty() => format!("export PATH={}:\"$PATH\"; ", quote(&path)),
679        _ => String::new(),
680    }
681}
682
683/// How to start a session's shell: a login shell, as `bash -lc` gives today.
684#[derive(Debug, Clone)]
685pub enum Launcher {
686    /// `bash -l` on this machine, starting in `root`, optionally sandboxed under a profile.
687    Local {
688        root: PathBuf,
689        profile: Option<Profile>,
690    },
691    /// `bash -l` inside a running container, starting in `workdir`.
692    Container {
693        container_id: String,
694        workdir: PathBuf,
695    },
696}
697
698impl Launcher {
699    fn command(&self, model_shell: bool) -> std::io::Result<Command> {
700        match self {
701            Launcher::Local { root, profile } => {
702                let mut c = match profile {
703                    Some(Profile::Seatbelt(p)) => {
704                        let mut cmd = Command::new("/usr/bin/sandbox-exec");
705                        cmd.args(["-p", p, "bash", "-l"]);
706                        cmd
707                    }
708                    Some(Profile::Landlock(paths)) => {
709                        #[cfg(target_os = "linux")]
710                        {
711                            let mut cmd = Command::new("bash");
712                            cmd.arg("-l");
713                            crate::sandbox::landlock_pre_exec(&mut cmd, paths, None, false)?;
714                            cmd
715                        }
716                        #[cfg(not(target_os = "linux"))]
717                        {
718                            let _ = paths;
719                            return Err(std::io::Error::new(
720                                std::io::ErrorKind::Unsupported,
721                                "Landlock is only supported on Linux",
722                            ));
723                        }
724                    }
725                    Some(Profile::LandlockOffline(paths)) => {
726                        #[cfg(target_os = "linux")]
727                        {
728                            let mut cmd = Command::new("bash");
729                            cmd.arg("-l");
730                            crate::sandbox::landlock_pre_exec(&mut cmd, paths, None, true)?;
731                            cmd
732                        }
733                        #[cfg(not(target_os = "linux"))]
734                        {
735                            let _ = paths;
736                            return Err(std::io::Error::new(
737                                std::io::ErrorKind::Unsupported,
738                                "Landlock is only supported on Linux",
739                            ));
740                        }
741                    }
742                    Some(Profile::LandlockConfined {
743                        write,
744                        read,
745                        block_tcp,
746                    }) => {
747                        #[cfg(target_os = "linux")]
748                        {
749                            let mut cmd = Command::new("bash");
750                            cmd.arg("-l");
751                            crate::sandbox::landlock_pre_exec(
752                                &mut cmd,
753                                write,
754                                Some(read),
755                                *block_tcp,
756                            )?;
757                            cmd
758                        }
759                        #[cfg(not(target_os = "linux"))]
760                        {
761                            let _ = (write, read, block_tcp);
762                            return Err(std::io::Error::new(
763                                std::io::ErrorKind::Unsupported,
764                                "Landlock is only supported on Linux",
765                            ));
766                        }
767                    }
768                    None => {
769                        let mut cmd = Command::new("bash");
770                        cmd.arg("-l");
771                        cmd
772                    }
773                };
774                c.current_dir(root);
775                scrub(&mut c);
776                if model_shell {
777                    c.env(MODEL_SHELL_ENV, "1");
778                }
779                Ok(c)
780            }
781            Launcher::Container {
782                container_id,
783                workdir,
784            } => {
785                let mut c = Command::new("docker");
786                c.args(["exec", "-i"]);
787                if model_shell {
788                    c.args(["-e", "BLYTE_MODEL_SHELL=1"]);
789                }
790                c.arg("-w")
791                    .arg(workdir)
792                    .arg(container_id)
793                    .args(["bash", "-l"]);
794                Ok(c)
795            }
796        }
797    }
798
799    fn with_profile(&self, profile: Profile) -> Self {
800        match self {
801            Launcher::Local { root, .. } => Launcher::Local {
802                root: root.clone(),
803                profile: Some(profile),
804            },
805            Launcher::Container {
806                container_id,
807                workdir,
808            } => Launcher::Container {
809                container_id: container_id.clone(),
810                workdir: workdir.clone(),
811            },
812        }
813    }
814
815    /// The process-per-command executor this launcher replaces, used whenever a session
816    /// cannot start.
817    fn fallback(&self) -> Box<dyn Shell> {
818        match self {
819            Launcher::Local { profile, .. } => match profile {
820                Some(p) => Box::new(LocalShell::sandboxed(p.clone())),
821                None => Box::new(LocalShell),
822            },
823            Launcher::Container {
824                container_id,
825                workdir,
826            } => Box::new(ContainerShell {
827                container_id: container_id.clone(),
828                workdir: workdir.clone(),
829            }),
830        }
831    }
832}
833
834/// How a session command ended.
835pub enum RunResult {
836    Done(Output),
837    /// The deadline passed; the session must be killed. Paths hold what the command wrote.
838    TimedOut {
839        out: String,
840        err: String,
841    },
842    /// The shell ended before reporting (e.g. the command ran `exit`).
843    Died {
844        out: String,
845        err: String,
846    },
847}
848
849/// One long-lived `bash -l`. A command arrives through a heredoc read by the `read` builtin; its
850/// stdout and stderr go to their own files and come back with one `printf` behind a header of
851/// byte lengths. Only the command itself runs as a process: the previous protocol spawned about
852/// six helpers per command (`base64`, `tr`, `rm`), about 25 ms on macOS.
853pub struct Session {
854    child: Child,
855    stdin: ChildStdin,
856    chunks: Receiver<Vec<u8>>,
857    buf: Vec<u8>,
858    tmp: String,
859    next: u64,
860    nonce: String,
861}
862
863const READY: &str = "__BLYTE_READY__ ";
864
865/// A per-process token for heredoc delimiters, so no command or file content can end one early.
866fn nonce() -> String {
867    let t = std::time::SystemTime::now()
868        .duration_since(std::time::UNIX_EPOCH)
869        .map(|d| d.as_nanos())
870        .unwrap_or(0);
871    format!("{t:x}{:x}", std::process::id())
872}
873
874enum ReadErr {
875    Timeout,
876    Closed,
877}
878
879impl Session {
880    pub fn start(launcher: &Launcher) -> Result<Session, String> {
881        Self::start_with_marker(launcher, false)
882    }
883
884    fn start_with_marker(launcher: &Launcher, model_shell: bool) -> Result<Session, String> {
885        let mut cmd = launcher
886            .command(model_shell)
887            .map_err(|e| format!("cannot start a shell session: {e}"))?;
888        cmd.stdin(Stdio::piped())
889            .stdout(Stdio::piped())
890            .stderr(Stdio::null());
891        #[cfg(unix)]
892        {
893            use std::os::unix::process::CommandExt;
894            cmd.process_group(0);
895        }
896        let mut child = cmd
897            .spawn()
898            .map_err(|e| format!("cannot start a shell session: {e}"))?;
899        let stdin = child.stdin.take().ok_or("no stdin")?;
900        let mut stdout = child.stdout.take().ok_or("no stdout")?;
901        let (tx, rx) = mpsc::channel();
902        std::thread::spawn(move || {
903            let mut chunk = vec![0u8; 64 * 1024];
904            loop {
905                match stdout.read(&mut chunk) {
906                    Ok(0) | Err(_) => break,
907                    Ok(n) => {
908                        if tx.send(chunk[..n].to_vec()).is_err() {
909                            break;
910                        }
911                    }
912                }
913            }
914        });
915        let mut s = Session {
916            child,
917            stdin,
918            chunks: rx,
919            buf: Vec::new(),
920            tmp: String::new(),
921            next: 0,
922            nonce: nonce(),
923        };
924        let init = match launcher {
925            Launcher::Local { .. } => inherited_path_prefix(),
926            Launcher::Container { .. } => String::new(),
927        };
928        s.send(&format!(
929            "{init}__blyte_t=$(mktemp -d 2>/dev/null || {{ mkdir -p /tmp/blyte.$$ && echo /tmp/blyte.$$; }}); \
930             echo \"__BLYTE_READY__ $__blyte_t\"\n",
931        ))?;
932        let deadline = Instant::now() + Duration::from_secs(30);
933        loop {
934            match s.read_line(deadline) {
935                Ok(l) if l.starts_with(READY) => {
936                    s.tmp = l[READY.len()..].trim().to_string();
937                    return Ok(s);
938                }
939                Ok(_) => continue, // profile output on stdout
940                Err(_) => {
941                    s.kill();
942                    return Err("the shell session did not start".into());
943                }
944            }
945        }
946    }
947
948    fn send(&mut self, script: &str) -> Result<(), String> {
949        self.stdin
950            .write_all(script.as_bytes())
951            .and_then(|_| self.stdin.flush())
952            .map_err(|e| format!("the shell session closed: {e}"))
953    }
954
955    fn fill(&mut self, deadline: Instant) -> Result<(), ReadErr> {
956        match self
957            .chunks
958            .recv_timeout(deadline.saturating_duration_since(Instant::now()))
959        {
960            Ok(c) => {
961                self.buf.extend_from_slice(&c);
962                Ok(())
963            }
964            Err(RecvTimeoutError::Timeout) => Err(ReadErr::Timeout),
965            Err(RecvTimeoutError::Disconnected) => Err(ReadErr::Closed),
966        }
967    }
968
969    /// The next line of session output, without its newline.
970    fn read_line(&mut self, deadline: Instant) -> Result<String, ReadErr> {
971        loop {
972            if let Some(i) = self.buf.iter().position(|&b| b == b'\n') {
973                let line: Vec<u8> = self.buf.drain(..=i).collect();
974                return Ok(String::from_utf8_lossy(&line[..i]).into_owned());
975            }
976            self.fill(deadline)?;
977        }
978    }
979
980    /// Exactly `n` bytes of session output.
981    fn read_exact(&mut self, n: usize, deadline: Instant) -> Result<Vec<u8>, ReadErr> {
982        while self.buf.len() < n {
983            self.fill(deadline)?;
984        }
985        Ok(self.buf.drain(..n).collect())
986    }
987
988    /// Kill the session and everything it started.
989    pub fn kill(&mut self) {
990        #[cfg(unix)]
991        {
992            let pgid = self.child.id() as i32;
993            if pgid > 0 {
994                unsafe {
995                    libc::kill(-pgid, libc::SIGKILL);
996                }
997            }
998        }
999        let _ = self.child.kill();
1000        let _ = self.child.wait();
1001    }
1002
1003    /// Run `command` to completion. `cwd: Some(dir)` runs it in a subshell in `dir`, so nothing
1004    /// it does persists; `None` runs it in the session itself, so `cd` and `export` carry over.
1005    pub fn run(&mut self, command: &str, cwd: Option<&Path>, timeout: Duration) -> RunResult {
1006        let id = self.next;
1007        self.next += 1;
1008        let (out, err) = (
1009            format!("{}/{id}.o", self.tmp),
1010            format!("{}/{id}.e", self.tmp),
1011        );
1012        let (qo, qe, qt) = (quote(&out), quote(&err), quote(&self.tmp));
1013        let delim = format!("__BLYTE_CMD_{id}_{}__", self.nonce);
1014        let body = match cwd {
1015            Some(d) => format!(
1016                "( cd {} && eval \"$__blyte_c\" )",
1017                quote(&d.to_string_lossy())
1018            ),
1019            None => "eval \"$__blyte_c\"".to_string(),
1020        };
1021        // `|| true` on the protocol's own reads: a model's `set -e` must not end the session
1022        // because `read` reports end of input. LC_ALL=C makes `${#var}` count bytes; the
1023        // model's LC_ALL is put back afterwards.
1024        // Recreate tmp before each command so output redirects succeed even if a command deleted it.
1025        let script = format!(
1026            "IFS= read -r -d '' __blyte_c <<'{delim}' || true\n{command}\n{delim}\n\
1027             [ -d {qt} ] || mkdir -p {qt} 2>/dev/null; {body} </dev/null >{qo} 2>{qe}; __blyte_r=$?; \
1028             IFS= read -r -d '' __blyte_o <{qo} || true; \
1029             IFS= read -r -d '' __blyte_e <{qe} || true; \
1030             __blyte_l=${{LC_ALL-__blyte_unset__}}; LC_ALL=C; \
1031             printf '__BLYTE_{id}__ %s %s %s\\n%s%s' \"$__blyte_r\" \"${{#__blyte_o}}\" \
1032             \"${{#__blyte_e}}\" \"$__blyte_o\" \"$__blyte_e\"; \
1033             if [ \"$__blyte_l\" = __blyte_unset__ ]; then unset LC_ALL; else LC_ALL=$__blyte_l; fi; \
1034             unset __blyte_c __blyte_o __blyte_e __blyte_l\n"
1035        );
1036        if self.send(&script).is_err() {
1037            return RunResult::Died { out, err };
1038        }
1039        let marker = format!("__BLYTE_{id}__ ");
1040        let deadline = Instant::now() + timeout;
1041        let fail = |e: ReadErr, out: String, err: String| match e {
1042            ReadErr::Timeout => RunResult::TimedOut { out, err },
1043            ReadErr::Closed => RunResult::Died { out, err },
1044        };
1045        let header = loop {
1046            match self.read_line(deadline) {
1047                Ok(l) => {
1048                    if let Some(rest) = l.strip_prefix(&marker) {
1049                        break rest.to_string();
1050                    }
1051                }
1052                Err(e) => return fail(e, out, err),
1053            }
1054        };
1055        let mut f = header.split(' ');
1056        let exit_code = f.next().and_then(|x| x.parse().ok()).unwrap_or(-1);
1057        let no: usize = f.next().and_then(|x| x.parse().ok()).unwrap_or(0);
1058        let ne: usize = f.next().and_then(|x| x.parse().ok()).unwrap_or(0);
1059        match self.read_exact(no + ne, deadline) {
1060            Ok(bytes) => RunResult::Done(Output {
1061                stdout: String::from_utf8_lossy(&bytes[..no]).into_owned(),
1062                stderr: String::from_utf8_lossy(&bytes[no..]).into_owned(),
1063                exit_code,
1064            }),
1065            Err(e) => fail(e, out, err),
1066        }
1067    }
1068
1069    /// Remove the session's scratch directory, then end it.
1070    fn close(&mut self) {
1071        let _ = self.send(&format!("rm -rf {}; exit 0\n", quote(&self.tmp)));
1072        let deadline = Instant::now() + Duration::from_millis(300);
1073        while Instant::now() < deadline {
1074            if let Ok(Some(_)) = self.child.try_wait() {
1075                return;
1076            }
1077            std::thread::sleep(Duration::from_millis(10));
1078        }
1079        self.kill();
1080    }
1081}
1082
1083pub type ProfileBuilder = Arc<dyn Fn() -> Result<Profile, String> + Send + Sync>;
1084
1085pub const SHELL_RESTART_NOTICE: &str =
1086    "blyte: the shell restarted because the open edits changed; exported variables were reset";
1087
1088struct UserSession {
1089    session: Session,
1090    profile: Option<Profile>,
1091}
1092
1093/// Commands through persistent sessions instead of a process each: one session for the
1094/// harness's own commands (each in a fresh subshell in the directory asked for, never affected
1095/// by the model's) and one for the model's `bash` (its `cd` and `export` carry over). Falls back
1096/// to a process per command, exactly as [`LocalShell`] / [`ContainerShell`], when a session
1097/// cannot start.
1098///
1099/// A `docker exec` per call cost 60-110 ms and a container `edit` about 300 ms; a session round
1100/// trip costs a few milliseconds (harness_bench, 2026-09-24).
1101pub struct PersistentShell {
1102    launcher: Launcher,
1103    profile_builder: Option<ProfileBuilder>,
1104    harness: Mutex<Option<Session>>,
1105    user: Mutex<Option<UserSession>>,
1106    fallback: Box<dyn Shell>,
1107}
1108
1109impl PersistentShell {
1110    pub fn new(launcher: Launcher) -> Self {
1111        let fallback = launcher.fallback();
1112        Self {
1113            launcher,
1114            profile_builder: None,
1115            harness: Mutex::new(None),
1116            user: Mutex::new(None),
1117            fallback,
1118        }
1119    }
1120
1121    pub fn with_profile_builder(mut self, builder: ProfileBuilder) -> Self {
1122        self.profile_builder = Some(builder);
1123        self
1124    }
1125
1126    pub fn local(root: PathBuf) -> Self {
1127        Self::new(Launcher::Local {
1128            root,
1129            profile: None,
1130        })
1131    }
1132
1133    pub fn local_sandboxed(root: PathBuf, profile: impl Into<Profile>) -> Self {
1134        Self::new(Launcher::Local {
1135            root,
1136            profile: Some(profile.into()),
1137        })
1138    }
1139
1140    pub fn sandboxed(root: PathBuf, profile: impl Into<Profile>) -> Self {
1141        Self::local_sandboxed(root, profile)
1142    }
1143
1144    pub fn container(container_id: String, workdir: PathBuf) -> Self {
1145        Self::new(Launcher::Container {
1146            container_id,
1147            workdir,
1148        })
1149    }
1150
1151    /// Whether the harness session is (or can be) running. False means every call falls back.
1152    pub fn is_persistent(&self) -> bool {
1153        let mut g = self.harness.lock().unwrap_or_else(|e| e.into_inner());
1154        if g.is_none() {
1155            *g = Session::start(&self.launcher).ok();
1156        }
1157        g.is_some()
1158    }
1159
1160    fn collect_aborted_output(
1161        &self,
1162        fallback: &dyn Shell,
1163        out: &str,
1164        err: &str,
1165        note: String,
1166        code: i32,
1167    ) -> Output {
1168        let cat = |p: &str| {
1169            fallback
1170                .exec(
1171                    &format!("cat -- {q} 2>/dev/null; rm -f -- {q}", q = quote(p)),
1172                    Path::new("/"),
1173                    Duration::from_secs(30),
1174                )
1175                .map(|o| o.stdout)
1176                .unwrap_or_default()
1177        };
1178        let (stdout, stderr) = (cat(out), cat(err));
1179        Output {
1180            stdout,
1181            stderr: format!("{stderr}{note}"),
1182            exit_code: code,
1183        }
1184    }
1185
1186    /// Run through `self.harness`, starting it if needed. `None` when no session can start.
1187    fn run_harness(
1188        &self,
1189        command: &str,
1190        cwd: &Path,
1191        timeout: Duration,
1192    ) -> Option<Result<Output, String>> {
1193        let mut g = self.harness.lock().unwrap_or_else(|e| e.into_inner());
1194        if g.is_none() {
1195            *g = Session::start_with_marker(&self.launcher, false).ok();
1196        }
1197        let session = g.as_mut()?;
1198        let (out, err, note, code) = match session.run(command, Some(cwd), timeout) {
1199            RunResult::Done(o) => return Some(Ok(o)),
1200            RunResult::TimedOut { out, err } => (
1201                out,
1202                err,
1203                format!("\n[killed by blyte after {}s]", timeout.as_secs()),
1204                124,
1205            ),
1206            RunResult::Died { out, err } => (
1207                out,
1208                err,
1209                "[the shell exited; the next command starts a fresh shell in the workspace root]"
1210                    .to_string(),
1211                1,
1212            ),
1213        };
1214        session.kill();
1215        *g = None;
1216        drop(g);
1217        Some(Ok(self.collect_aborted_output(
1218            self.fallback.as_ref(),
1219            &out,
1220            &err,
1221            note,
1222            code,
1223        )))
1224    }
1225
1226    fn run_user(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
1227        let desired_profile = match &self.profile_builder {
1228            Some(builder) => Some(builder()?),
1229            None => None,
1230        };
1231        let launcher = match &desired_profile {
1232            Some(profile) => self.launcher.with_profile(profile.clone()),
1233            None => self.launcher.clone(),
1234        };
1235
1236        let mut restarted = false;
1237        let mut g = self.user.lock().unwrap_or_else(|e| e.into_inner());
1238
1239        let mut saved_cwd = None;
1240        if let (Some(desired), Some(existing)) = (&desired_profile, g.as_mut()) {
1241            if existing.profile.as_ref() != Some(desired) {
1242                if let RunResult::Done(o) =
1243                    existing.session.run("pwd", None, Duration::from_secs(5))
1244                {
1245                    if o.exit_code == 0 {
1246                        let dir = o.stdout.trim_end_matches(&['\n', '\r'][..]);
1247                        if !dir.is_empty() {
1248                            saved_cwd = Some(PathBuf::from(dir));
1249                        }
1250                    }
1251                }
1252                existing.session.close();
1253                *g = None;
1254                restarted = true;
1255            }
1256        }
1257
1258        if g.is_none() {
1259            match Session::start_with_marker(&launcher, true) {
1260                Ok(mut session) => {
1261                    if let Some(dir) = saved_cwd {
1262                        let _ = session.run(
1263                            &format!("cd -- {}", quote(&dir.to_string_lossy())),
1264                            None,
1265                            Duration::from_secs(5),
1266                        );
1267                    }
1268                    *g = Some(UserSession {
1269                        session,
1270                        profile: desired_profile,
1271                    });
1272                }
1273                Err(_) => {
1274                    drop(g);
1275                    let mut out = if self.profile_builder.is_some() {
1276                        launcher.fallback().exec_user(command, cwd, timeout)?
1277                    } else {
1278                        self.fallback.exec_user(command, cwd, timeout)?
1279                    };
1280                    if restarted {
1281                        out.stdout = format!("{SHELL_RESTART_NOTICE}\n{}", out.stdout);
1282                    }
1283                    return Ok(out);
1284                }
1285            }
1286        }
1287
1288        let user = g.as_mut().unwrap();
1289        let mut output = match user.session.run(command, None, timeout) {
1290            RunResult::Done(o) => o,
1291            RunResult::TimedOut { out, err } => {
1292                user.session.kill();
1293                *g = None;
1294                drop(g);
1295                let fallback = if self.profile_builder.is_some() {
1296                    launcher.fallback()
1297                } else {
1298                    self.launcher.fallback()
1299                };
1300                self.collect_aborted_output(
1301                    fallback.as_ref(),
1302                    &out,
1303                    &err,
1304                    format!("\n[killed by blyte after {}s]", timeout.as_secs()),
1305                    124,
1306                )
1307            }
1308            RunResult::Died { out, err } => {
1309                user.session.kill();
1310                *g = None;
1311                drop(g);
1312                let fallback = if self.profile_builder.is_some() {
1313                    launcher.fallback()
1314                } else {
1315                    self.launcher.fallback()
1316                };
1317                self.collect_aborted_output(
1318                    fallback.as_ref(),
1319                    &out,
1320                    &err,
1321                    "[the shell exited; the next command starts a fresh shell in the workspace root]"
1322                        .to_string(),
1323                    1,
1324                )
1325            }
1326        };
1327        if restarted {
1328            output.stdout = format!("{SHELL_RESTART_NOTICE}\n{}", output.stdout);
1329        }
1330        Ok(output)
1331    }
1332}
1333
1334impl Shell for PersistentShell {
1335    fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
1336        self.run_harness(command, cwd, timeout)
1337            .unwrap_or_else(|| self.fallback.exec(command, cwd, timeout))
1338    }
1339
1340    fn exec_user(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
1341        self.run_user(command, cwd, timeout)
1342    }
1343
1344    fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
1345        self.fallback.exec_host(command, cwd, timeout)
1346    }
1347
1348    fn describe(&self) -> String {
1349        format!(
1350            "{} Your `bash` commands share one shell session: `cd` and `export` carry over to \
1351             later commands. File tools always resolve paths from the workspace root.",
1352            self.fallback.describe()
1353        )
1354    }
1355}
1356
1357impl Drop for PersistentShell {
1358    fn drop(&mut self) {
1359        if let Some(mut s) = self
1360            .harness
1361            .lock()
1362            .unwrap_or_else(|e| e.into_inner())
1363            .take()
1364        {
1365            s.close();
1366        }
1367        if let Some(mut u) = self.user.lock().unwrap_or_else(|e| e.into_inner()).take() {
1368            u.session.close();
1369        }
1370    }
1371}
1372
1373#[cfg(test)]
1374mod tests {
1375    use super::*;
1376
1377    #[test]
1378    fn persistent_shell_profile_builder_error_fails_command() {
1379        let tmp = tempfile::tempdir().unwrap();
1380        let shell =
1381            PersistentShell::local(tmp.path().to_path_buf()).with_profile_builder(Arc::new(|| {
1382                Err("cannot read .wt: permission denied".into())
1383            }));
1384        let err = shell
1385            .exec_user("echo hi", tmp.path(), Duration::from_secs(5))
1386            .unwrap_err();
1387        assert_eq!(err, "cannot read .wt: permission denied");
1388    }
1389}