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