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