Skip to main content

blyte_agent/
shell.rs

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