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