Skip to main content

rpi_tools/
os_env.rs

1//! Mirrors `packages/agent/src/harness/env/nodejs.ts` — `NodeExecutionEnv` →
2//! `OsExecutionEnv`. Real-filesystem + real-process backend via `tokio::fs` +
3//! `tokio::process`.
4//!
5//! Path resolution (\[`resolvePath`\]): tilde (`~`/`~/`, `~\` on Windows),
6//! `file://` URL (parse failure silently keeps the literal string), absolute
7//! → `canonicalize`-style normalize, relative → `cwd.join`. No env-var or
8//! `~user` expansion. No symlink resolution (that's `canonical_path`).
9//!
10//! Shell detection (\[`getShellConfig`\]): explicit override → Windows
11//! git-bash probe (`ProgramFiles\Git\bin\bash.exe`, `ProgramFiles(x86)\…`) →
12//! `where bash.exe` → POSIX `/bin/bash` → `which bash` → `/bin/sh` fallback
13//! (POSIX only). **No cmd.exe fallback** on Windows — failure is
14//! `ExecutionError::ShellUnavailable`. Legacy WSL bash (`System32\bash.exe`)
15//! uses `bash -s` stdin transport to avoid argv parse bugs.
16//!
17//! Kill tree: Windows `taskkill /F /T /PID`; POSIX `kill -PG` (process group,
18//! since the child is spawned as its own group leader) with fallback to
19//! `kill -PID`. Best-effort, errors swallowed.
20//!
21//! `exec` abort+timeout bracketing (plan §5.4): the spawn is `tokio::select!`-ed
22//! against the cancellation token and `tokio::time::timeout`. Resolution
23//! priority: callbackError → timeout → aborted → exit-code-from-success.
24//! `cleanup()` kills tracked child pids best-effort.
25
26use std::collections::{HashMap, HashSet};
27use std::path::{Path, PathBuf};
28use std::sync::Arc;
29
30use async_trait::async_trait;
31use tokio::sync::Mutex;
32use tokio_util::sync::CancellationToken;
33
34use crate::env::{
35    check_cancel_exec, check_cancel_file, ExecutionEnv, FileContent, FileInfo, FileKind,
36    FileSystem, Shell, ShellExecOptions, ShellOutput,
37};
38use crate::error::{
39    io_to_file_error, ExecutionError, ExecutionErrorCode, FileError, FileErrorCode,
40};
41use crate::file_mutation_queue::{MutatingEnv, MutationQueueRegistry};
42
43/// Max timeout in ms (Int32 max). Mirrors `MAX_TIMEOUT_MS`.
44const MAX_TIMEOUT_MS: u64 = 2_147_483_647;
45/// Max timeout in seconds. Mirrors `MAX_TIMEOUT_SECONDS`.
46const MAX_TIMEOUT_SECONDS: f64 = 2_147_483.647;
47/// Grace period after child exit for trailing stdio. Mirrors
48/// `EXIT_STDIO_GRACE_MS`.
49const EXIT_STDIO_GRACE_MS: u64 = 100;
50
51/// How the command is fed to the shell. Mirrors `commandTransport`.
52#[derive(Clone, Copy)]
53enum CommandTransport {
54    /// Append the command as the last argv element (`bash -c <cmd>`).
55    Argv,
56    /// Pipe the command to the shell's stdin (`bash -s`).
57    Stdin,
58}
59
60/// Resolved shell config. Mirrors `ShellConfig`.
61struct ShellConfig {
62    shell: PathBuf,
63    args: Vec<String>,
64    transport: CommandTransport,
65}
66
67/// Environment variables the **host** sets for its own runtime plumbing, which
68/// must not be handed to a shell it spawns.
69///
70/// A spawned shell is a child process, so anything inherited reaches whatever
71/// that shell runs — including another `rpi`. `RPI_SESSION_ID` names the session
72/// *this process* serves, which is meaningless (and actively misleading) in a
73/// descendant: the child would either report the parent's session or, seeing the
74/// variable already present, refuse to publish its own. Both are wrong answers,
75/// and neither is visible from the child.
76///
77/// This is only the host's own half. An *extension* can publish variables with
78/// the same hazard, and it declares them itself; [`is_host_private_env`] is the
79/// function that answers the full question. Use it rather than reading this
80/// slice, or an extension's channel will be missed — which is precisely the bug
81/// that let `LANGFUSE_PI_PARENT_*` through.
82pub const HOST_PRIVATE_ENV: &[&str] = &[rpi_plugin_sdk::SESSION_ID_ENV];
83
84/// Whether `name` must not be inherited by a spawned shell.
85///
86/// Two sources, because the variables come from two places:
87///
88/// - [`HOST_PRIVATE_ENV`] — the host's own plumbing.
89/// - [`rpi_plugin_sdk::SUBAGENT_PARENT_ENV`] — the family an *extension*
90///   declares for subagent nesting. An inherited copy makes a plain `rpi` started
91///   from inside `bash` adopt its ancestor's trace, hang its root off the
92///   ancestor's root span, and call itself `Subagent Turn` instead of opening its
93///   own trace. A launcher that sets these on the child *it* starts is the
94///   supported nesting path, so this is about not *inheriting* them, not about
95///   forbidding the names.
96///
97/// The extension family is consulted **as the SDK's slice**, never as names
98/// restated here. Restating them is what the previous version did, and it is
99/// how the channel re-leaked when the plugin renamed them: the list went on
100/// matching a name nobody set. Going through the constant means a rename is a
101/// compile error, and a newly added family member is excluded automatically.
102pub fn is_host_private_env(name: &str) -> bool {
103    HOST_PRIVATE_ENV.contains(&name) || rpi_plugin_sdk::SUBAGENT_PARENT_ENV.contains(&name)
104}
105
106/// Real-OS `ExecutionEnv`. Clone shares the tracked-pid set + registry.
107pub struct OsExecutionEnv {
108    cwd: PathBuf,
109    shell_path: Option<PathBuf>,
110    shell_env: Option<HashMap<String, String>>,
111    active_pids: Arc<Mutex<HashSet<u32>>>,
112    registry: Arc<MutationQueueRegistry>,
113}
114
115impl OsExecutionEnv {
116    pub fn new() -> Self {
117        Self {
118            cwd: std::env::current_dir().unwrap_or_else(|_| PathBuf::from("/")),
119            shell_path: None,
120            shell_env: None,
121            active_pids: Arc::new(Mutex::new(HashSet::new())),
122            registry: Arc::new(MutationQueueRegistry::new()),
123        }
124    }
125
126    pub fn with_cwd(cwd: PathBuf) -> Self {
127        Self {
128            cwd,
129            shell_path: None,
130            shell_env: None,
131            active_pids: Arc::new(Mutex::new(HashSet::new())),
132            registry: Arc::new(MutationQueueRegistry::new()),
133        }
134    }
135
136    pub fn with_shell_path(mut self, shell_path: PathBuf) -> Self {
137        self.shell_path = Some(shell_path);
138        self
139    }
140
141    pub fn with_shell_env(mut self, env: HashMap<String, String>) -> Self {
142        self.shell_env = Some(env);
143        self
144    }
145
146    /// Resolve a path (tilde, file://, absolute/relative) against `cwd`. Pure.
147    fn resolve_path(cwd: &Path, path: &str) -> PathBuf {
148        let mut p = path.to_string();
149        // Tilde expansion (literal only).
150        if p == "~" {
151            p = home_dir_string();
152        } else if let Some(rest) = p.strip_prefix("~/") {
153            p = format!("{}/{}", home_dir_string(), rest);
154        } else if cfg!(windows) {
155            if let Some(rest) = p.strip_prefix("~\\") {
156                p = format!("{}\\{}", home_dir_string(), rest);
157            }
158        }
159        // file:// URL → path. Parse failure silently keeps the literal.
160        if p.starts_with("file://") {
161            if let Some(local) = file_url_to_path(&p) {
162                p = local;
163            }
164        }
165        let pb = PathBuf::from(&p);
166        if pb.is_absolute() {
167            normalize_absolute(&pb)
168        } else {
169            normalize_absolute(&cwd.join(pb))
170        }
171    }
172
173    /// Detect + return the shell config, or `ShellUnavailable`. Mirrors
174    /// `getShellConfig`.
175    async fn get_shell_config(&self) -> Result<ShellConfig, ExecutionError> {
176        // Explicit override.
177        if let Some(sp) = &self.shell_path {
178            if tokio::fs::metadata(sp).await.is_ok() {
179                return Ok(bash_shell_config(sp.clone()));
180            }
181            return Err(ExecutionError::new(
182                ExecutionErrorCode::ShellUnavailable,
183                format!("Custom shell path not found: {}", sp.display()),
184            ));
185        }
186        // Windows probe.
187        #[cfg(windows)]
188        {
189            if let Some(cfg) = windows_probe_bash().await {
190                return Ok(cfg);
191            }
192            return Err(ExecutionError::new(
193                ExecutionErrorCode::ShellUnavailable,
194                "bash not found. Install Git for Windows / MSYS2 / Cygwin, or set shellPath.",
195            ));
196        }
197        // POSIX.
198        #[cfg(not(windows))]
199        {
200            if tokio::fs::metadata("/bin/bash").await.is_ok() {
201                return Ok(ShellConfig {
202                    shell: PathBuf::from("/bin/bash"),
203                    args: vec!["-c".to_string()],
204                    transport: CommandTransport::Argv,
205                });
206            }
207            // `which bash` fallback.
208            if let Some(found) =
209                run_command("which", &["bash"], std::time::Duration::from_millis(5000)).await
210            {
211                let trimmed = found.trim();
212                if !trimmed.is_empty() && tokio::fs::metadata(trimmed).await.is_ok() {
213                    return Ok(ShellConfig {
214                        shell: PathBuf::from(trimmed),
215                        args: vec!["-c".to_string()],
216                        transport: CommandTransport::Argv,
217                    });
218                }
219            }
220            // sh fallback.
221            return Ok(ShellConfig {
222                shell: PathBuf::from("sh"),
223                args: vec!["-c".to_string()],
224                transport: CommandTransport::Argv,
225            });
226        }
227    }
228}
229
230impl Default for OsExecutionEnv {
231    fn default() -> Self {
232        Self::new()
233    }
234}
235
236fn home_dir_string() -> String {
237    dirs::home_dir()
238        .map(|p| p.to_string_lossy().into_owned())
239        .unwrap_or_default()
240}
241
242fn normalize_absolute(p: &Path) -> PathBuf {
243    // std::path doesn't expose ".."/"." collapse without canonicalize (which
244    // hits the FS). Rebuild component-by-component.
245    let mut out = PathBuf::new();
246    for comp in p.components() {
247        match comp {
248            std::path::Component::ParentDir => {
249                out.pop();
250            }
251            std::path::Component::CurDir => {}
252            other => out.push(other),
253        }
254    }
255    out
256}
257
258fn file_url_to_path(url: &str) -> Option<String> {
259    // Minimal file:// → path conversion. Handles `file:///abs/path` and
260    // Windows `file:///C:/...`. Parse failure → None (caller keeps literal).
261    let rest = url.strip_prefix("file://")?;
262    if let Some(drive_rest) = rest.strip_prefix('/') {
263        // `/C:/...` (Windows drive) or `/abs/path`.
264        if drive_rest.len() >= 2 && drive_rest.as_bytes()[1] == b':' {
265            return Some(drive_rest.to_string());
266        }
267        return Some(format!("/{}", drive_rest));
268    }
269    Some(rest.to_string())
270}
271
272fn bash_shell_config(shell: PathBuf) -> ShellConfig {
273    if is_legacy_wsl_bash_path(&shell) {
274        ShellConfig {
275            shell,
276            args: vec!["-s".to_string()],
277            transport: CommandTransport::Stdin,
278        }
279    } else {
280        ShellConfig {
281            shell,
282            args: vec!["-c".to_string()],
283            transport: CommandTransport::Argv,
284        }
285    }
286}
287
288fn is_legacy_wsl_bash_path(p: &Path) -> bool {
289    let s = p.to_string_lossy().replace('/', "\\").to_lowercase();
290    let re = regex::Regex::new(r"^[a-z]:\\windows\\(?:system32|sysnative)\\bash\.exe$").unwrap();
291    re.is_match(&s)
292}
293
294#[cfg(windows)]
295async fn windows_probe_bash() -> Option<ShellConfig> {
296    let pf = std::env::var("ProgramFiles").ok();
297    let pf86 = std::env::var("ProgramFiles(x86)").ok();
298    let mut candidates: Vec<PathBuf> = Vec::new();
299    if let Some(p) = pf {
300        candidates.push(PathBuf::from(p).join("Git").join("bin").join("bash.exe"));
301    }
302    if let Some(p) = pf86 {
303        candidates.push(PathBuf::from(p).join("Git").join("bin").join("bash.exe"));
304    }
305    for c in &candidates {
306        if tokio::fs::metadata(c).await.is_ok() {
307            return Some(bash_shell_config(c.clone()));
308        }
309    }
310    // `where bash.exe`.
311    if let Some(found) = run_command(
312        "where",
313        &["bash.exe"],
314        std::time::Duration::from_millis(5000),
315    )
316    .await
317    {
318        let first = found.lines().next().unwrap_or("").trim().to_string();
319        if !first.is_empty() && tokio::fs::metadata(&first).await.is_ok() {
320            return Some(bash_shell_config(PathBuf::from(first)));
321        }
322    }
323    None
324}
325
326/// Run a quick command, capture stdout, with a timeout. Mirrors `runCommand`
327/// (used only by shell detection). Returns `None` on spawn failure / timeout /
328/// empty stdout.
329async fn run_command(cmd: &str, args: &[&str], timeout: std::time::Duration) -> Option<String> {
330    let mut command = tokio::process::Command::new(cmd);
331    command.args(args);
332    command.stdout(std::process::Stdio::piped());
333    command.stderr(std::process::Stdio::null());
334    command.stdin(std::process::Stdio::null());
335    #[cfg(windows)]
336    {
337        // Hide the console window for the probe.
338        use windows_sys::Win32::System::Threading::CREATE_NO_WINDOW;
339        command.creation_flags(CREATE_NO_WINDOW);
340    }
341    let child = command.spawn().ok()?;
342    let out = match tokio::time::timeout(timeout, child.wait_with_output()).await {
343        Ok(Ok(o)) => o,
344        _ => return None,
345    };
346    if !out.status.success() {
347        return None;
348    }
349    let s = String::from_utf8_lossy(&out.stdout).into_owned();
350    if s.trim().is_empty() {
351        None
352    } else {
353        Some(s)
354    }
355}
356
357/// Kill a process tree. Windows: `taskkill /F /T /PID`. POSIX: `kill -PG` with
358/// fallback to `kill -PID`. Best-effort, errors swallowed.
359async fn kill_process_tree(pid: u32) {
360    #[cfg(windows)]
361    {
362        use windows_sys::Win32::System::Threading::CREATE_NO_WINDOW;
363        let mut cmd = tokio::process::Command::new("taskkill");
364        cmd.args(&["/F", "/T", "/PID", &pid.to_string()]);
365        cmd.creation_flags(CREATE_NO_WINDOW);
366        cmd.stdin(std::process::Stdio::null());
367        cmd.stdout(std::process::Stdio::null());
368        cmd.stderr(std::process::Stdio::null());
369        // Wait for taskkill itself to finish. Spawning it fire-and-forget lets
370        // the shell's `child.wait()` race the tree termination, and a listener
371        // can keep its inherited stdout/stderr handles open long enough to
372        // deadlock the capture join after Ctrl+C.
373        let _ = cmd.status().await;
374    }
375    #[cfg(unix)]
376    {
377        use nix::sys::signal::{kill, Signal};
378        use nix::unistd::Pid;
379        // Process group: negative pid.
380        let pg = Pid::from_raw(-(pid as i32));
381        if kill(pg, Signal::SIGKILL).is_err() {
382            let _ = kill(Pid::from_raw(pid as i32), Signal::SIGKILL);
383        }
384    }
385    #[cfg(not(any(windows, unix)))]
386    {
387        let _ = pid;
388    }
389}
390
391#[async_trait]
392impl FileSystem for OsExecutionEnv {
393    fn cwd(&self) -> &Path {
394        &self.cwd
395    }
396
397    async fn absolute_path(
398        &self,
399        path: &str,
400        cancel: Option<&CancellationToken>,
401    ) -> Result<PathBuf, FileError> {
402        check_cancel_file(cancel, Some(path))?;
403        Ok(Self::resolve_path(&self.cwd, path))
404    }
405
406    async fn join_path(
407        &self,
408        parts: &[&str],
409        cancel: Option<&CancellationToken>,
410    ) -> Result<PathBuf, FileError> {
411        check_cancel_file(cancel, None)?;
412        let mut out = PathBuf::new();
413        for p in parts {
414            out.push(p);
415        }
416        Ok(out)
417    }
418
419    async fn read_text_file(
420        &self,
421        path: &str,
422        cancel: Option<&CancellationToken>,
423    ) -> Result<String, FileError> {
424        check_cancel_file(cancel, Some(path))?;
425        let abs = Self::resolve_path(&self.cwd, path);
426        let bytes = read_cancellable(&abs, cancel).await?;
427        String::from_utf8(bytes).map_err(|e| {
428            FileError::new(FileErrorCode::Invalid, format!("invalid utf-8: {e}"))
429                .with_path(abs.to_string_lossy())
430        })
431    }
432
433    async fn read_text_lines(
434        &self,
435        path: &str,
436        max_lines: Option<usize>,
437        cancel: Option<&CancellationToken>,
438    ) -> Result<Vec<String>, FileError> {
439        check_cancel_file(cancel, Some(path))?;
440        if max_lines.map(|m| m == 0).unwrap_or(false) {
441            return Ok(Vec::new());
442        }
443        let text = self.read_text_file(path, cancel).await?;
444        let mut lines: Vec<String> = text.split('\n').map(|s| s.to_string()).collect();
445        if text.ends_with('\n') {
446            if lines.last().map(|s| s.is_empty()).unwrap_or(false) {
447                lines.pop();
448            }
449        }
450        if let Some(m) = max_lines {
451            lines.truncate(m);
452        }
453        Ok(lines)
454    }
455
456    async fn read_binary_file(
457        &self,
458        path: &str,
459        cancel: Option<&CancellationToken>,
460    ) -> Result<Vec<u8>, FileError> {
461        check_cancel_file(cancel, Some(path))?;
462        let abs = Self::resolve_path(&self.cwd, path);
463        read_cancellable(&abs, cancel).await
464    }
465
466    async fn write_file(
467        &self,
468        path: &str,
469        content: FileContent,
470        cancel: Option<&CancellationToken>,
471    ) -> Result<(), FileError> {
472        check_cancel_file(cancel, Some(path))?;
473        let abs = Self::resolve_path(&self.cwd, path);
474        // mkdir parent (recursive).
475        if let Some(parent) = abs.parent() {
476            if !parent.as_os_str().is_empty() {
477                if let Err(e) = tokio::fs::create_dir_all(parent).await {
478                    return Err(io_to_file_error(e, Some(&abs.to_string_lossy())));
479                }
480            }
481        }
482        check_cancel_file(cancel, Some(&abs.to_string_lossy()))?;
483        write_cancellable(&abs, content.as_bytes(), cancel).await
484    }
485
486    async fn append_file(
487        &self,
488        path: &str,
489        content: FileContent,
490        cancel: Option<&CancellationToken>,
491    ) -> Result<(), FileError> {
492        check_cancel_file(cancel, Some(path))?;
493        let abs = Self::resolve_path(&self.cwd, path);
494        if let Some(parent) = abs.parent() {
495            if !parent.as_os_str().is_empty() {
496                let _ = tokio::fs::create_dir_all(parent).await;
497            }
498        }
499        use tokio::io::AsyncWriteExt;
500        let res = match tokio::fs::OpenOptions::new()
501            .create(true)
502            .append(true)
503            .open(&abs)
504            .await
505        {
506            Ok(mut f) => f.write_all(content.as_bytes()).await,
507            Err(e) => return Err(io_to_file_error(e, Some(&abs.to_string_lossy()))),
508        };
509        res.map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))
510    }
511
512    async fn rename_file(
513        &self,
514        source: &str,
515        dest: &str,
516        cancel: Option<&CancellationToken>,
517    ) -> Result<(), FileError> {
518        check_cancel_file(cancel, Some(source))?;
519        let src = Self::resolve_path(&self.cwd, source);
520        let dst = Self::resolve_path(&self.cwd, dest);
521        tokio::fs::rename(&src, &dst)
522            .await
523            .map_err(|e| io_to_file_error(e, Some(&src.to_string_lossy())))
524    }
525
526    async fn file_info(
527        &self,
528        path: &str,
529        cancel: Option<&CancellationToken>,
530    ) -> Result<FileInfo, FileError> {
531        check_cancel_file(cancel, Some(path))?;
532        let abs = Self::resolve_path(&self.cwd, path);
533        let meta = tokio::fs::symlink_metadata(&abs)
534            .await
535            .map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))?;
536        let ft = meta.file_type();
537        let kind = if ft.is_file() {
538            FileKind::File
539        } else if ft.is_dir() {
540            FileKind::Directory
541        } else if ft.is_symlink() {
542            FileKind::Symlink
543        } else {
544            return Err(
545                FileError::new(FileErrorCode::Invalid, "Unsupported file type")
546                    .with_path(abs.to_string_lossy()),
547            );
548        };
549        let mtime_ms = meta
550            .modified()
551            .ok()
552            .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
553            .map(|d| d.as_millis() as i64)
554            .unwrap_or(0);
555        Ok(FileInfo {
556            name: abs
557                .file_name()
558                .map(|n| n.to_string_lossy().into_owned())
559                .unwrap_or_else(|| abs.to_string_lossy().into_owned()),
560            path: abs.clone(),
561            kind,
562            size: meta.len(),
563            mtime_ms,
564        })
565    }
566
567    async fn list_dir(
568        &self,
569        path: &str,
570        cancel: Option<&CancellationToken>,
571    ) -> Result<Vec<FileInfo>, FileError> {
572        check_cancel_file(cancel, Some(path))?;
573        let abs = Self::resolve_path(&self.cwd, path);
574        let mut entries = tokio::fs::read_dir(&abs)
575            .await
576            .map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))?;
577        let mut out = Vec::new();
578        while let Some(entry) = entries
579            .next_entry()
580            .await
581            .map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))?
582        {
583            if let Some(t) = cancel {
584                if t.is_cancelled() {
585                    return Err(FileError::aborted().with_path(abs.to_string_lossy()));
586                }
587            }
588            let ep = entry.path();
589            let meta = match tokio::fs::symlink_metadata(&ep).await {
590                Ok(m) => m,
591                Err(e) => {
592                    // Skip unsupported types silently; propagate real stat errors.
593                    let code = crate::error::io_to_file_code(&e);
594                    if code == FileErrorCode::NotSupported {
595                        continue;
596                    }
597                    return Err(io_to_file_error(e, Some(&ep.to_string_lossy())));
598                }
599            };
600            let ft = meta.file_type();
601            let kind = if ft.is_file() {
602                FileKind::File
603            } else if ft.is_dir() {
604                FileKind::Directory
605            } else if ft.is_symlink() {
606                FileKind::Symlink
607            } else {
608                continue; // silently skip sockets/fifos/etc.
609            };
610            let mtime_ms = meta
611                .modified()
612                .ok()
613                .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
614                .map(|d| d.as_millis() as i64)
615                .unwrap_or(0);
616            out.push(FileInfo {
617                name: entry.file_name().to_string_lossy().into_owned(),
618                path: ep,
619                kind,
620                size: meta.len(),
621                mtime_ms,
622            });
623        }
624        Ok(out)
625    }
626
627    async fn canonical_path(
628        &self,
629        path: &str,
630        cancel: Option<&CancellationToken>,
631    ) -> Result<PathBuf, FileError> {
632        check_cancel_file(cancel, Some(path))?;
633        let abs = Self::resolve_path(&self.cwd, path);
634        tokio::fs::canonicalize(&abs)
635            .await
636            .map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))
637    }
638
639    async fn exists(
640        &self,
641        path: &str,
642        cancel: Option<&CancellationToken>,
643    ) -> Result<bool, FileError> {
644        check_cancel_file(cancel, Some(path))?;
645        let abs = Self::resolve_path(&self.cwd, path);
646        match tokio::fs::symlink_metadata(&abs).await {
647            Ok(_) => Ok(true),
648            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
649            Err(e) => Err(io_to_file_error(e, Some(&abs.to_string_lossy()))),
650        }
651    }
652
653    async fn create_dir(
654        &self,
655        path: &str,
656        recursive: bool,
657        cancel: Option<&CancellationToken>,
658    ) -> Result<(), FileError> {
659        check_cancel_file(cancel, Some(path))?;
660        let abs = Self::resolve_path(&self.cwd, path);
661        let res = if recursive {
662            tokio::fs::create_dir_all(&abs).await
663        } else {
664            tokio::fs::create_dir(&abs).await
665        };
666        res.map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))
667    }
668
669    async fn remove(
670        &self,
671        path: &str,
672        recursive: bool,
673        force: bool,
674        cancel: Option<&CancellationToken>,
675    ) -> Result<(), FileError> {
676        check_cancel_file(cancel, Some(path))?;
677        let abs = Self::resolve_path(&self.cwd, path);
678        let res = if recursive {
679            tokio::fs::remove_dir_all(&abs).await
680        } else {
681            // Try file first, then empty dir.
682            match tokio::fs::remove_file(&abs).await {
683                Ok(()) => Ok(()),
684                Err(_) => tokio::fs::remove_dir(&abs).await,
685            }
686        };
687        match res {
688            Ok(()) => Ok(()),
689            Err(e) if e.kind() == std::io::ErrorKind::NotFound && force => Ok(()),
690            Err(e) => Err(io_to_file_error(e, Some(&abs.to_string_lossy()))),
691        }
692    }
693
694    async fn create_temp_dir(
695        &self,
696        prefix: Option<&str>,
697        cancel: Option<&CancellationToken>,
698    ) -> Result<PathBuf, FileError> {
699        check_cancel_file(cancel, None)?;
700        let prefix = prefix.unwrap_or("tmp-");
701        // Use tempfile's NamedTempFile-less builder for a dir.
702        let tmp =
703            tempfile::tempdir_in(std::env::temp_dir()).map_err(|e| io_to_file_error(e, None))?;
704        // tempfile picks a random name; rename to include the prefix.
705        let path = tmp.path().to_path_buf();
706        std::mem::forget(tmp); // keep the dir alive; caller manages cleanup.
707                               // Build a prefixed sibling.
708        let final_path = std::env::temp_dir().join(format!("{}{}", prefix, random_suffix()));
709        // Rename the tempdir into the prefixed path.
710        if let Err(e) = tokio::fs::rename(&path, &final_path).await {
711            // Fallback: just return the original random path.
712            let _ = e;
713            return Ok(path);
714        }
715        Ok(final_path)
716    }
717
718    async fn create_temp_file(
719        &self,
720        prefix: &str,
721        suffix: &str,
722        cancel: Option<&CancellationToken>,
723    ) -> Result<PathBuf, FileError> {
724        check_cancel_file(cancel, None)?;
725        // Create an isolated temp dir (matching the TS pattern of one dir per
726        // file), then write an empty file named `<prefix><random><suffix>`.
727        let dir = self.create_temp_dir(Some("tmp-"), cancel).await?;
728        let name = format!("{}{}{}", prefix, random_suffix(), suffix);
729        let path = dir.join(name);
730        tokio::fs::File::create(&path)
731            .await
732            .map_err(|e| io_to_file_error(e, Some(&path.to_string_lossy())))?;
733        Ok(path)
734    }
735
736    async fn cleanup(&self) {
737        let pids: Vec<u32> = self.active_pids.lock().await.iter().copied().collect();
738        for pid in pids {
739            kill_process_tree(pid).await;
740        }
741        self.active_pids.lock().await.clear();
742    }
743}
744
745/// Read a file to bytes, honoring cooperative cancellation.
746async fn read_cancellable(
747    path: &Path,
748    cancel: Option<&CancellationToken>,
749) -> Result<Vec<u8>, FileError> {
750    let read = tokio::fs::read(path);
751    let res = match cancel {
752        Some(t) => tokio::select! {
753            r = read => r,
754            _ = t.cancelled() => return Err(FileError::aborted().with_path(path.to_string_lossy())),
755        },
756        None => read.await,
757    };
758    res.map_err(|e| io_to_file_error(e, Some(&path.to_string_lossy())))
759}
760
761/// Write bytes to a file (truncate), honoring cooperative cancellation.
762async fn write_cancellable(
763    path: &Path,
764    bytes: &[u8],
765    cancel: Option<&CancellationToken>,
766) -> Result<(), FileError> {
767    use tokio::io::AsyncWriteExt;
768    let f = tokio::fs::File::create(path)
769        .await
770        .map_err(|e| io_to_file_error(e, Some(&path.to_string_lossy())))?;
771    let write = async {
772        let mut f = f;
773        f.write_all(bytes).await?;
774        f.flush().await?;
775        Ok::<(), std::io::Error>(())
776    };
777    let res = match cancel {
778        Some(t) => tokio::select! {
779            r = write => r,
780            _ = t.cancelled() => return Err(FileError::aborted().with_path(path.to_string_lossy())),
781        },
782        None => write.await,
783    };
784    res.map_err(|e| io_to_file_error(e, Some(&path.to_string_lossy())))
785}
786
787fn random_suffix() -> String {
788    // Short random suffix via uuid v4 (no Time—it's a UUID, not a timestamp).
789    uuid::Uuid::new_v4().simple().to_string()
790}
791
792#[async_trait]
793impl Shell for OsExecutionEnv {
794    async fn exec<'a>(
795        &'a self,
796        command: &str,
797        options: ShellExecOptions<'a>,
798    ) -> Result<ShellOutput, ExecutionError> {
799        // Pre-flight abort.
800        check_cancel_exec(options.cancel)?;
801        // Resolve timeout.
802        let timeout = match resolve_timeout(options.timeout) {
803            Ok(t) => t,
804            Err(e) => return Err(e),
805        };
806        // Resolve cwd.
807        let cwd = match &options.cwd {
808            Some(c) => Self::resolve_path(&self.cwd, &c.to_string_lossy()),
809            None => self.cwd.clone(),
810        };
811        // Shell config. An explicit override is used by native shell tools
812        // such as PowerShell; otherwise preserve the default Bash behavior.
813        let shell_cfg = match &options.shell {
814            Some(override_shell) => ShellConfig {
815                shell: override_shell.program.clone(),
816                args: override_shell.args.clone(),
817                transport: CommandTransport::Argv,
818            },
819            None => self.get_shell_config().await?,
820        };
821        // Verify cwd exists.
822        if !cwd.exists() {
823            return Err(ExecutionError::new(
824                ExecutionErrorCode::SpawnError,
825                format!(
826                    "Working directory does not exist: {}\nCannot execute bash commands.",
827                    cwd.display()
828                ),
829            ));
830        }
831
832        // Build the spawn.
833        let mut cmd = tokio::process::Command::new(&shell_cfg.shell);
834        cmd.current_dir(&cwd);
835        cmd.env_clear();
836        // Environment: inherit + shell_env + per-call. The host's own private
837        // plumbing (`HOST_PRIVATE_ENV`) is skipped: it describes *this* process,
838        // not the shell or anything the shell runs, and inheriting it makes a
839        // nested `rpi` misreport its session. A caller that genuinely wants a
840        // value passed down can still set it explicitly through `env`/`shell_env`
841        // below (those are applied after this loop and win).
842        if options.inherit_env {
843            for (k, v) in std::env::vars() {
844                if is_host_private_env(&k) {
845                    continue;
846                }
847                cmd.env(k, v);
848            }
849        }
850        if let Some(base) = &self.shell_env {
851            for (k, v) in base {
852                cmd.env(k, v);
853            }
854        }
855        if let Some(extra) = &options.env {
856            for (k, v) in extra {
857                cmd.env(k, v);
858            }
859        }
860        // stdio.
861        cmd.stdin(std::process::Stdio::piped());
862        cmd.stdout(std::process::Stdio::piped());
863        cmd.stderr(std::process::Stdio::piped());
864        #[cfg(unix)]
865        {
866            use std::os::unix::process::CommandExt;
867            cmd.process_group(0); // child becomes its own group leader.
868        }
869        #[cfg(windows)]
870        {
871            use windows_sys::Win32::System::Threading::CREATE_NO_WINDOW;
872            cmd.creation_flags(CREATE_NO_WINDOW);
873        }
874
875        // Args: stdin transport → `bash -s` (no command argv); argv → append.
876        let transport = shell_cfg.transport;
877        cmd.args(&shell_cfg.args);
878        if matches!(transport, CommandTransport::Argv) {
879            cmd.arg(command);
880        }
881
882        let mut child = match cmd.spawn() {
883            Ok(c) => c,
884            Err(e) => {
885                return Err(ExecutionError::new(
886                    ExecutionErrorCode::SpawnError,
887                    format!("failed to spawn shell: {e}"),
888                ));
889            }
890        };
891        let pid = child.id();
892        if let Some(pid) = pid {
893            self.active_pids.lock().await.insert(pid);
894        }
895
896        // Stdin transport: write command then close. Closing happens on BOTH
897        // transports, and deliberately: anything that prompts (`npx` asking to
898        // install, `npm init`, a `read` in a script) must see EOF and fail fast,
899        // not block on a pipe that nothing will ever write to or close. tokio's
900        // `Child::wait` also drops stdin as a deadlock guard, but relying on that
901        // would make the guarantee a side effect of an implementation detail.
902        let mut stdin = child.stdin.take();
903        if matches!(transport, CommandTransport::Stdin) {
904            if let Some(stdin) = stdin.as_mut() {
905                use tokio::io::AsyncWriteExt;
906                let _ = stdin.write_all(command.as_bytes()).await;
907                let _ = stdin.flush().await;
908            }
909        }
910        drop(stdin);
911
912        // Collect stdout/stderr via separate read tasks, firing callbacks.
913        let mut stdout_buf = String::new();
914        let mut stderr_buf = String::new();
915        let cancel = options.cancel;
916        let mut on_stdout = options.on_stdout;
917        let mut on_stderr = options.on_stderr;
918
919        let mut stdout = child.stdout.take();
920        let mut stderr = child.stderr.take();
921
922        let stdout_task = async {
923            if let Some(s) = stdout.as_mut() {
924                let mut buf = vec![0u8; 8192];
925                use tokio::io::AsyncReadExt;
926                loop {
927                    let read = s.read(&mut buf);
928                    let read_result = match cancel {
929                        Some(token) => tokio::select! {
930                            result = read => result,
931                            _ = token.cancelled() => break,
932                        },
933                        None => read.await,
934                    };
935                    let n = match read_result {
936                        Ok(0) => break,
937                        Ok(n) => n,
938                        Err(_) => break,
939                    };
940                    let chunk = String::from_utf8_lossy(&buf[..n]).into_owned();
941                    if let Some(cb) = on_stdout.as_mut() {
942                        // Callback errors are swallowed (TS sets callbackError;
943                        // v1 simplifies — the callback contract is best-effort).
944                        cb(&chunk);
945                    }
946                    stdout_buf.push_str(&chunk);
947                }
948            }
949        };
950        let stderr_task = async {
951            if let Some(s) = stderr.as_mut() {
952                let mut buf = vec![0u8; 8192];
953                use tokio::io::AsyncReadExt;
954                loop {
955                    let read = s.read(&mut buf);
956                    let read_result = match cancel {
957                        Some(token) => tokio::select! {
958                            result = read => result,
959                            _ = token.cancelled() => break,
960                        },
961                        None => read.await,
962                    };
963                    let n = match read_result {
964                        Ok(0) => break,
965                        Ok(n) => n,
966                        Err(_) => break,
967                    };
968                    let chunk = String::from_utf8_lossy(&buf[..n]).into_owned();
969                    if let Some(cb) = on_stderr.as_mut() {
970                        cb(&chunk);
971                    }
972                    stderr_buf.push_str(&chunk);
973                }
974            }
975        };
976
977        // Wait for the child, with timeout + cancellation.
978        let mut timed_out = false;
979        let exit_status = {
980            // We pin stdout/stderr take handles + the wait future, then drive
981            // them concurrently inside a single select! block. `child` is only
982            // touched again AFTER the join completes (kill + reap), so the
983            // borrow ends cleanly.
984            let status_fut = async {
985                match (timeout, cancel) {
986                    (Some(to), Some(token)) => {
987                        tokio::select! {
988                            status = child.wait() => status,
989                            _ = tokio::time::sleep(to) => {
990                                timed_out = true;
991                                if let Some(pid) = child.id() {
992                                    kill_process_tree(pid).await;
993                                }
994                                child.wait().await
995                            }
996                            _ = token.cancelled() => {
997                                if let Some(pid) = child.id() {
998                                    kill_process_tree(pid).await;
999                                }
1000                                child.wait().await
1001                            }
1002                        }
1003                    }
1004                    (Some(to), None) => match tokio::time::timeout(to, child.wait()).await {
1005                        Ok(status) => status,
1006                        Err(_) => {
1007                            timed_out = true;
1008                            if let Some(pid) = child.id() {
1009                                kill_process_tree(pid).await;
1010                            }
1011                            child.wait().await
1012                        }
1013                    },
1014                    (None, Some(token)) => {
1015                        tokio::select! {
1016                            status = child.wait() => status,
1017                            _ = token.cancelled() => {
1018                                if let Some(pid) = child.id() {
1019                                    kill_process_tree(pid).await;
1020                                }
1021                                child.wait().await
1022                            }
1023                        }
1024                    }
1025                    (None, None) => child.wait().await,
1026                }
1027            };
1028            // Run stdio + status concurrently — but the CHILD is the driver:
1029            // once it is reaped the command is over, and the call has to end even
1030            // if something else still holds the stdout/stderr pipes open.
1031            //
1032            // This is the "`npm run` 卡住" shape. A script that starts a watcher,
1033            // a dev-server or a background daemon leaves a grandchild running with
1034            // the inherited pipes, so reading to EOF waits for a process the
1035            // command no longer owns. No timeout rescues that: the timeout wraps
1036            // `child.wait()` and the child already exited successfully.
1037            tokio::pin!(status_fut, stdout_task, stderr_task);
1038            let status_res = (&mut status_fut).await;
1039            // Drain what is already in the pipe — a completed write is already in
1040            // the pipe buffer, so this is not a race — then stop, without waiting
1041            // for an EOF that may never come. A command whose own process is gone
1042            // should not be able to hold the call open.
1043            let _ = tokio::time::timeout(
1044                std::time::Duration::from_millis(EXIT_STDIO_GRACE_MS),
1045                async {
1046                    let _ = tokio::join!(&mut stdout_task, &mut stderr_task);
1047                },
1048            )
1049            .await;
1050            status_res
1051        };
1052
1053        // Give trailing stdio a brief grace period. Only the timed-out and
1054        // cancelled paths still owe a wait: on the normal path the drain above
1055        // already capped it.
1056        if timed_out {
1057            let _ = tokio::time::sleep(std::time::Duration::from_millis(EXIT_STDIO_GRACE_MS)).await;
1058        }
1059
1060        // Remove from tracked pids.
1061        if let Some(pid) = pid {
1062            self.active_pids.lock().await.remove(&pid);
1063        }
1064
1065        // Resolution priority: timedOut → cancelled → status.
1066        let status = match exit_status {
1067            Ok(s) => s,
1068            Err(e) => {
1069                return Err(ExecutionError::new(
1070                    ExecutionErrorCode::SpawnError,
1071                    format!("child wait failed: {e}"),
1072                ));
1073            }
1074        };
1075        if timed_out {
1076            return Err(ExecutionError::timeout(
1077                options.timeout.map(|f| f as u64).unwrap_or(0),
1078            ));
1079        }
1080        if cancel.map(|t| t.is_cancelled()).unwrap_or(false) {
1081            return Err(ExecutionError::aborted());
1082        }
1083        let exit_code = status.code().unwrap_or(0);
1084        Ok(ShellOutput {
1085            stdout: stdout_buf,
1086            stderr: stderr_buf,
1087            exit_code,
1088        })
1089    }
1090
1091    async fn cleanup(&self) {
1092        FileSystem::cleanup(self).await
1093    }
1094}
1095
1096#[async_trait]
1097impl ExecutionEnv for OsExecutionEnv {}
1098
1099#[async_trait]
1100impl MutatingEnv for OsExecutionEnv {
1101    fn as_env(&self) -> &dyn ExecutionEnv {
1102        self
1103    }
1104    fn mutation_registry(&self) -> &MutationQueueRegistry {
1105        &self.registry
1106    }
1107}
1108
1109/// Validate a timeout (seconds). Mirrors `resolveTimeoutMs` semantics.
1110fn resolve_timeout(timeout: Option<f64>) -> Result<Option<std::time::Duration>, ExecutionError> {
1111    match timeout {
1112        None => Ok(None),
1113        Some(secs) => {
1114            if !secs.is_finite() || secs <= 0.0 {
1115                return Err(ExecutionError::new(
1116                    ExecutionErrorCode::Timeout,
1117                    "Invalid timeout: must be a finite number of seconds",
1118                ));
1119            }
1120            let ms = secs * 1000.0;
1121            if ms > MAX_TIMEOUT_MS as f64 {
1122                return Err(ExecutionError::new(
1123                    ExecutionErrorCode::Timeout,
1124                    format!(
1125                        "Invalid timeout: maximum is {} seconds",
1126                        MAX_TIMEOUT_SECONDS
1127                    ),
1128                ));
1129            }
1130            Ok(Some(std::time::Duration::from_secs_f64(secs)))
1131        }
1132    }
1133}