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