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    /// Creates a local shell sandboxed with a conversation sandbox profile and optional private `TMPDIR`.
494    pub fn conversation_sandboxed(sandbox: crate::sandbox::ConversationSandbox) -> Self {
495        Self {
496            profile: Some(sandbox.profile),
497            tmpdir: sandbox.tmpdir,
498        }
499    }
500
501    /// Overrides `TMPDIR` for commands executed by this shell when `tmpdir` is `Some`.
502    pub fn with_tmpdir(mut self, tmpdir: Option<PathBuf>) -> Self {
503        self.tmpdir = tmpdir;
504        self
505    }
506
507    fn build_command(&self, command: &str, cwd: &Path) -> Result<Command, String> {
508        let full_command = inherited_path_prefix() + command;
509        let command = full_command.as_str();
510        let mut cmd = match &self.profile {
511            Some(Profile::Seatbelt(profile)) => {
512                let mut c = Command::new("/usr/bin/sandbox-exec");
513                c.args(["-p", profile, "bash", "-lc", command]);
514                c
515            }
516            Some(Profile::Landlock(paths)) => {
517                #[cfg(target_os = "linux")]
518                {
519                    let mut c = Command::new("bash");
520                    c.arg("-lc").arg(command);
521                    crate::sandbox::landlock_pre_exec(&mut c, paths, None, false)
522                        .map_err(|e| e.to_string())?;
523                    c
524                }
525                #[cfg(not(target_os = "linux"))]
526                {
527                    let _ = paths;
528                    return Err(std::io::Error::new(
529                        std::io::ErrorKind::Unsupported,
530                        "Landlock is only supported on Linux",
531                    )
532                    .to_string());
533                }
534            }
535            Some(Profile::LandlockOffline(paths)) => {
536                #[cfg(target_os = "linux")]
537                {
538                    let mut c = Command::new("bash");
539                    c.arg("-lc").arg(command);
540                    crate::sandbox::landlock_pre_exec(&mut c, paths, None, true)
541                        .map_err(|e| e.to_string())?;
542                    c
543                }
544                #[cfg(not(target_os = "linux"))]
545                {
546                    let _ = paths;
547                    return Err(std::io::Error::new(
548                        std::io::ErrorKind::Unsupported,
549                        "Landlock is only supported on Linux",
550                    )
551                    .to_string());
552                }
553            }
554            Some(Profile::LandlockConfined {
555                write,
556                read,
557                block_tcp,
558            }) => {
559                #[cfg(target_os = "linux")]
560                {
561                    let mut c = Command::new("bash");
562                    c.arg("-lc").arg(command);
563                    crate::sandbox::landlock_pre_exec(&mut c, write, Some(read), *block_tcp)
564                        .map_err(|e| e.to_string())?;
565                    c
566                }
567                #[cfg(not(target_os = "linux"))]
568                {
569                    let _ = (write, read, block_tcp);
570                    return Err(std::io::Error::new(
571                        std::io::ErrorKind::Unsupported,
572                        "Landlock is only supported on Linux",
573                    )
574                    .to_string());
575                }
576            }
577            None => {
578                let mut c = Command::new("bash");
579                c.arg("-lc").arg(command);
580                c
581            }
582        };
583        cmd.current_dir(cwd);
584        scrub(&mut cmd);
585        if let Some(ref tmpdir) = self.tmpdir {
586            cmd.env("TMPDIR", tmpdir);
587        }
588        Ok(cmd)
589    }
590}
591
592impl Shell for LocalShell {
593    fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
594        let cmd = self.build_command(command, cwd)?;
595        exec_command(cmd, timeout)
596    }
597
598    fn exec_user(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
599        let mut cmd = self.build_command(command, cwd)?;
600        cmd.env(MODEL_SHELL_ENV, "1");
601        exec_command(cmd, timeout)
602    }
603
604    fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
605        let full_command = inherited_path_prefix() + command;
606        let mut cmd = Command::new("bash");
607        cmd.arg("-lc").arg(&full_command);
608        cmd.current_dir(cwd);
609        scrub_harness(&mut cmd);
610        cmd.env(MODEL_SHELL_ENV, "1");
611        exec_command(cmd, timeout)
612    }
613
614    fn describe(&self) -> String {
615        "Commands run directly on this machine, in the workspace directory.".into()
616    }
617}
618
619/// A [`LocalShell`] whose running command can be stopped via a [`CancelHandle`].
620#[derive(Debug, Clone)]
621pub struct CancellableLocalShell {
622    pub inner: LocalShell,
623    pub cancel: Arc<CancelHandle>,
624}
625
626impl Shell for CancellableLocalShell {
627    fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
628        let cmd = self.inner.build_command(command, cwd)?;
629        exec_command_cancellable(cmd, timeout, Some(&self.cancel))
630    }
631
632    fn exec_user(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
633        let mut cmd = self.inner.build_command(command, cwd)?;
634        cmd.env(MODEL_SHELL_ENV, "1");
635        exec_command_cancellable(cmd, timeout, Some(&self.cancel))
636    }
637
638    fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
639        let full_command = inherited_path_prefix() + command;
640        let mut cmd = Command::new("bash");
641        cmd.arg("-lc").arg(&full_command);
642        cmd.current_dir(cwd);
643        scrub_harness(&mut cmd);
644        cmd.env(MODEL_SHELL_ENV, "1");
645        exec_command_cancellable(cmd, timeout, Some(&self.cancel))
646    }
647
648    fn describe(&self) -> String {
649        self.inner.describe()
650    }
651}
652
653/// Commands run inside an already-running container via `docker exec`.
654///
655/// The case the previous harness handled with a prose instruction. Here the model still calls
656/// `bash` and cannot route around it, because there is no host shell in its tool surface.
657#[derive(Debug, Clone)]
658pub struct ContainerShell {
659    pub container_id: String,
660    /// Where the workspace is mounted inside the container.
661    pub workdir: PathBuf,
662}
663
664impl ContainerShell {
665    fn build_command(&self, command: &str, model_shell: bool) -> Command {
666        let mut cmd = Command::new("docker");
667        cmd.args(["exec", "-i"]);
668        if model_shell {
669            cmd.args(["-e", "BLYTE_MODEL_SHELL=1"]);
670        }
671        cmd.arg("-w")
672            .arg(&self.workdir)
673            .arg(&self.container_id)
674            .args(["bash", "-lc", command]);
675        cmd
676    }
677}
678
679impl Shell for ContainerShell {
680    fn exec(&self, command: &str, _cwd: &Path, timeout: Duration) -> Result<Output, String> {
681        exec_command(self.build_command(command, false), timeout)
682    }
683
684    fn exec_user(&self, command: &str, _cwd: &Path, timeout: Duration) -> Result<Output, String> {
685        exec_command(self.build_command(command, true), timeout)
686    }
687
688    fn describe(&self) -> String {
689        format!(
690            "Commands run inside the project container at {}. Project dependencies are \
691             installed there, not on the host.",
692            self.workdir.display()
693        )
694    }
695}
696
697/// A [`ContainerShell`] whose running command can be stopped via a [`CancelHandle`].
698#[derive(Debug, Clone)]
699pub struct CancellableContainerShell {
700    pub inner: ContainerShell,
701    pub cancel: Arc<CancelHandle>,
702}
703
704impl Shell for CancellableContainerShell {
705    fn exec(&self, command: &str, _cwd: &Path, timeout: Duration) -> Result<Output, String> {
706        exec_command_cancellable(
707            self.inner.build_command(command, false),
708            timeout,
709            Some(&self.cancel),
710        )
711    }
712
713    fn exec_user(&self, command: &str, _cwd: &Path, timeout: Duration) -> Result<Output, String> {
714        exec_command_cancellable(
715            self.inner.build_command(command, true),
716            timeout,
717            Some(&self.cancel),
718        )
719    }
720
721    fn describe(&self) -> String {
722        self.inner.describe()
723    }
724}
725
726/// Single-quote for a POSIX shell.
727fn quote(s: &str) -> String {
728    format!("'{}'", s.replace('\'', r"'\''"))
729}
730
731/// macOS `path_helper` in the login profile reorders PATH.
732pub fn inherited_path_prefix() -> String {
733    match std::env::var("PATH") {
734        Ok(path) if !path.is_empty() => format!("export PATH={}:\"$PATH\"; ", quote(&path)),
735        _ => String::new(),
736    }
737}
738
739/// How to start a session's shell: a login shell, as `bash -lc` gives today.
740#[derive(Debug, Clone)]
741pub enum Launcher {
742    /// `bash -l` on this machine, starting in `root`, optionally sandboxed under a profile.
743    Local {
744        root: PathBuf,
745        profile: Option<Profile>,
746        tmpdir: Option<PathBuf>,
747    },
748    /// `bash -l` inside a running container, starting in `workdir`.
749    Container {
750        container_id: String,
751        workdir: PathBuf,
752    },
753}
754
755impl Launcher {
756    fn command(&self, model_shell: bool) -> std::io::Result<Command> {
757        match self {
758            Launcher::Local {
759                root,
760                profile,
761                tmpdir,
762            } => {
763                let mut c = match profile {
764                    Some(Profile::Seatbelt(p)) => {
765                        let mut cmd = Command::new("/usr/bin/sandbox-exec");
766                        cmd.args(["-p", p, "bash", "-l"]);
767                        cmd
768                    }
769                    Some(Profile::Landlock(paths)) => {
770                        #[cfg(target_os = "linux")]
771                        {
772                            let mut cmd = Command::new("bash");
773                            cmd.arg("-l");
774                            crate::sandbox::landlock_pre_exec(&mut cmd, paths, None, false)?;
775                            cmd
776                        }
777                        #[cfg(not(target_os = "linux"))]
778                        {
779                            let _ = paths;
780                            return Err(std::io::Error::new(
781                                std::io::ErrorKind::Unsupported,
782                                "Landlock is only supported on Linux",
783                            ));
784                        }
785                    }
786                    Some(Profile::LandlockOffline(paths)) => {
787                        #[cfg(target_os = "linux")]
788                        {
789                            let mut cmd = Command::new("bash");
790                            cmd.arg("-l");
791                            crate::sandbox::landlock_pre_exec(&mut cmd, paths, None, true)?;
792                            cmd
793                        }
794                        #[cfg(not(target_os = "linux"))]
795                        {
796                            let _ = paths;
797                            return Err(std::io::Error::new(
798                                std::io::ErrorKind::Unsupported,
799                                "Landlock is only supported on Linux",
800                            ));
801                        }
802                    }
803                    Some(Profile::LandlockConfined {
804                        write,
805                        read,
806                        block_tcp,
807                    }) => {
808                        #[cfg(target_os = "linux")]
809                        {
810                            let mut cmd = Command::new("bash");
811                            cmd.arg("-l");
812                            crate::sandbox::landlock_pre_exec(
813                                &mut cmd,
814                                write,
815                                Some(read),
816                                *block_tcp,
817                            )?;
818                            cmd
819                        }
820                        #[cfg(not(target_os = "linux"))]
821                        {
822                            let _ = (write, read, block_tcp);
823                            return Err(std::io::Error::new(
824                                std::io::ErrorKind::Unsupported,
825                                "Landlock is only supported on Linux",
826                            ));
827                        }
828                    }
829                    None => {
830                        let mut cmd = Command::new("bash");
831                        cmd.arg("-l");
832                        cmd
833                    }
834                };
835                c.current_dir(root);
836                scrub(&mut c);
837                if let Some(ref tmpdir) = tmpdir {
838                    c.env("TMPDIR", tmpdir);
839                }
840                if model_shell {
841                    c.env(MODEL_SHELL_ENV, "1");
842                }
843                Ok(c)
844            }
845            Launcher::Container {
846                container_id,
847                workdir,
848            } => {
849                let mut c = Command::new("docker");
850                c.args(["exec", "-i"]);
851                if model_shell {
852                    c.args(["-e", "BLYTE_MODEL_SHELL=1"]);
853                }
854                c.arg("-w")
855                    .arg(workdir)
856                    .arg(container_id)
857                    .args(["bash", "-l"]);
858                Ok(c)
859            }
860        }
861    }
862
863    fn with_profile(&self, profile: Profile) -> Self {
864        match self {
865            Launcher::Local { root, tmpdir, .. } => Launcher::Local {
866                root: root.clone(),
867                profile: Some(profile),
868                tmpdir: tmpdir.clone(),
869            },
870            Launcher::Container {
871                container_id,
872                workdir,
873            } => Launcher::Container {
874                container_id: container_id.clone(),
875                workdir: workdir.clone(),
876            },
877        }
878    }
879
880    /// The process-per-command executor this launcher replaces, used whenever a session
881    /// cannot start.
882    fn fallback(&self) -> Box<dyn Shell> {
883        match self {
884            Launcher::Local {
885                profile, tmpdir, ..
886            } => match profile {
887                Some(p) => Box::new(LocalShell::sandboxed(p.clone()).with_tmpdir(tmpdir.clone())),
888                None => Box::new(LocalShell::new().with_tmpdir(tmpdir.clone())),
889            },
890            Launcher::Container {
891                container_id,
892                workdir,
893            } => Box::new(ContainerShell {
894                container_id: container_id.clone(),
895                workdir: workdir.clone(),
896            }),
897        }
898    }
899}
900
901/// How a session command ended.
902pub enum RunResult {
903    Done(Output),
904    /// The deadline passed; the session must be killed. Paths hold what the command wrote.
905    TimedOut {
906        out: String,
907        err: String,
908    },
909    /// The shell ended before reporting (e.g. the command ran `exit`).
910    Died {
911        out: String,
912        err: String,
913    },
914    Failed(String),
915}
916
917/// One long-lived `bash -l`. A command arrives through a heredoc read by the `read` builtin; its
918/// stdout and stderr go to their own files and come back with one `printf` behind a header of
919/// byte lengths. Only the command itself runs as a process: the previous protocol spawned about
920/// six helpers per command (`base64`, `tr`, `rm`), about 25 ms on macOS.
921pub struct Session {
922    child: Child,
923    stdin: ChildStdin,
924    chunks: Receiver<Vec<u8>>,
925    buf: Vec<u8>,
926    tmp: String,
927    next: u64,
928    nonce: String,
929}
930
931const READY: &str = "__BLYTE_READY__ ";
932
933/// A per-process token for heredoc delimiters, so no command or file content can end one early.
934fn nonce() -> String {
935    let t = std::time::SystemTime::now()
936        .duration_since(std::time::UNIX_EPOCH)
937        .map(|d| d.as_nanos())
938        .unwrap_or(0);
939    format!("{t:x}{:x}", std::process::id())
940}
941
942enum ReadErr {
943    Timeout,
944    Closed,
945    Malformed(String),
946}
947
948fn parse_header(header: &str) -> Result<(i32, usize, usize), String> {
949    let malformed = || format!("shell returned a malformed result header: {header}");
950    let mut f = header.split(' ');
951    let exit_code: i32 = f
952        .next()
953        .ok_or_else(malformed)?
954        .parse()
955        .map_err(|_| malformed())?;
956    let no: usize = f
957        .next()
958        .ok_or_else(malformed)?
959        .parse()
960        .map_err(|_| malformed())?;
961    let ne: usize = f
962        .next()
963        .ok_or_else(malformed)?
964        .parse()
965        .map_err(|_| malformed())?;
966    if f.next().is_some() || no.checked_add(ne).is_none() {
967        return Err(malformed());
968    }
969    Ok((exit_code, no, ne))
970}
971
972impl Session {
973    pub fn start(launcher: &Launcher) -> Result<Session, String> {
974        Self::start_with_marker(launcher, false)
975    }
976
977    fn start_with_marker(launcher: &Launcher, model_shell: bool) -> Result<Session, String> {
978        let mut cmd = launcher
979            .command(model_shell)
980            .map_err(|e| format!("cannot start a shell session: {e}"))?;
981        cmd.stdin(Stdio::piped())
982            .stdout(Stdio::piped())
983            .stderr(Stdio::null());
984        #[cfg(unix)]
985        {
986            use std::os::unix::process::CommandExt;
987            cmd.process_group(0);
988        }
989        let mut child = cmd
990            .spawn()
991            .map_err(|e| format!("cannot start a shell session: {e}"))?;
992        let stdin = child.stdin.take().ok_or("no stdin")?;
993        let mut stdout = child.stdout.take().ok_or("no stdout")?;
994        let (tx, rx) = mpsc::channel();
995        std::thread::spawn(move || {
996            let mut chunk = vec![0u8; 64 * 1024];
997            loop {
998                match stdout.read(&mut chunk) {
999                    Ok(0) | Err(_) => break,
1000                    Ok(n) => {
1001                        if tx.send(chunk[..n].to_vec()).is_err() {
1002                            break;
1003                        }
1004                    }
1005                }
1006            }
1007        });
1008        let mut s = Session {
1009            child,
1010            stdin,
1011            chunks: rx,
1012            buf: Vec::new(),
1013            tmp: String::new(),
1014            next: 0,
1015            nonce: nonce(),
1016        };
1017        let init = match launcher {
1018            Launcher::Local { .. } => inherited_path_prefix(),
1019            Launcher::Container { .. } => String::new(),
1020        };
1021        s.send(&format!(
1022            "{init}__blyte_t=$(mktemp -d 2>/dev/null || {{ mkdir -p /tmp/blyte.$$ && echo /tmp/blyte.$$; }}); \
1023             echo \"__BLYTE_READY__ $__blyte_t\"\n",
1024        ))?;
1025        let deadline = Instant::now() + Duration::from_secs(30);
1026        loop {
1027            match s.read_line(deadline) {
1028                Ok(l) if l.starts_with(READY) => {
1029                    s.tmp = l[READY.len()..].trim().to_string();
1030                    return Ok(s);
1031                }
1032                Ok(_) => continue, // profile output on stdout
1033                Err(_) => {
1034                    s.kill();
1035                    return Err("the shell session did not start".into());
1036                }
1037            }
1038        }
1039    }
1040
1041    fn send(&mut self, script: &str) -> Result<(), String> {
1042        self.stdin
1043            .write_all(script.as_bytes())
1044            .and_then(|_| self.stdin.flush())
1045            .map_err(|e| format!("the shell session closed: {e}"))
1046    }
1047
1048    fn fill(&mut self, deadline: Instant) -> Result<(), ReadErr> {
1049        match self
1050            .chunks
1051            .recv_timeout(deadline.saturating_duration_since(Instant::now()))
1052        {
1053            Ok(c) => {
1054                self.buf.extend_from_slice(&c);
1055                Ok(())
1056            }
1057            Err(RecvTimeoutError::Timeout) => Err(ReadErr::Timeout),
1058            Err(RecvTimeoutError::Disconnected) => Err(ReadErr::Closed),
1059        }
1060    }
1061
1062    /// The next line of session output, without its newline.
1063    fn read_line(&mut self, deadline: Instant) -> Result<String, ReadErr> {
1064        loop {
1065            if let Some(i) = self.buf.iter().position(|&b| b == b'\n') {
1066                let line: Vec<u8> = self.buf.drain(..=i).collect();
1067                return Ok(String::from_utf8_lossy(&line[..i]).into_owned());
1068            }
1069            self.fill(deadline)?;
1070        }
1071    }
1072
1073    /// Exactly `n` bytes of session output.
1074    fn read_exact(&mut self, n: usize, deadline: Instant) -> Result<Vec<u8>, ReadErr> {
1075        while self.buf.len() < n {
1076            self.fill(deadline)?;
1077        }
1078        Ok(self.buf.drain(..n).collect())
1079    }
1080
1081    /// Kill the session and everything it started.
1082    pub fn kill(&mut self) {
1083        #[cfg(unix)]
1084        {
1085            let pgid = self.child.id() as i32;
1086            if pgid > 0 {
1087                unsafe {
1088                    libc::kill(-pgid, libc::SIGKILL);
1089                }
1090            }
1091        }
1092        let _ = self.child.kill();
1093        let _ = self.child.wait();
1094    }
1095
1096    /// Run `command` to completion. `cwd: Some(dir)` runs it in a subshell in `dir`, so nothing
1097    /// it does persists; `None` runs it in the session itself, so `cd` and `export` carry over.
1098    pub fn run(&mut self, command: &str, cwd: Option<&Path>, timeout: Duration) -> RunResult {
1099        let id = self.next;
1100        self.next += 1;
1101        let (out, err) = (
1102            format!("{}/{id}.o", self.tmp),
1103            format!("{}/{id}.e", self.tmp),
1104        );
1105        let (qo, qe, qt) = (quote(&out), quote(&err), quote(&self.tmp));
1106        let delim = format!("__BLYTE_CMD_{id}_{}__", self.nonce);
1107        let body = match cwd {
1108            Some(d) => format!(
1109                "( cd {} && eval \"$__blyte_c\" )",
1110                quote(&d.to_string_lossy())
1111            ),
1112            None => "eval \"$__blyte_c\"".to_string(),
1113        };
1114        // `|| true` on the protocol's own reads: a model's `set -e` must not end the session
1115        // because `read` reports end of input. LC_ALL=C makes `${#var}` count bytes; the
1116        // model's LC_ALL is put back afterwards.
1117        // Recreate tmp before each command so output redirects succeed even if a command deleted it.
1118        let script = format!(
1119            "IFS= read -r -d '' __blyte_c <<'{delim}' || true\n{command}\n{delim}\n\
1120             [ -d {qt} ] || mkdir -p {qt} 2>/dev/null; {body} </dev/null >{qo} 2>{qe}; __blyte_r=$?; \
1121             IFS= read -r -d '' __blyte_o <{qo} || true; \
1122             IFS= read -r -d '' __blyte_e <{qe} || true; \
1123             __blyte_l=${{LC_ALL-__blyte_unset__}}; LC_ALL=C; \
1124             printf '__BLYTE_{id}__ %s %s %s\\n%s%s' \"$__blyte_r\" \"${{#__blyte_o}}\" \
1125             \"${{#__blyte_e}}\" \"$__blyte_o\" \"$__blyte_e\"; \
1126             if [ \"$__blyte_l\" = __blyte_unset__ ]; then unset LC_ALL; else LC_ALL=$__blyte_l; fi; \
1127             unset __blyte_c __blyte_o __blyte_e __blyte_l\n"
1128        );
1129        if self.send(&script).is_err() {
1130            return RunResult::Died { out, err };
1131        }
1132        let marker = format!("__BLYTE_{id}__ ");
1133        let deadline = Instant::now() + timeout;
1134        let fail = |e: ReadErr, out: String, err: String| match e {
1135            ReadErr::Timeout => RunResult::TimedOut { out, err },
1136            ReadErr::Closed => RunResult::Died { out, err },
1137            ReadErr::Malformed(msg) => RunResult::Failed(msg),
1138        };
1139        let header = loop {
1140            match self.read_line(deadline) {
1141                Ok(l) => {
1142                    if let Some(rest) = l.strip_prefix(&marker) {
1143                        break rest.to_string();
1144                    }
1145                }
1146                Err(e) => return fail(e, out, err),
1147            }
1148        };
1149        let (exit_code, no, ne) = match parse_header(&header) {
1150            Ok(parsed) => parsed,
1151            Err(msg) => return fail(ReadErr::Malformed(msg), out, err),
1152        };
1153        match self.read_exact(no + ne, deadline) {
1154            Ok(bytes) => RunResult::Done(Output {
1155                stdout: String::from_utf8_lossy(&bytes[..no]).into_owned(),
1156                stderr: String::from_utf8_lossy(&bytes[no..]).into_owned(),
1157                exit_code,
1158            }),
1159            Err(e) => fail(e, out, err),
1160        }
1161    }
1162
1163    /// Remove the session's scratch directory, then end it.
1164    fn close(&mut self) {
1165        let _ = self.send(&format!("rm -rf {}; exit 0\n", quote(&self.tmp)));
1166        let deadline = Instant::now() + Duration::from_millis(300);
1167        while Instant::now() < deadline {
1168            if let Ok(Some(_)) = self.child.try_wait() {
1169                return;
1170            }
1171            std::thread::sleep(Duration::from_millis(10));
1172        }
1173        self.kill();
1174    }
1175}
1176
1177pub type ProfileBuilder = Arc<dyn Fn() -> Result<Profile, String> + Send + Sync>;
1178
1179pub const SHELL_RESTART_NOTICE: &str =
1180    "blyte: the shell restarted because the open edits changed; exported variables were reset";
1181
1182struct UserSession {
1183    session: Session,
1184    profile: Option<Profile>,
1185}
1186
1187/// Commands through persistent sessions instead of a process each: one session for the
1188/// harness's own commands (each in a fresh subshell in the directory asked for, never affected
1189/// by the model's) and one for the model's `bash` (its `cd` and `export` carry over). Falls back
1190/// to a process per command, exactly as [`LocalShell`] / [`ContainerShell`], when a session
1191/// cannot start.
1192///
1193/// A `docker exec` per call cost 60-110 ms and a container `edit` about 300 ms; a session round
1194/// trip costs a few milliseconds (harness_bench, 2026-09-24).
1195pub struct PersistentShell {
1196    launcher: Launcher,
1197    profile_builder: Option<ProfileBuilder>,
1198    harness: Mutex<Option<Session>>,
1199    user: Mutex<Option<UserSession>>,
1200    fallback: Box<dyn Shell>,
1201}
1202
1203impl PersistentShell {
1204    pub fn new(launcher: Launcher) -> Self {
1205        let fallback = launcher.fallback();
1206        Self {
1207            launcher,
1208            profile_builder: None,
1209            harness: Mutex::new(None),
1210            user: Mutex::new(None),
1211            fallback,
1212        }
1213    }
1214
1215    pub fn with_profile_builder(mut self, builder: ProfileBuilder) -> Self {
1216        self.profile_builder = Some(builder);
1217        self
1218    }
1219
1220    pub fn with_tmpdir(mut self, tmpdir: Option<PathBuf>) -> Self {
1221        if let Launcher::Local {
1222            tmpdir: ref mut slot,
1223            ..
1224        } = self.launcher
1225        {
1226            *slot = tmpdir;
1227            self.fallback = self.launcher.fallback();
1228        }
1229        self
1230    }
1231
1232    pub fn local(root: PathBuf) -> Self {
1233        Self::new(Launcher::Local {
1234            root,
1235            profile: None,
1236            tmpdir: None,
1237        })
1238    }
1239
1240    pub fn local_sandboxed(root: PathBuf, profile: impl Into<Profile>) -> Self {
1241        Self::new(Launcher::Local {
1242            root,
1243            profile: Some(profile.into()),
1244            tmpdir: None,
1245        })
1246    }
1247
1248    pub fn sandboxed(root: PathBuf, profile: impl Into<Profile>) -> Self {
1249        Self::local_sandboxed(root, profile)
1250    }
1251
1252    pub fn container(container_id: String, workdir: PathBuf) -> Self {
1253        Self::new(Launcher::Container {
1254            container_id,
1255            workdir,
1256        })
1257    }
1258
1259    /// Whether the harness session is (or can be) running. False means every call falls back.
1260    pub fn is_persistent(&self) -> bool {
1261        let mut g = self.harness.lock().unwrap_or_else(|e| e.into_inner());
1262        if g.is_none() {
1263            *g = Session::start(&self.launcher).ok();
1264        }
1265        g.is_some()
1266    }
1267
1268    fn collect_aborted_output(
1269        &self,
1270        fallback: &dyn Shell,
1271        out: &str,
1272        err: &str,
1273        note: String,
1274        code: i32,
1275    ) -> Output {
1276        let cat = |p: &str| {
1277            fallback
1278                .exec(
1279                    &format!("cat -- {q} 2>/dev/null; rm -f -- {q}", q = quote(p)),
1280                    Path::new("/"),
1281                    Duration::from_secs(30),
1282                )
1283                .map(|o| o.stdout)
1284                .unwrap_or_default()
1285        };
1286        let (stdout, stderr) = (cat(out), cat(err));
1287        Output {
1288            stdout,
1289            stderr: format!("{stderr}{note}"),
1290            exit_code: code,
1291        }
1292    }
1293
1294    /// Run through `self.harness`, starting it if needed. `None` when no session can start.
1295    fn run_harness(
1296        &self,
1297        command: &str,
1298        cwd: &Path,
1299        timeout: Duration,
1300    ) -> Option<Result<Output, String>> {
1301        let mut g = self.harness.lock().unwrap_or_else(|e| e.into_inner());
1302        if g.is_none() {
1303            *g = Session::start_with_marker(&self.launcher, false).ok();
1304        }
1305        let session = g.as_mut()?;
1306        let (out, err, note, code) = match session.run(command, Some(cwd), timeout) {
1307            RunResult::Done(o) => return Some(Ok(o)),
1308            RunResult::Failed(msg) => {
1309                session.kill();
1310                *g = None;
1311                return Some(Err(msg));
1312            }
1313            RunResult::TimedOut { out, err } => (
1314                out,
1315                err,
1316                format!("\n[killed by blyte after {}s]", timeout.as_secs()),
1317                124,
1318            ),
1319            RunResult::Died { out, err } => (
1320                out,
1321                err,
1322                "[the shell exited; the next command starts a fresh shell in the workspace root]"
1323                    .to_string(),
1324                1,
1325            ),
1326        };
1327        session.kill();
1328        *g = None;
1329        drop(g);
1330        Some(Ok(self.collect_aborted_output(
1331            self.fallback.as_ref(),
1332            &out,
1333            &err,
1334            note,
1335            code,
1336        )))
1337    }
1338
1339    fn run_user(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
1340        let desired_profile = match &self.profile_builder {
1341            Some(builder) => Some(builder()?),
1342            None => None,
1343        };
1344        let launcher = match &desired_profile {
1345            Some(profile) => self.launcher.with_profile(profile.clone()),
1346            None => self.launcher.clone(),
1347        };
1348
1349        let mut restarted = false;
1350        let mut g = self.user.lock().unwrap_or_else(|e| e.into_inner());
1351
1352        let mut saved_cwd = None;
1353        if let (Some(desired), Some(existing)) = (&desired_profile, g.as_mut()) {
1354            if existing.profile.as_ref() != Some(desired) {
1355                if let RunResult::Done(o) =
1356                    existing.session.run("pwd", None, Duration::from_secs(5))
1357                {
1358                    if o.exit_code == 0 {
1359                        let dir = o.stdout.trim_end_matches(&['\n', '\r'][..]);
1360                        if !dir.is_empty() {
1361                            saved_cwd = Some(PathBuf::from(dir));
1362                        }
1363                    }
1364                }
1365                existing.session.close();
1366                *g = None;
1367                restarted = true;
1368            }
1369        }
1370
1371        if g.is_none() {
1372            match Session::start_with_marker(&launcher, true) {
1373                Ok(mut session) => {
1374                    if let Some(dir) = saved_cwd {
1375                        let _ = session.run(
1376                            &format!("cd -- {}", quote(&dir.to_string_lossy())),
1377                            None,
1378                            Duration::from_secs(5),
1379                        );
1380                    }
1381                    *g = Some(UserSession {
1382                        session,
1383                        profile: desired_profile,
1384                    });
1385                }
1386                Err(_) => {
1387                    drop(g);
1388                    let mut out = if self.profile_builder.is_some() {
1389                        launcher.fallback().exec_user(command, cwd, timeout)?
1390                    } else {
1391                        self.fallback.exec_user(command, cwd, timeout)?
1392                    };
1393                    if restarted {
1394                        out.stdout = format!("{SHELL_RESTART_NOTICE}\n{}", out.stdout);
1395                    }
1396                    return Ok(out);
1397                }
1398            }
1399        }
1400
1401        let user = g.as_mut().unwrap();
1402        let mut output = match user.session.run(command, None, timeout) {
1403            RunResult::Done(o) => o,
1404            RunResult::Failed(msg) => {
1405                user.session.kill();
1406                *g = None;
1407                return Err(msg);
1408            }
1409            RunResult::TimedOut { out, err } => {
1410                user.session.kill();
1411                *g = None;
1412                drop(g);
1413                let fallback = if self.profile_builder.is_some() {
1414                    launcher.fallback()
1415                } else {
1416                    self.launcher.fallback()
1417                };
1418                self.collect_aborted_output(
1419                    fallback.as_ref(),
1420                    &out,
1421                    &err,
1422                    format!("\n[killed by blyte after {}s]", timeout.as_secs()),
1423                    124,
1424                )
1425            }
1426            RunResult::Died { out, err } => {
1427                user.session.kill();
1428                *g = None;
1429                drop(g);
1430                let fallback = if self.profile_builder.is_some() {
1431                    launcher.fallback()
1432                } else {
1433                    self.launcher.fallback()
1434                };
1435                self.collect_aborted_output(
1436                    fallback.as_ref(),
1437                    &out,
1438                    &err,
1439                    "[the shell exited; the next command starts a fresh shell in the workspace root]"
1440                        .to_string(),
1441                    1,
1442                )
1443            }
1444        };
1445        if restarted {
1446            output.stdout = format!("{SHELL_RESTART_NOTICE}\n{}", output.stdout);
1447        }
1448        Ok(output)
1449    }
1450}
1451
1452impl Shell for PersistentShell {
1453    fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
1454        self.run_harness(command, cwd, timeout)
1455            .unwrap_or_else(|| self.fallback.exec(command, cwd, timeout))
1456    }
1457
1458    fn exec_user(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
1459        self.run_user(command, cwd, timeout)
1460    }
1461
1462    fn exec_host(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
1463        self.fallback.exec_host(command, cwd, timeout)
1464    }
1465
1466    fn describe(&self) -> String {
1467        format!(
1468            "{} Your `bash` commands share one shell session: `cd` and `export` carry over to \
1469             later commands. File tools always resolve paths from the workspace root.",
1470            self.fallback.describe()
1471        )
1472    }
1473}
1474
1475impl Drop for PersistentShell {
1476    fn drop(&mut self) {
1477        if let Some(mut s) = self
1478            .harness
1479            .lock()
1480            .unwrap_or_else(|e| e.into_inner())
1481            .take()
1482        {
1483            s.close();
1484        }
1485        if let Some(mut u) = self.user.lock().unwrap_or_else(|e| e.into_inner()).take() {
1486            u.session.close();
1487        }
1488    }
1489}
1490
1491#[cfg(test)]
1492mod tests {
1493    use super::*;
1494
1495    #[test]
1496    fn persistent_shell_profile_builder_error_fails_command() {
1497        let tmp = tempfile::tempdir().unwrap();
1498        let shell =
1499            PersistentShell::local(tmp.path().to_path_buf()).with_profile_builder(Arc::new(|| {
1500                Err("cannot read .wt: permission denied".into())
1501            }));
1502        let err = shell
1503            .exec_user("echo hi", tmp.path(), Duration::from_secs(5))
1504            .unwrap_err();
1505        assert_eq!(err, "cannot read .wt: permission denied");
1506    }
1507
1508    #[test]
1509    fn parse_header_accepts_valid_and_rejects_malformed() {
1510        assert_eq!(parse_header("0 3 4"), Ok((0, 3, 4)));
1511        assert_eq!(parse_header("127 0 12"), Ok((127, 0, 12)));
1512        assert_eq!(parse_header("-1 0 0"), Ok((-1, 0, 0)));
1513
1514        for bad in ["", "x 1 2", "0 1", "0 -1 2", "0 1 2 3"] {
1515            let err = parse_header(bad).unwrap_err();
1516            assert_eq!(
1517                err,
1518                format!("shell returned a malformed result header: {bad}")
1519            );
1520        }
1521    }
1522
1523    #[cfg(unix)]
1524    #[test]
1525    fn persistent_shell_rejects_malformed_result_header_and_recovers() {
1526        let tmp = tempfile::tempdir().unwrap();
1527        let root = tmp.path().canonicalize().unwrap();
1528        let shell = PersistentShell::local(root.clone());
1529        let err = shell
1530            .exec_user(
1531                "printf() { builtin printf '__BLYTE_0__ x 1 2\\n'; }",
1532                &root,
1533                Duration::from_secs(10),
1534            )
1535            .unwrap_err();
1536        assert_eq!(err, "shell returned a malformed result header: x 1 2");
1537
1538        let recovered = shell
1539            .exec_user("echo ok", &root, Duration::from_secs(10))
1540            .unwrap();
1541        assert_eq!(recovered.exit_code, 0);
1542        assert_eq!(recovered.stdout, "ok\n");
1543    }
1544
1545    struct FailingExecShell {
1546        outcome: Result<Output, String>,
1547    }
1548
1549    impl Shell for FailingExecShell {
1550        fn exec(&self, _command: &str, _cwd: &Path, _timeout: Duration) -> Result<Output, String> {
1551            self.outcome.clone()
1552        }
1553
1554        fn describe(&self) -> String {
1555            "failing".into()
1556        }
1557    }
1558
1559    struct UnspawnableShell;
1560
1561    impl Shell for UnspawnableShell {
1562        fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
1563            let mut cmd = Command::new("/nonexistent-blyte-probe-binary");
1564            cmd.arg("-c").arg(command).current_dir(cwd);
1565            exec_command(cmd, timeout)
1566        }
1567
1568        fn describe(&self) -> String {
1569            "unspawnable".into()
1570        }
1571    }
1572
1573    #[test]
1574    fn available_binaries_returns_err_when_probe_cannot_be_spawned() {
1575        let tmp = tempfile::tempdir().unwrap();
1576        let err = UnspawnableShell
1577            .available_binaries(tmp.path(), &["git", "cargo"])
1578            .unwrap_err();
1579        assert!(err.contains("command -v git"), "got: {err}");
1580        assert!(
1581            err.contains("/nonexistent-blyte-probe-binary"),
1582            "got: {err}"
1583        );
1584    }
1585
1586    #[test]
1587    fn available_binaries_returns_err_when_probe_exits_nonzero() {
1588        let shell = FailingExecShell {
1589            outcome: Ok(Output {
1590                stdout: String::new(),
1591                stderr: "Error response from daemon: container is not running\n".into(),
1592                exit_code: 125,
1593            }),
1594        };
1595        let err = shell
1596            .available_binaries(Path::new("."), &["git", "cargo"])
1597            .unwrap_err();
1598        assert!(err.contains("command -v git"), "got: {err}");
1599        assert!(err.contains("125"), "got: {err}");
1600        assert!(err.contains("container is not running"), "got: {err}");
1601    }
1602
1603    #[test]
1604    fn available_binaries_succeeds_when_all_candidates_are_absent() {
1605        let tmp = tempfile::tempdir().unwrap();
1606        let bins = LocalShell
1607            .available_binaries(
1608                tmp.path(),
1609                &[
1610                    "blyte_nonexistent_probe_binary_a",
1611                    "blyte_nonexistent_probe_binary_b",
1612                ],
1613            )
1614            .expect("missing candidates must not fail the probe");
1615        assert!(bins.is_empty(), "got: {bins:?}");
1616    }
1617}