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 terminates the shell's job object, falling back to
18//! `taskkill /F /T /PID`; POSIX `kill -PG` (process group, since the child is
19//! spawned as its own group leader) with fallback to `kill -PID`. Best-effort,
20//! errors swallowed.
21//!
22//! `exec` abort+timeout bracketing (plan §5.4): the spawn is `tokio::select!`-ed
23//! against the cancellation token and `tokio::time::timeout`. Resolution
24//! priority: callbackError → timeout → aborted → exit-code-from-success.
25//! `cleanup()` kills tracked child pids best-effort.
26
27use std::collections::{HashMap, HashSet};
28use std::io::{Read, Seek, SeekFrom, Write};
29use std::path::{Path, PathBuf};
30use std::sync::{Arc, Mutex};
31
32use async_trait::async_trait;
33use tokio_util::sync::CancellationToken;
34
35use crate::env::{
36    check_cancel_exec, check_cancel_file, ExecutionEnv, FileContent, FileInfo, FileKind,
37    FileSystem, Shell, ShellExecOptions, ShellOutput, WriterLease,
38};
39use crate::error::{
40    io_to_file_error, ExecutionError, ExecutionErrorCode, FileError, FileErrorCode,
41};
42use crate::file_mutation_queue::{MutatingEnv, MutationQueueRegistry};
43
44/// Max timeout in ms (Int32 max). Mirrors `MAX_TIMEOUT_MS`.
45const MAX_TIMEOUT_MS: u64 = 2_147_483_647;
46/// Max timeout in seconds. Mirrors `MAX_TIMEOUT_SECONDS`.
47const MAX_TIMEOUT_SECONDS: f64 = 2_147_483.647;
48/// Grace period after child exit for trailing stdio. Mirrors
49/// `EXIT_STDIO_GRACE_MS`.
50const EXIT_STDIO_GRACE_MS: u64 = 100;
51
52/// Non-interactive defaults for every spawned shell. A tool call has no
53/// terminal the user can answer: `git` with no credential helper opens
54/// `/dev/tty` directly for `Username for 'https://…':`, bypassing the piped
55/// stdin/stdout/stderr (and the deliberate stdin-close in `exec`). That writes
56/// over the TUI frame as text the editor never owned — so it cannot be selected
57/// or deleted — and blocks the child until the timeout. Failing fast instead
58/// turns it into an ordinary, capturable stderr error.
59///
60/// These are *defaults*, not a policy lock: they are applied before the
61/// inherit loop and before `shell_env` / per-call `env`, so an explicit host
62/// export, `with_shell_env`, or `ShellExecOptions::env` still opts back in.
63/// This is deliberately narrower than the managed-install `harden_git_env`
64/// (which also isolated git config): here the user's own git config and
65/// credential helpers must keep working.
66const NON_INTERACTIVE_SHELL_ENV: &[(&str, &str)] = &[
67    ("GIT_TERMINAL_PROMPT", "0"),
68    ("GCM_INTERACTIVE", "Never"),
69    ("SSH_ASKPASS_REQUIRE", "never"),
70];
71
72/// How the command is fed to the shell. Mirrors `commandTransport`.
73#[derive(Clone, Copy)]
74enum CommandTransport {
75    /// Append the command as the last argv element (`bash -c <cmd>`).
76    Argv,
77    /// Pipe the command to the shell's stdin (`bash -s`).
78    Stdin,
79}
80
81/// Resolved shell config. Mirrors `ShellConfig`.
82struct ShellConfig {
83    shell: PathBuf,
84    args: Vec<String>,
85    transport: CommandTransport,
86}
87
88mod append;
89mod read;
90
91/// The open lock file is the storage-level ownership capability.
92struct OsWriterLease {
93    file: std::fs::File,
94    fence: u64,
95}
96
97#[cfg(unix)]
98impl Drop for OsWriterLease {
99    fn drop(&mut self) {
100        // A child in the fork-to-exec window can still share this open file
101        // description. Unlock even if closing our descriptor is insufficient.
102        let _ = fs2::FileExt::unlock(&self.file);
103    }
104}
105
106impl WriterLease for OsWriterLease {
107    fn verify_fence(&self) -> Result<(), FileError> {
108        let mut probe = self
109            .file
110            .try_clone()
111            .map_err(|error| io_to_file_error(error, Some("writer lease fence")))?;
112        probe
113            .seek(SeekFrom::Start(0))
114            .map_err(|error| io_to_file_error(error, Some("writer lease fence")))?;
115        let mut contents = String::new();
116        probe
117            .read_to_string(&mut contents)
118            .map_err(|error| io_to_file_error(error, Some("writer lease fence")))?;
119        let current = contents.trim().parse::<u64>().map_err(|error| {
120            FileError::new(
121                FileErrorCode::Unknown,
122                format!("invalid persisted writer lease fence: {error}"),
123            )
124        })?;
125        if current != self.fence {
126            return Err(FileError::new(
127                FileErrorCode::PermissionDenied,
128                "writer lease fence changed; reopen the session",
129            ));
130        }
131        Ok(())
132    }
133}
134
135/// Environment variables the **host** sets for its own runtime plumbing, which
136/// must not be handed to a shell it spawns.
137///
138/// A spawned shell is a child process, so anything inherited reaches whatever
139/// that shell runs — including another `rpi`. `RPI_SESSION_ID` names the session
140/// *this process* serves, which is meaningless (and actively misleading) in a
141/// descendant: the child would either report the parent's session or, seeing the
142/// variable already present, refuse to publish its own. Both are wrong answers,
143/// and neither is visible from the child.
144///
145/// This is only the host's own half. An *extension* can publish variables with
146/// the same hazard, and it declares them itself; [`is_host_private_env`] is the
147/// function that answers the full question. Use it rather than reading this
148/// slice, or an extension's channel will be missed — which is precisely the bug
149/// that let `LANGFUSE_PI_PARENT_*` through.
150pub const HOST_PRIVATE_ENV: &[&str] = &[rpi_plugin_sdk::SESSION_ID_ENV];
151
152/// Whether `name` must not be inherited by a spawned shell.
153///
154/// Two sources, because the variables come from two places:
155///
156/// - [`HOST_PRIVATE_ENV`] — the host's own plumbing.
157/// - [`rpi_plugin_sdk::SUBAGENT_PARENT_ENV`] — the family an *extension*
158///   declares for subagent nesting. An inherited copy makes a plain `rpi` started
159///   from inside `bash` adopt its ancestor's trace, hang its root off the
160///   ancestor's root span, and call itself `Subagent Turn` instead of opening its
161///   own trace. A launcher that sets these on the child *it* starts is the
162///   supported nesting path, so this is about not *inheriting* them, not about
163///   forbidding the names.
164///
165/// The extension family is consulted **as the SDK's slice**, never as names
166/// restated here. Restating them is what the previous version did, and it is
167/// how the channel re-leaked when the plugin renamed them: the list went on
168/// matching a name nobody set. Going through the constant means a rename is a
169/// compile error, and a newly added family member is excluded automatically.
170pub fn is_host_private_env(name: &str) -> bool {
171    HOST_PRIVATE_ENV.contains(&name) || rpi_plugin_sdk::SUBAGENT_PARENT_ENV.contains(&name)
172}
173
174/// Real-OS `ExecutionEnv`. Clone shares the tracked-pid set + registry.
175pub struct OsExecutionEnv {
176    cwd: PathBuf,
177    shell_path: Option<PathBuf>,
178    shell_env: Option<HashMap<String, String>>,
179    /// None preserves legacy process inheritance. Some is a closed, immutable
180    /// per-Agent baseline (including HOME for file-path expansion).
181    environment: Option<HashMap<String, String>>,
182    active_pids: Arc<Mutex<HashSet<u32>>>,
183    registry: Arc<MutationQueueRegistry>,
184}
185
186impl OsExecutionEnv {
187    pub fn new() -> Self {
188        Self {
189            cwd: std::env::current_dir().unwrap_or_else(|_| PathBuf::from("/")),
190            shell_path: None,
191            shell_env: None,
192            environment: None,
193            active_pids: Arc::new(Mutex::new(HashSet::new())),
194            registry: Arc::new(MutationQueueRegistry::new()),
195        }
196    }
197
198    pub fn with_cwd(cwd: PathBuf) -> Self {
199        Self {
200            cwd,
201            shell_path: None,
202            shell_env: None,
203            environment: None,
204            active_pids: Arc::new(Mutex::new(HashSet::new())),
205            registry: Arc::new(MutationQueueRegistry::new()),
206        }
207    }
208
209    pub fn with_shell_path(mut self, shell_path: PathBuf) -> Self {
210        self.shell_path = Some(shell_path);
211        self
212    }
213
214    pub fn with_shell_env(mut self, env: HashMap<String, String>) -> Self {
215        self.shell_env = Some(env);
216        self
217    }
218
219    /// Replace process environment inheritance with an explicit frozen baseline.
220    /// Unlike `with_shell_env`, absent keys never fall back to process globals.
221    /// Private host channels remain excluded; explicit shell/per-call overlays
222    /// retain their existing semantics. Hosts must supply an absolute shell path
223    /// as well when shell discovery must not consult ambient PATH.
224    pub fn with_environment(mut self, environment: HashMap<String, String>) -> Self {
225        self.environment = Some(environment);
226        self
227    }
228
229    /// Whether process inheritance and ambient HOME fallback are disabled.
230    pub fn has_explicit_environment(&self) -> bool {
231        self.environment.is_some()
232    }
233
234    /// Resolve a path (tilde, file://, absolute/relative) against `cwd`. Pure.
235    fn resolve_path(&self, path: &str) -> PathBuf {
236        let cwd = &self.cwd;
237        let home = || match &self.environment {
238            Some(environment) => environment
239                .get(if cfg!(windows) { "USERPROFILE" } else { "HOME" })
240                .cloned()
241                .unwrap_or_default(),
242            None => home_dir_string(),
243        };
244        let mut p = path.to_string();
245        // Tilde expansion (literal only). A missing HOME in a closed baseline
246        // leaves the tilde literal; it must not turn `~/x` into `/x` or consult
247        // another Agent's ambient home directory.
248        if p == "~" {
249            let home = home();
250            if self.environment.is_none() || !home.is_empty() {
251                p = home;
252            }
253        } else if let Some(rest) = p.strip_prefix("~/") {
254            let home = home();
255            if self.environment.is_none() || !home.is_empty() {
256                p = format!("{home}/{rest}");
257            }
258        } else if cfg!(windows) {
259            if let Some(rest) = p.strip_prefix("~\\") {
260                let home = home();
261                if self.environment.is_none() || !home.is_empty() {
262                    p = format!("{home}\\{rest}");
263                }
264            }
265        }
266        // file:// URL → path. Parse failure silently keeps the literal.
267        if p.starts_with("file://") {
268            if let Some(local) = file_url_to_path(&p) {
269                p = local;
270            }
271        }
272        let pb = PathBuf::from(&p);
273        if pb.is_absolute() {
274            normalize_absolute(&pb)
275        } else {
276            normalize_absolute(&cwd.join(pb))
277        }
278    }
279
280    /// Detect + return the shell config, or `ShellUnavailable`. Mirrors
281    /// `getShellConfig`.
282    async fn get_shell_config(&self) -> Result<ShellConfig, ExecutionError> {
283        // Explicit override. Shell discovery happens on the hot path immediately
284        // before spawning a command. Keep this probe synchronous: putting a
285        // `tokio::fs` metadata future here can queue work on Tokio's blocking
286        // pool and leave a tool run waiting before it has even created a child.
287        if let Some(sp) = &self.shell_path {
288            if sp.is_file() {
289                return Ok(bash_shell_config(sp.clone()));
290            }
291            return Err(ExecutionError::new(
292                ExecutionErrorCode::ShellUnavailable,
293                format!("Custom shell path not found: {}", sp.display()),
294            ));
295        }
296        // Windows probe.
297        #[cfg(windows)]
298        {
299            if let Some(cfg) = windows_probe_bash().await {
300                return Ok(cfg);
301            }
302            return Err(ExecutionError::new(
303                ExecutionErrorCode::ShellUnavailable,
304                "bash not found. Install Git for Windows / MSYS2 / Cygwin, or set shellPath.",
305            ));
306        }
307        // POSIX.
308        #[cfg(not(windows))]
309        {
310            if std::path::Path::new("/bin/bash").is_file() {
311                return Ok(ShellConfig {
312                    shell: PathBuf::from("/bin/bash"),
313                    args: vec!["-c".to_string()],
314                    transport: CommandTransport::Argv,
315                });
316            }
317            // `which bash` fallback.
318            if let Some(found) =
319                run_command("which", &["bash"], std::time::Duration::from_millis(5000)).await
320            {
321                let trimmed = found.trim();
322                if !trimmed.is_empty() && std::path::Path::new(trimmed).is_file() {
323                    return Ok(ShellConfig {
324                        shell: PathBuf::from(trimmed),
325                        args: vec!["-c".to_string()],
326                        transport: CommandTransport::Argv,
327                    });
328                }
329            }
330            // sh fallback.
331            return Ok(ShellConfig {
332                shell: PathBuf::from("sh"),
333                args: vec!["-c".to_string()],
334                transport: CommandTransport::Argv,
335            });
336        }
337    }
338}
339
340impl Default for OsExecutionEnv {
341    fn default() -> Self {
342        Self::new()
343    }
344}
345
346fn home_dir_string() -> String {
347    dirs::home_dir()
348        .map(|p| p.to_string_lossy().into_owned())
349        .unwrap_or_default()
350}
351
352fn normalize_absolute(p: &Path) -> PathBuf {
353    // std::path doesn't expose ".."/"." collapse without canonicalize (which
354    // hits the FS). Rebuild component-by-component.
355    let mut out = PathBuf::new();
356    for comp in p.components() {
357        match comp {
358            std::path::Component::ParentDir => {
359                out.pop();
360            }
361            std::path::Component::CurDir => {}
362            other => out.push(other),
363        }
364    }
365    out
366}
367
368fn file_url_to_path(url: &str) -> Option<String> {
369    // Minimal file:// → path conversion. Handles `file:///abs/path` and
370    // Windows `file:///C:/...`. Parse failure → None (caller keeps literal).
371    let rest = url.strip_prefix("file://")?;
372    if let Some(drive_rest) = rest.strip_prefix('/') {
373        // `/C:/...` (Windows drive) or `/abs/path`.
374        if drive_rest.len() >= 2 && drive_rest.as_bytes()[1] == b':' {
375            return Some(drive_rest.to_string());
376        }
377        return Some(format!("/{}", drive_rest));
378    }
379    Some(rest.to_string())
380}
381
382fn bash_shell_config(shell: PathBuf) -> ShellConfig {
383    if is_legacy_wsl_bash_path(&shell) {
384        ShellConfig {
385            shell,
386            args: vec!["-s".to_string()],
387            transport: CommandTransport::Stdin,
388        }
389    } else {
390        ShellConfig {
391            shell,
392            args: vec!["-c".to_string()],
393            transport: CommandTransport::Argv,
394        }
395    }
396}
397
398fn is_legacy_wsl_bash_path(p: &Path) -> bool {
399    let s = p.to_string_lossy().replace('/', "\\").to_lowercase();
400    let re = regex::Regex::new(r"^[a-z]:\\windows\\(?:system32|sysnative)\\bash\.exe$").unwrap();
401    re.is_match(&s)
402}
403
404#[cfg(windows)]
405async fn windows_probe_bash() -> Option<ShellConfig> {
406    let pf = std::env::var("ProgramFiles").ok();
407    let pf86 = std::env::var("ProgramFiles(x86)").ok();
408    let mut candidates: Vec<PathBuf> = Vec::new();
409    if let Some(p) = pf {
410        candidates.push(PathBuf::from(p).join("Git").join("bin").join("bash.exe"));
411    }
412    if let Some(p) = pf86 {
413        candidates.push(PathBuf::from(p).join("Git").join("bin").join("bash.exe"));
414    }
415    for c in &candidates {
416        if tokio::fs::metadata(c).await.is_ok() {
417            return Some(bash_shell_config(c.clone()));
418        }
419    }
420    // `where bash.exe`.
421    if let Some(found) = run_command(
422        "where",
423        &["bash.exe"],
424        std::time::Duration::from_millis(5000),
425    )
426    .await
427    {
428        let first = found.lines().next().unwrap_or("").trim().to_string();
429        if !first.is_empty() && tokio::fs::metadata(&first).await.is_ok() {
430            return Some(bash_shell_config(PathBuf::from(first)));
431        }
432    }
433    None
434}
435
436/// Run a quick command, capture stdout, with a timeout. Mirrors `runCommand`
437/// (used only by shell detection). Returns `None` on spawn failure / timeout /
438/// empty stdout.
439async fn run_command(cmd: &str, args: &[&str], timeout: std::time::Duration) -> Option<String> {
440    let mut command = tokio::process::Command::new(cmd);
441    command.args(args);
442    command.stdout(std::process::Stdio::piped());
443    command.stderr(std::process::Stdio::null());
444    command.stdin(std::process::Stdio::null());
445    #[cfg(windows)]
446    {
447        // Hide the console window for the probe.
448        use windows_sys::Win32::System::Threading::CREATE_NO_WINDOW;
449        command.creation_flags(CREATE_NO_WINDOW);
450    }
451    let child = command.spawn().ok()?;
452    let out = match tokio::time::timeout(timeout, child.wait_with_output()).await {
453        Ok(Ok(o)) => o,
454        _ => return None,
455    };
456    if !out.status.success() {
457        return None;
458    }
459    // `where` prints paths in the console code page (e.g. a Chinese user name).
460    let s = crate::output_decode::decode_output(&out.stdout);
461    if s.trim().is_empty() {
462        None
463    } else {
464        Some(s)
465    }
466}
467
468/// One job object per running shell, by root pid. `taskkill /T` walks parent
469/// pids, and an MSYS shell's children are not on that chain: `sleep` under Git
470/// Bash outlives it. Job membership is inherited by every descendant.
471///
472/// Kill-on-close is armed only when killing, so whatever a command leaves
473/// running on purpose keeps running after it ends normally.
474#[cfg(windows)]
475mod shell_jobs {
476    use std::collections::HashMap;
477    use std::sync::{LazyLock, Mutex};
478
479    use win32job::{ExtendedLimitInfo, Job};
480
481    static JOBS: LazyLock<Mutex<HashMap<u32, Job>>> = LazyLock::new(Default::default);
482
483    /// Put a shell spawned with `CREATE_SUSPENDED` in its own job, then let it
484    /// run: no descendant can start outside the job. A shell that gets no job
485    /// still runs, and cancelling it falls back to `taskkill`.
486    pub fn start(pid: u32, process: std::os::windows::io::RawHandle) -> Result<(), String> {
487        if let Ok(job) = Job::create() {
488            if job.assign_process(process as isize).is_ok() {
489                JOBS.lock().unwrap().insert(pid, job);
490            }
491        }
492        rpi_plugin_sdk::process::resume_child(pid)
493    }
494
495    /// End every process in `pid`'s job: arm kill-on-close, then drop the only
496    /// handle. False when `pid` has no job or arming failed.
497    pub fn terminate(pid: u32) -> bool {
498        let Some(job) = JOBS.lock().unwrap().remove(&pid) else {
499            return false;
500        };
501        let mut info = ExtendedLimitInfo::new();
502        info.limit_kill_on_job_close();
503        job.set_extended_limit_info(&info).is_ok()
504    }
505
506    pub fn forget(pid: u32) {
507        JOBS.lock().unwrap().remove(&pid);
508    }
509}
510
511// A tool or harness can drop exec before its cancellation branch is polled.
512// Own the process group until wait() has actually reaped the shell. The guard
513// must be synchronous: Drop runs while the async execution future is unwinding.
514struct ShellProcessGuard {
515    pid: Option<u32>,
516    active: Arc<Mutex<HashSet<u32>>>,
517}
518impl ShellProcessGuard {
519    fn finish(&mut self) {
520        if let Some(pid) = self.pid.take() {
521            #[cfg(windows)]
522            shell_jobs::forget(pid);
523            self.active
524                .lock()
525                .unwrap_or_else(|e| e.into_inner())
526                .remove(&pid);
527        }
528    }
529}
530impl Drop for ShellProcessGuard {
531    fn drop(&mut self) {
532        if let Some(pid) = self.pid {
533            #[cfg(unix)]
534            {
535                use nix::sys::signal::{kill, Signal};
536                use nix::unistd::Pid;
537                // Every shell is spawned into its own process group. No
538                // unrelated session or successful background command is killed.
539                let _ = kill(Pid::from_raw(-(pid as i32)), Signal::SIGKILL);
540            }
541            #[cfg(windows)]
542            shell_jobs::terminate(pid);
543            self.finish();
544        }
545    }
546}
547
548/// Kill a process tree. Windows: the shell's job object, else
549/// `taskkill /F /T /PID`. POSIX: `kill -PG` with fallback to `kill -PID`.
550/// Best-effort, errors swallowed.
551async fn kill_process_tree(pid: u32) {
552    #[cfg(windows)]
553    {
554        if shell_jobs::terminate(pid) {
555            return;
556        }
557        use windows_sys::Win32::System::Threading::CREATE_NO_WINDOW;
558        let mut cmd = tokio::process::Command::new("taskkill");
559        cmd.args(&["/F", "/T", "/PID", &pid.to_string()]);
560        cmd.creation_flags(CREATE_NO_WINDOW);
561        cmd.stdin(std::process::Stdio::null());
562        cmd.stdout(std::process::Stdio::null());
563        cmd.stderr(std::process::Stdio::null());
564        // Wait for taskkill itself to finish. Spawning it fire-and-forget lets
565        // the shell's `child.wait()` race the tree termination, and a listener
566        // can keep its inherited stdout/stderr handles open long enough to
567        // deadlock the capture join after Ctrl+C.
568        let _ = cmd.status().await;
569    }
570    #[cfg(unix)]
571    {
572        use nix::sys::signal::{kill, Signal};
573        use nix::unistd::Pid;
574        // Process group: negative pid.
575        let pg = Pid::from_raw(-(pid as i32));
576        if kill(pg, Signal::SIGKILL).is_err() {
577            let _ = kill(Pid::from_raw(pid as i32), Signal::SIGKILL);
578        }
579    }
580    #[cfg(not(any(windows, unix)))]
581    {
582        let _ = pid;
583    }
584}
585
586#[async_trait]
587impl FileSystem for OsExecutionEnv {
588    fn native_file_path(&self, path: &str) -> Option<PathBuf> {
589        #[cfg(unix)]
590        return Some(self.resolve_path(path));
591        #[cfg(not(unix))]
592        {
593            let _ = path;
594            None
595        }
596    }
597
598    async fn try_acquire_writer_lease(
599        &self,
600        path: &str,
601    ) -> Result<Option<Box<dyn WriterLease>>, FileError> {
602        let session_path = self.resolve_path(path);
603        let lock_path = PathBuf::from(format!("{}.lock", session_path.display()));
604        let display_path = session_path.to_string_lossy().into_owned();
605        tokio::task::spawn_blocking(move || {
606            use fs2::FileExt;
607            let mut file = std::fs::OpenOptions::new()
608                .create(true)
609                .read(true)
610                .write(true)
611                .open(&lock_path)
612                .map_err(|error| io_to_file_error(error, Some(&lock_path.to_string_lossy())))?;
613            file.try_lock_exclusive().map_err(|error| {
614                FileError::new(
615                    FileErrorCode::PermissionDenied,
616                    format!("writer lease is already held for {display_path}"),
617                )
618                .with_path(lock_path.to_string_lossy())
619                .with_source(Box::new(error))
620            })?;
621            file.seek(SeekFrom::Start(0))
622                .map_err(|error| io_to_file_error(error, Some(&lock_path.to_string_lossy())))?;
623            let mut contents = String::new();
624            file.read_to_string(&mut contents)
625                .map_err(|error| io_to_file_error(error, Some(&lock_path.to_string_lossy())))?;
626            let previous = if contents.trim().is_empty() {
627                0
628            } else {
629                contents.trim().parse::<u64>().map_err(|error| {
630                    FileError::new(
631                        FileErrorCode::Unknown,
632                        format!("invalid persisted writer lease fence: {error}"),
633                    )
634                    .with_path(lock_path.to_string_lossy())
635                })?
636            };
637            let fence = previous.checked_add(1).ok_or_else(|| {
638                FileError::new(FileErrorCode::Unknown, "writer lease fence exhausted")
639                    .with_path(lock_path.to_string_lossy())
640            })?;
641            file.seek(SeekFrom::Start(0))
642                .and_then(|_| file.set_len(0))
643                .and_then(|_| file.write_all(fence.to_string().as_bytes()))
644                .and_then(|_| file.sync_all())
645                .map_err(|error| io_to_file_error(error, Some(&lock_path.to_string_lossy())))?;
646            Ok(Some(
647                Box::new(OsWriterLease { file, fence }) as Box<dyn WriterLease>
648            ))
649        })
650        .await
651        .map_err(|error| {
652            FileError::new(
653                FileErrorCode::Unknown,
654                format!("writer lease task failed: {error}"),
655            )
656            .with_path(session_path.to_string_lossy())
657        })?
658    }
659
660    async fn sync_file(
661        &self,
662        path: &str,
663        data_only: bool,
664        cancel: Option<&CancellationToken>,
665    ) -> Result<(), FileError> {
666        check_cancel_file(cancel, Some(path))?;
667        let abs = self.resolve_path(path);
668        let error_path = abs.to_string_lossy().into_owned();
669        let io_path = error_path.clone();
670        tokio::task::spawn_blocking(move || {
671            let file = std::fs::OpenOptions::new()
672                .read(true)
673                .write(true)
674                .open(&abs)
675                .map_err(|error| io_to_file_error(error, Some(&io_path)))?;
676            if data_only {
677                file.sync_data()
678                    .map_err(|error| io_to_file_error(error, Some(&io_path)))
679            } else {
680                file.sync_all()
681                    .map_err(|error| io_to_file_error(error, Some(&io_path)))
682            }
683        })
684        .await
685        .map_err(|error| {
686            FileError::new(
687                FileErrorCode::Unknown,
688                format!("file sync task failed: {error}"),
689            )
690            .with_path(error_path)
691        })??;
692        Ok(())
693    }
694
695    async fn sync_directory(
696        &self,
697        path: &str,
698        cancel: Option<&CancellationToken>,
699    ) -> Result<(), FileError> {
700        check_cancel_file(cancel, Some(path))?;
701        let abs = self.resolve_path(path);
702        #[cfg(unix)]
703        {
704            let error_path = abs.to_string_lossy().into_owned();
705            let io_path = error_path.clone();
706            tokio::task::spawn_blocking(move || {
707                std::fs::File::open(&abs)
708                    .map_err(|error| io_to_file_error(error, Some(&io_path)))?
709                    .sync_all()
710                    .map_err(|error| io_to_file_error(error, Some(&io_path)))
711            })
712            .await
713            .map_err(|error| {
714                FileError::new(
715                    FileErrorCode::Unknown,
716                    format!("directory sync task failed: {error}"),
717                )
718                .with_path(error_path)
719            })??;
720        }
721        #[cfg(not(unix))]
722        {
723            // Windows has no portable directory-handle fsync equivalent in
724            // this abstraction. File contents are still synced above, but
725            // rename-directory durability remains unproved on this target.
726            let _ = abs;
727        }
728        Ok(())
729    }
730
731    async fn sync_file_and_parent(
732        &self,
733        path: &str,
734        cancel: Option<&CancellationToken>,
735    ) -> Result<(), FileError> {
736        check_cancel_file(cancel, Some(path))?;
737        #[cfg(unix)]
738        {
739            let abs = self.resolve_path(path);
740            let info = self.file_info(path, cancel).await?;
741            if info.kind != FileKind::File {
742                return Err(FileError::new(
743                    FileErrorCode::NotSupported,
744                    "journal synchronization requires a regular file",
745                )
746                .with_path(path));
747            }
748            // Use the existing OS implementations, not the compatibility no-op
749            // defaults. Both errors propagate; a file-only sync is not success.
750            self.sync_file(path, false, cancel).await?;
751            let parent = abs.parent().ok_or_else(|| {
752                FileError::new(
753                    FileErrorCode::NotSupported,
754                    "journal has no parent directory",
755                )
756                .with_path(path)
757            })?;
758            self.sync_directory(&parent.to_string_lossy(), cancel).await
759        }
760        #[cfg(not(unix))]
761        {
762            // The legacy directory sync is a no-op on Windows. Do not promote
763            // that compatibility behavior into a physical persistence proof.
764            Err(FileError::new(
765                FileErrorCode::NotSupported,
766                "physical journal synchronization is unsupported on this platform",
767            )
768            .with_path(path))
769        }
770    }
771
772    async fn open_append_file(
773        &self,
774        path: &str,
775    ) -> Result<Option<Box<dyn crate::env::AppendFile>>, FileError> {
776        let path = self.resolve_path(path);
777        Ok(Some(Box::new(append::OsAppendFile::open(path).await?)))
778    }
779
780    async fn open_read_file(
781        &self,
782        path: &str,
783    ) -> Result<Option<Arc<dyn crate::env::ReadFile>>, FileError> {
784        let path = self.resolve_path(path);
785        Ok(Some(Arc::new(read::OsReadFile::open(path).await?)))
786    }
787
788    async fn truncate_file(
789        &self,
790        path: &str,
791        len: u64,
792        cancel: Option<&CancellationToken>,
793    ) -> Result<(), FileError> {
794        check_cancel_file(cancel, Some(path))?;
795        let abs = self.resolve_path(path);
796        let error_path = abs.to_string_lossy().into_owned();
797        tokio::task::spawn_blocking(move || {
798            let file = std::fs::OpenOptions::new().write(true).open(&abs)?;
799            if len > file.metadata()?.len() {
800                return Err(std::io::Error::new(
801                    std::io::ErrorKind::InvalidInput,
802                    "truncation cannot grow a file",
803                ));
804            }
805            file.set_len(len)
806        })
807        .await
808        .map_err(|error| {
809            FileError::new(
810                FileErrorCode::Unknown,
811                format!("file truncation task failed: {error}"),
812            )
813        })?
814        .map_err(|error| io_to_file_error(error, Some(&error_path)))
815    }
816
817    fn cwd(&self) -> &Path {
818        &self.cwd
819    }
820
821    async fn absolute_path(
822        &self,
823        path: &str,
824        cancel: Option<&CancellationToken>,
825    ) -> Result<PathBuf, FileError> {
826        check_cancel_file(cancel, Some(path))?;
827        Ok(self.resolve_path(path))
828    }
829
830    async fn join_path(
831        &self,
832        parts: &[&str],
833        cancel: Option<&CancellationToken>,
834    ) -> Result<PathBuf, FileError> {
835        check_cancel_file(cancel, None)?;
836        let mut out = PathBuf::new();
837        for p in parts {
838            out.push(p);
839        }
840        Ok(out)
841    }
842
843    async fn read_text_file(
844        &self,
845        path: &str,
846        cancel: Option<&CancellationToken>,
847    ) -> Result<String, FileError> {
848        check_cancel_file(cancel, Some(path))?;
849        let abs = self.resolve_path(path);
850        let bytes = read_cancellable(&abs, cancel).await?;
851        String::from_utf8(bytes).map_err(|e| {
852            FileError::new(FileErrorCode::Invalid, format!("invalid utf-8: {e}"))
853                .with_path(abs.to_string_lossy())
854        })
855    }
856
857    async fn read_text_file_bounded(
858        &self,
859        path: &str,
860        max_bytes: usize,
861        cancel: Option<&CancellationToken>,
862    ) -> Result<Option<String>, FileError> {
863        check_cancel_file(cancel, Some(path))?;
864        let abs = self.resolve_path(path);
865        read::read_text_file_bounded(&abs, max_bytes, cancel).await
866    }
867
868    async fn read_text_lines(
869        &self,
870        path: &str,
871        max_lines: Option<usize>,
872        cancel: Option<&CancellationToken>,
873    ) -> Result<Vec<String>, FileError> {
874        check_cancel_file(cancel, Some(path))?;
875        if max_lines.map(|m| m == 0).unwrap_or(false) {
876            return Ok(Vec::new());
877        }
878        let abs = self.resolve_path(path);
879        read::read_text_lines(&abs, max_lines, cancel).await
880    }
881
882    async fn read_binary_file(
883        &self,
884        path: &str,
885        cancel: Option<&CancellationToken>,
886    ) -> Result<Vec<u8>, FileError> {
887        check_cancel_file(cancel, Some(path))?;
888        let abs = self.resolve_path(path);
889        read_cancellable(&abs, cancel).await
890    }
891
892    async fn write_file(
893        &self,
894        path: &str,
895        content: FileContent,
896        cancel: Option<&CancellationToken>,
897    ) -> Result<(), FileError> {
898        check_cancel_file(cancel, Some(path))?;
899        let abs = self.resolve_path(path);
900        // mkdir parent (recursive).
901        if let Some(parent) = abs.parent() {
902            if !parent.as_os_str().is_empty() {
903                if let Err(e) = tokio::fs::create_dir_all(parent).await {
904                    return Err(io_to_file_error(e, Some(&abs.to_string_lossy())));
905                }
906            }
907        }
908        check_cancel_file(cancel, Some(&abs.to_string_lossy()))?;
909        write_cancellable(abs, content, cancel).await
910    }
911
912    async fn write_new_file(
913        &self,
914        path: &str,
915        content: FileContent,
916        cancel: Option<&CancellationToken>,
917    ) -> Result<(), FileError> {
918        check_cancel_file(cancel, Some(path))?;
919        let abs = self.resolve_path(path);
920        let cancel = cancel.cloned();
921        // One owned blocking operation retains the opened descriptor even if
922        // its async waiter disappears. O_EXCL/create_new is the authority: no
923        // separate metadata check, parent mkdir, truncation or cleanup unlink.
924        tokio::task::spawn_blocking(move || {
925            let display = abs.to_string_lossy();
926            check_cancel_file(cancel.as_ref(), Some(&display))?;
927            let mut options = std::fs::OpenOptions::new();
928            options.write(true).create_new(true);
929            #[cfg(unix)]
930            {
931                use std::os::unix::fs::OpenOptionsExt;
932                options.mode(0o600);
933            }
934            let mut file = options
935                .open(&abs)
936                .map_err(|error| io_to_file_error(error, Some(&display)))?;
937            for chunk in content.as_bytes().chunks(64 * 1024) {
938                check_cancel_file(cancel.as_ref(), Some(&display))?;
939                file.write_all(chunk)
940                    .map_err(|error| io_to_file_error(error, Some(&display)))?;
941            }
942            file.flush()
943                .map_err(|error| io_to_file_error(error, Some(&display)))
944        })
945        .await
946        .map_err(|_| {
947            FileError::new(
948                FileErrorCode::Unknown,
949                "exclusive file creation task stopped",
950            )
951        })?
952    }
953
954    async fn append_file(
955        &self,
956        path: &str,
957        content: FileContent,
958        cancel: Option<&CancellationToken>,
959    ) -> Result<(), FileError> {
960        check_cancel_file(cancel, Some(path))?;
961        let abs = self.resolve_path(path);
962        if let Some(parent) = abs.parent() {
963            if !parent.as_os_str().is_empty() {
964                let _ = tokio::fs::create_dir_all(parent).await;
965            }
966        }
967        use tokio::io::AsyncWriteExt;
968        let res = match tokio::fs::OpenOptions::new()
969            .create(true)
970            .append(true)
971            .open(&abs)
972            .await
973        {
974            Ok(mut f) => {
975                // Tokio may acknowledge a buffered write before the blocking
976                // filesystem operation completes. Await it before returning so
977                // an immediate read/metadata call observes the appended bytes.
978                match f.write_all(content.as_bytes()).await {
979                    Ok(()) => f.flush().await,
980                    Err(error) => Err(error),
981                }
982            }
983            Err(e) => return Err(io_to_file_error(e, Some(&abs.to_string_lossy()))),
984        };
985        res.map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))
986    }
987
988    async fn rename_file(
989        &self,
990        source: &str,
991        dest: &str,
992        cancel: Option<&CancellationToken>,
993    ) -> Result<(), FileError> {
994        check_cancel_file(cancel, Some(source))?;
995        let src = self.resolve_path(source);
996        let dst = self.resolve_path(dest);
997        tokio::fs::rename(&src, &dst)
998            .await
999            .map_err(|e| io_to_file_error(e, Some(&src.to_string_lossy())))
1000    }
1001
1002    async fn file_info(
1003        &self,
1004        path: &str,
1005        cancel: Option<&CancellationToken>,
1006    ) -> Result<FileInfo, FileError> {
1007        check_cancel_file(cancel, Some(path))?;
1008        let abs = self.resolve_path(path);
1009        let meta = tokio::fs::symlink_metadata(&abs)
1010            .await
1011            .map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))?;
1012        let ft = meta.file_type();
1013        let kind = if ft.is_file() {
1014            FileKind::File
1015        } else if ft.is_dir() {
1016            FileKind::Directory
1017        } else if ft.is_symlink() {
1018            FileKind::Symlink
1019        } else {
1020            return Err(
1021                FileError::new(FileErrorCode::Invalid, "Unsupported file type")
1022                    .with_path(abs.to_string_lossy()),
1023            );
1024        };
1025        let mtime_ms = meta
1026            .modified()
1027            .ok()
1028            .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1029            .map(|d| d.as_millis() as i64)
1030            .unwrap_or(0);
1031        Ok(FileInfo {
1032            name: abs
1033                .file_name()
1034                .map(|n| n.to_string_lossy().into_owned())
1035                .unwrap_or_else(|| abs.to_string_lossy().into_owned()),
1036            path: abs.clone(),
1037            kind,
1038            size: meta.len(),
1039            mtime_ms,
1040        })
1041    }
1042
1043    async fn list_dir(
1044        &self,
1045        path: &str,
1046        cancel: Option<&CancellationToken>,
1047    ) -> Result<Vec<FileInfo>, FileError> {
1048        check_cancel_file(cancel, Some(path))?;
1049        let abs = self.resolve_path(path);
1050        let mut entries = tokio::fs::read_dir(&abs)
1051            .await
1052            .map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))?;
1053        let mut out = Vec::new();
1054        while let Some(entry) = entries
1055            .next_entry()
1056            .await
1057            .map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))?
1058        {
1059            if let Some(t) = cancel {
1060                if t.is_cancelled() {
1061                    return Err(FileError::aborted().with_path(abs.to_string_lossy()));
1062                }
1063            }
1064            let ep = entry.path();
1065            let meta = match tokio::fs::symlink_metadata(&ep).await {
1066                Ok(m) => m,
1067                Err(e) => {
1068                    // Skip unsupported types silently; propagate real stat errors.
1069                    let code = crate::error::io_to_file_code(&e);
1070                    if code == FileErrorCode::NotSupported {
1071                        continue;
1072                    }
1073                    return Err(io_to_file_error(e, Some(&ep.to_string_lossy())));
1074                }
1075            };
1076            let ft = meta.file_type();
1077            let kind = if ft.is_file() {
1078                FileKind::File
1079            } else if ft.is_dir() {
1080                FileKind::Directory
1081            } else if ft.is_symlink() {
1082                FileKind::Symlink
1083            } else {
1084                continue; // silently skip sockets/fifos/etc.
1085            };
1086            let mtime_ms = meta
1087                .modified()
1088                .ok()
1089                .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1090                .map(|d| d.as_millis() as i64)
1091                .unwrap_or(0);
1092            out.push(FileInfo {
1093                name: entry.file_name().to_string_lossy().into_owned(),
1094                path: ep,
1095                kind,
1096                size: meta.len(),
1097                mtime_ms,
1098            });
1099        }
1100        Ok(out)
1101    }
1102
1103    async fn has_file_with_suffix(
1104        &self,
1105        path: &str,
1106        suffix: &str,
1107        cancel: Option<&CancellationToken>,
1108    ) -> Result<bool, FileError> {
1109        check_cancel_file(cancel, Some(path))?;
1110        let abs = self.resolve_path(path);
1111        let error_path = abs.to_string_lossy().into_owned();
1112        let suffix = String::from(suffix);
1113        let cancel = cancel.cloned();
1114        // One blocking job, not one lstat + runtime round-trip per entry. Session
1115        // existence checks need names/types only, not every sidecar's metadata.
1116        tokio::task::spawn_blocking(move || {
1117            check_cancel_file(cancel.as_ref(), Some(&abs.to_string_lossy()))?;
1118            let entries = std::fs::read_dir(&abs)
1119                .map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))?;
1120            for entry in entries {
1121                check_cancel_file(cancel.as_ref(), Some(&abs.to_string_lossy()))?;
1122                let entry = entry.map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))?;
1123                if !entry.file_name().to_string_lossy().ends_with(&suffix) {
1124                    continue;
1125                }
1126                let kind = match entry.file_type() {
1127                    Ok(kind) => kind,
1128                    Err(error)
1129                        if crate::error::io_to_file_code(&error) == FileErrorCode::NotSupported =>
1130                    {
1131                        continue
1132                    }
1133                    Err(error) => {
1134                        return Err(io_to_file_error(
1135                            error,
1136                            Some(&entry.path().to_string_lossy()),
1137                        ))
1138                    }
1139                };
1140                check_cancel_file(cancel.as_ref(), Some(&abs.to_string_lossy()))?;
1141                if kind.is_file() || kind.is_symlink() {
1142                    return Ok(true);
1143                }
1144            }
1145            check_cancel_file(cancel.as_ref(), Some(&abs.to_string_lossy()))?;
1146            Ok(false)
1147        })
1148        .await
1149        .map_err(|error| {
1150            FileError::new(
1151                FileErrorCode::Unknown,
1152                format!("directory scan task failed: {error}"),
1153            )
1154            .with_path(error_path)
1155        })?
1156    }
1157
1158    async fn canonical_path(
1159        &self,
1160        path: &str,
1161        cancel: Option<&CancellationToken>,
1162    ) -> Result<PathBuf, FileError> {
1163        check_cancel_file(cancel, Some(path))?;
1164        let abs = self.resolve_path(path);
1165        tokio::fs::canonicalize(&abs)
1166            .await
1167            .map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))
1168    }
1169
1170    async fn exists(
1171        &self,
1172        path: &str,
1173        cancel: Option<&CancellationToken>,
1174    ) -> Result<bool, FileError> {
1175        check_cancel_file(cancel, Some(path))?;
1176        let abs = self.resolve_path(path);
1177        match tokio::fs::symlink_metadata(&abs).await {
1178            Ok(_) => Ok(true),
1179            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
1180            Err(e) => Err(io_to_file_error(e, Some(&abs.to_string_lossy()))),
1181        }
1182    }
1183
1184    async fn create_dir(
1185        &self,
1186        path: &str,
1187        recursive: bool,
1188        cancel: Option<&CancellationToken>,
1189    ) -> Result<(), FileError> {
1190        check_cancel_file(cancel, Some(path))?;
1191        let abs = self.resolve_path(path);
1192        let res = if recursive {
1193            tokio::fs::create_dir_all(&abs).await
1194        } else {
1195            tokio::fs::create_dir(&abs).await
1196        };
1197        res.map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))
1198    }
1199
1200    async fn remove(
1201        &self,
1202        path: &str,
1203        recursive: bool,
1204        force: bool,
1205        cancel: Option<&CancellationToken>,
1206    ) -> Result<(), FileError> {
1207        check_cancel_file(cancel, Some(path))?;
1208        let abs = self.resolve_path(path);
1209        let res = if recursive {
1210            tokio::fs::remove_dir_all(&abs).await
1211        } else {
1212            // Try file first, then empty dir.
1213            match tokio::fs::remove_file(&abs).await {
1214                Ok(()) => Ok(()),
1215                Err(_) => tokio::fs::remove_dir(&abs).await,
1216            }
1217        };
1218        match res {
1219            Ok(()) => Ok(()),
1220            Err(e) if e.kind() == std::io::ErrorKind::NotFound && force => Ok(()),
1221            Err(e) => Err(io_to_file_error(e, Some(&abs.to_string_lossy()))),
1222        }
1223    }
1224
1225    async fn create_temp_dir(
1226        &self,
1227        prefix: Option<&str>,
1228        cancel: Option<&CancellationToken>,
1229    ) -> Result<PathBuf, FileError> {
1230        check_cancel_file(cancel, None)?;
1231        let prefix = prefix.unwrap_or("tmp-");
1232        // Use tempfile's NamedTempFile-less builder for a dir.
1233        let tmp =
1234            tempfile::tempdir_in(std::env::temp_dir()).map_err(|e| io_to_file_error(e, None))?;
1235        // tempfile picks a random name; rename to include the prefix.
1236        let path = tmp.path().to_path_buf();
1237        std::mem::forget(tmp); // keep the dir alive; caller manages cleanup.
1238                               // Build a prefixed sibling.
1239        let final_path = std::env::temp_dir().join(format!("{}{}", prefix, random_suffix()));
1240        // Rename the tempdir into the prefixed path.
1241        if let Err(e) = tokio::fs::rename(&path, &final_path).await {
1242            // Fallback: just return the original random path.
1243            let _ = e;
1244            return Ok(path);
1245        }
1246        Ok(final_path)
1247    }
1248
1249    async fn create_temp_file(
1250        &self,
1251        prefix: &str,
1252        suffix: &str,
1253        cancel: Option<&CancellationToken>,
1254    ) -> Result<PathBuf, FileError> {
1255        check_cancel_file(cancel, None)?;
1256        // Create an isolated temp dir (matching the TS pattern of one dir per
1257        // file), then write an empty file named `<prefix><random><suffix>`.
1258        let dir = self.create_temp_dir(Some("tmp-"), cancel).await?;
1259        let name = format!("{}{}{}", prefix, random_suffix(), suffix);
1260        let path = dir.join(name);
1261        tokio::fs::File::create(&path)
1262            .await
1263            .map_err(|e| io_to_file_error(e, Some(&path.to_string_lossy())))?;
1264        Ok(path)
1265    }
1266
1267    async fn cleanup(&self) {
1268        let pids: Vec<u32> = self
1269            .active_pids
1270            .lock()
1271            .unwrap_or_else(|e| e.into_inner())
1272            .iter()
1273            .copied()
1274            .collect();
1275        for pid in pids {
1276            kill_process_tree(pid).await;
1277        }
1278        self.active_pids
1279            .lock()
1280            .unwrap_or_else(|e| e.into_inner())
1281            .clear();
1282    }
1283}
1284
1285/// Read a file to bytes, honoring cooperative cancellation.
1286async fn read_cancellable(
1287    path: &Path,
1288    cancel: Option<&CancellationToken>,
1289) -> Result<Vec<u8>, FileError> {
1290    let read = tokio::fs::read(path);
1291    let res = match cancel {
1292        Some(t) => tokio::select! {
1293            r = read => r,
1294            _ = t.cancelled() => return Err(FileError::aborted().with_path(path.to_string_lossy())),
1295        },
1296        None => read.await,
1297    };
1298    res.map_err(|e| io_to_file_error(e, Some(&path.to_string_lossy())))
1299}
1300
1301/// Observe cancellation immediately before opening the destination. Once
1302/// truncation can begin, wait for the write and report its actual I/O result.
1303async fn write_cancellable(
1304    path: PathBuf,
1305    content: FileContent,
1306    cancel: Option<&CancellationToken>,
1307) -> Result<(), FileError> {
1308    let task_path = path.clone();
1309    let cancel = cancel.cloned();
1310    tokio::task::spawn_blocking(move || {
1311        let path = task_path.to_string_lossy();
1312        check_cancel_file(cancel.as_ref(), Some(&path))?;
1313        let write = || -> std::io::Result<()> {
1314            let mut file = std::fs::File::create(&task_path)?;
1315            file.write_all(content.as_bytes())?;
1316            file.flush()
1317        };
1318        write().map_err(|error| io_to_file_error(error, Some(&path)))
1319    })
1320    .await
1321    .map_err(|error| {
1322        FileError::new(FileErrorCode::Unknown, "file write task failed")
1323            .with_path(path.to_string_lossy())
1324            .with_source(Box::new(error))
1325    })?
1326}
1327
1328fn random_suffix() -> String {
1329    // Short random suffix via uuid v4 (no Time—it's a UUID, not a timestamp).
1330    uuid::Uuid::new_v4().simple().to_string()
1331}
1332
1333async fn drain_shell_pipe(
1334    pipe: Option<impl tokio::io::AsyncRead + Unpin>,
1335    mut callback: Option<Box<dyn FnMut(&str) + Send + '_>>,
1336    retained: &mut String,
1337    streamed: Option<&tokio::sync::mpsc::Sender<String>>,
1338    shell_exited: &CancellationToken,
1339    cancel: Option<&CancellationToken>,
1340) {
1341    use tokio::io::AsyncReadExt;
1342    use tokio::time::{timeout, Duration, Instant};
1343
1344    let Some(mut pipe) = pipe else { return };
1345    let mut buffer = [0u8; 8192];
1346    let mut decoder = crate::output_decode::StreamDecoder::new();
1347    let mut drain_budget = Duration::from_millis(EXIT_STDIO_GRACE_MS);
1348    let cancelled = async {
1349        match cancel {
1350            Some(token) => token.cancelled().await,
1351            None => std::future::pending::<()>().await,
1352        }
1353    };
1354    tokio::pin!(cancelled);
1355    loop {
1356        let read = async {
1357            let read = pipe.read(&mut buffer);
1358            tokio::pin!(read);
1359            tokio::select! {
1360                biased;
1361                _ = shell_exited.cancelled() => {},
1362                result = &mut read => return result.unwrap_or(0),
1363            }
1364
1365            // Apply the post-exit budget only to reading the pipe. Time spent
1366            // delivering a chunk to a slow consumer must not cut off later reads.
1367            if drain_budget.is_zero() {
1368                return 0;
1369            }
1370            let started = Instant::now();
1371            let result = timeout(drain_budget, &mut read).await;
1372            drain_budget = drain_budget.saturating_sub(started.elapsed());
1373            result.ok().and_then(Result::ok).unwrap_or(0)
1374        };
1375        let count = tokio::select! {
1376            biased;
1377            _ = &mut cancelled => 0,
1378            count = read => count,
1379        };
1380        let chunk = if count == 0 {
1381            decoder.finish()
1382        } else {
1383            decoder.push(&buffer[..count])
1384        };
1385        if !chunk.is_empty() {
1386            if let Some(callback) = callback.as_mut() {
1387                callback(&chunk);
1388            }
1389            if let Some(sender) = streamed {
1390                let _ = sender.send(chunk).await;
1391            } else {
1392                retained.push_str(&chunk);
1393            }
1394        }
1395        if count == 0 {
1396            break;
1397        }
1398    }
1399}
1400
1401impl OsExecutionEnv {
1402    async fn exec_inner(
1403        &self,
1404        command: &str,
1405        options: ShellExecOptions<'_>,
1406        streamed: Option<tokio::sync::mpsc::Sender<String>>,
1407    ) -> Result<ShellOutput, ExecutionError> {
1408        // Pre-flight abort.
1409        check_cancel_exec(options.cancel)?;
1410        // Resolve timeout.
1411        let timeout = match resolve_timeout(options.timeout) {
1412            Ok(t) => t,
1413            Err(e) => return Err(e),
1414        };
1415        // Resolve cwd.
1416        let cwd = match &options.cwd {
1417            Some(c) => self.resolve_path(&c.to_string_lossy()),
1418            None => self.cwd.clone(),
1419        };
1420        // Shell config. An explicit override is used by native shell tools
1421        // such as PowerShell; otherwise preserve the default Bash behavior.
1422        let shell_cfg = match &options.shell {
1423            Some(override_shell) => ShellConfig {
1424                shell: override_shell.program.clone(),
1425                args: override_shell.args.clone(),
1426                transport: CommandTransport::Argv,
1427            },
1428            None => self.get_shell_config().await?,
1429        };
1430        self.exec_configured(command, options, streamed, shell_cfg, timeout, cwd)
1431            .await
1432    }
1433
1434    async fn exec_configured(
1435        &self,
1436        command: &str,
1437        options: ShellExecOptions<'_>,
1438        streamed: Option<tokio::sync::mpsc::Sender<String>>,
1439        shell_cfg: ShellConfig,
1440        timeout: Option<std::time::Duration>,
1441        cwd: PathBuf,
1442    ) -> Result<ShellOutput, ExecutionError> {
1443        // Verify cwd exists.
1444        if !cwd.exists() {
1445            return Err(ExecutionError::new(
1446                ExecutionErrorCode::SpawnError,
1447                format!(
1448                    "Working directory does not exist: {}\nCannot execute bash commands.",
1449                    cwd.display()
1450                ),
1451            ));
1452        }
1453
1454        check_cancel_exec(options.cancel)?;
1455        // Build the spawn.
1456        let mut cmd = tokio::process::Command::new(&shell_cfg.shell);
1457        cmd.current_dir(&cwd);
1458        cmd.env_clear();
1459        // Non-interactive defaults apply even when `inherit_env` is false: a
1460        // caller asking for a clean environment is not asking for a prompt.
1461        // They sit before the inherit loop so any explicit value wins.
1462        for (k, v) in NON_INTERACTIVE_SHELL_ENV {
1463            cmd.env(k, v);
1464        }
1465        // Environment: inherit + shell_env + per-call. The host's own private
1466        // plumbing (`HOST_PRIVATE_ENV`) is skipped: it describes *this* process,
1467        // not the shell or anything the shell runs, and inheriting it makes a
1468        // nested `rpi` misreport its session. A caller that genuinely wants a
1469        // value passed down can still set it explicitly through `env`/`shell_env`
1470        // below (those are applied after this loop and win).
1471        if options.inherit_env {
1472            let mut inherit = |name: &str, value: &str| {
1473                if !is_host_private_env(name) {
1474                    cmd.env(name, value);
1475                }
1476            };
1477            match &self.environment {
1478                Some(environment) => {
1479                    for (name, value) in environment {
1480                        inherit(name, value);
1481                    }
1482                }
1483                None => {
1484                    for (name, value) in std::env::vars() {
1485                        inherit(&name, &value);
1486                    }
1487                }
1488            }
1489        }
1490        if let Some(base) = &self.shell_env {
1491            for (k, v) in base {
1492                cmd.env(k, v);
1493            }
1494        }
1495        if let Some(extra) = &options.env {
1496            for (k, v) in extra {
1497                cmd.env(k, v);
1498            }
1499        }
1500        // stdio.
1501        cmd.kill_on_drop(true);
1502        cmd.stdout(std::process::Stdio::piped());
1503        cmd.stderr(std::process::Stdio::piped());
1504        #[cfg(unix)]
1505        {
1506            cmd.process_group(0); // child becomes its own group leader.
1507        }
1508        #[cfg(windows)]
1509        {
1510            use windows_sys::Win32::System::Threading::{CREATE_NO_WINDOW, CREATE_SUSPENDED};
1511            // Suspended until it is in its job (see `shell_jobs::start`).
1512            cmd.creation_flags(CREATE_NO_WINDOW | CREATE_SUSPENDED);
1513        }
1514
1515        cmd.args(&shell_cfg.args);
1516        match shell_cfg.transport {
1517            CommandTransport::Argv => {
1518                // Commands given as arguments have no input. Provide EOF from
1519                // spawn, even while another thread is launching a process.
1520                cmd.stdin(std::process::Stdio::null());
1521                cmd.arg(command);
1522            }
1523            CommandTransport::Stdin => {
1524                // Legacy WSL bash reads the script from stdin via `bash -s`.
1525                cmd.stdin(std::process::Stdio::piped());
1526            }
1527        }
1528
1529        let mut child = match cmd.spawn() {
1530            Ok(c) => c,
1531            Err(e) => {
1532                return Err(ExecutionError::new(
1533                    ExecutionErrorCode::SpawnError,
1534                    format!("failed to spawn shell: {e}"),
1535                ));
1536            }
1537        };
1538        let pid = child.id();
1539        let mut process_guard = ShellProcessGuard {
1540            pid,
1541            active: self.active_pids.clone(),
1542        };
1543        #[cfg(windows)]
1544        {
1545            let started = match (pid, child.raw_handle()) {
1546                (Some(pid), Some(process)) => shell_jobs::start(pid, process),
1547                _ => Err("the shell has no process handle".to_owned()),
1548            };
1549            if let Err(error) = started {
1550                if let Some(pid) = pid {
1551                    shell_jobs::forget(pid);
1552                }
1553                let _ = child.start_kill();
1554                return Err(ExecutionError::new(
1555                    ExecutionErrorCode::SpawnError,
1556                    format!("failed to start shell: {error}"),
1557                ));
1558            }
1559        }
1560        if let Some(pid) = pid {
1561            self.active_pids
1562                .lock()
1563                .unwrap_or_else(|e| e.into_inner())
1564                .insert(pid);
1565        }
1566
1567        let stdin = child.stdin.take();
1568        let stop_input = CancellationToken::new();
1569        let deadline = timeout.map(|duration| tokio::time::Instant::now() + duration);
1570        let mut stdout_buf = String::new();
1571        let mut stderr_buf = String::new();
1572        let cancel = options.cancel;
1573        let shell_exited = CancellationToken::new();
1574        let stdout_task = drain_shell_pipe(
1575            child.stdout.take(),
1576            options.on_stdout,
1577            &mut stdout_buf,
1578            streamed.as_ref(),
1579            &shell_exited,
1580            cancel,
1581        );
1582        let stderr_task = drain_shell_pipe(
1583            child.stderr.take(),
1584            options.on_stderr,
1585            &mut stderr_buf,
1586            streamed.as_ref(),
1587            &shell_exited,
1588            cancel,
1589        );
1590
1591        // Drive script input, both output pipes, and process termination
1592        // together. A shell can fill an output pipe before reading more stdin.
1593        let mut timed_out = false;
1594        let exit_status = {
1595            let status_fut = async {
1596                let expired = async {
1597                    match deadline {
1598                        Some(at) => tokio::time::sleep_until(at).await,
1599                        None => std::future::pending::<()>().await,
1600                    }
1601                };
1602                let cancelled = async {
1603                    match cancel {
1604                        Some(token) => token.cancelled().await,
1605                        None => std::future::pending::<()>().await,
1606                    }
1607                };
1608                tokio::select! {
1609                    status = child.wait() => return status,
1610                    () = expired => timed_out = true,
1611                    () = cancelled => {}
1612                }
1613                stop_input.cancel();
1614                if let Some(pid) = child.id() {
1615                    kill_process_tree(pid).await;
1616                }
1617                child.wait().await
1618            };
1619            tokio::pin!(status_fut, stdout_task, stderr_task);
1620            let (mut stdout_done, mut stderr_done) = (false, false);
1621            let status_res = {
1622                let stdin_task = async {
1623                    let Some(mut stdin) = stdin else { return };
1624                    use tokio::io::AsyncWriteExt;
1625
1626                    // Dropping the pipe signals EOF to bash -s. A shell that
1627                    // exits early can close it first and still report its own
1628                    // exit status.
1629                    tokio::select! {
1630                        biased;
1631                        () = stop_input.cancelled() => {}
1632                        () = async {
1633                            if stdin.write_all(command.as_bytes()).await.is_ok() {
1634                                let _ = stdin.flush().await;
1635                            }
1636                        } => {}
1637                    }
1638                };
1639                tokio::pin!(stdin_task);
1640                let mut stdin_done = false;
1641                loop {
1642                    tokio::select! {
1643                        status = &mut status_fut => break status,
1644                        () = &mut stdin_task, if !stdin_done => stdin_done = true,
1645                        () = &mut stdout_task, if !stdout_done => stdout_done = true,
1646                        () = &mut stderr_task, if !stderr_done => stderr_done = true,
1647                    }
1648                }
1649            };
1650            // Disarm immediately after a successful wait, before any await:
1651            // the shell has been reaped and its PID may now be reused.
1652            if status_res.is_ok() {
1653                process_guard.finish();
1654            }
1655            // Each reader now limits time spent on its pipe so an inherited
1656            // pipe can't hold the call open. Join both readers through delivery.
1657            shell_exited.cancel();
1658            tokio::join!(
1659                async {
1660                    if !stdout_done {
1661                        (&mut stdout_task).await;
1662                    }
1663                },
1664                async {
1665                    if !stderr_done {
1666                        (&mut stderr_task).await;
1667                    }
1668                },
1669            );
1670            status_res
1671        };
1672
1673        // Give trailing stdio a brief grace period. Only the timed-out and
1674        // cancelled paths still owe a wait: on the normal path the drain above
1675        // already capped it.
1676        if timed_out {
1677            let _ = tokio::time::sleep(std::time::Duration::from_millis(EXIT_STDIO_GRACE_MS)).await;
1678        }
1679
1680        // Resolution priority: timedOut → cancelled → status.
1681        let status = match exit_status {
1682            Ok(s) => s,
1683            Err(e) => {
1684                return Err(ExecutionError::new(
1685                    ExecutionErrorCode::SpawnError,
1686                    format!("child wait failed: {e}"),
1687                ));
1688            }
1689        };
1690        if timed_out {
1691            return Err(ExecutionError::timeout(
1692                options.timeout.map(|f| f as u64).unwrap_or(0),
1693            ));
1694        }
1695        if cancel.map(|t| t.is_cancelled()).unwrap_or(false) {
1696            return Err(ExecutionError::aborted());
1697        }
1698        let exit_code = status.code().unwrap_or(0);
1699        Ok(ShellOutput {
1700            stdout: stdout_buf,
1701            stderr: stderr_buf,
1702            exit_code,
1703        })
1704    }
1705}
1706
1707#[async_trait]
1708impl Shell for OsExecutionEnv {
1709    async fn exec<'a>(
1710        &'a self,
1711        command: &str,
1712        options: ShellExecOptions<'a>,
1713    ) -> Result<ShellOutput, ExecutionError> {
1714        self.exec_inner(command, options, None).await
1715    }
1716
1717    async fn exec_streamed<'a>(
1718        &'a self,
1719        command: &str,
1720        options: ShellExecOptions<'a>,
1721        output: tokio::sync::mpsc::Sender<String>,
1722    ) -> Result<i32, ExecutionError> {
1723        self.exec_inner(command, options, Some(output))
1724            .await
1725            .map(|result| result.exit_code)
1726    }
1727
1728    async fn cleanup(&self) {
1729        FileSystem::cleanup(self).await
1730    }
1731}
1732
1733#[async_trait]
1734impl ExecutionEnv for OsExecutionEnv {}
1735
1736#[async_trait]
1737impl MutatingEnv for OsExecutionEnv {
1738    fn as_env(&self) -> &dyn ExecutionEnv {
1739        self
1740    }
1741    fn mutation_registry(&self) -> &MutationQueueRegistry {
1742        &self.registry
1743    }
1744}
1745
1746#[cfg(test)]
1747mod stdin_transport_tests {
1748    use super::*;
1749    use std::time::Duration;
1750
1751    fn long_script(first: &str, last: &str) -> String {
1752        format!(
1753            "{first}\n{}{last}\n",
1754            "# benign stdin pipe fixture data\n".repeat(64 * 1024)
1755        )
1756    }
1757
1758    async fn exec_stdin(
1759        env: &OsExecutionEnv,
1760        script: &str,
1761        options: ShellExecOptions<'_>,
1762    ) -> Result<ShellOutput, ExecutionError> {
1763        let config = ShellConfig {
1764            shell: env.get_shell_config().await?.shell,
1765            args: vec!["-s".to_owned()],
1766            transport: CommandTransport::Stdin,
1767        };
1768        let timeout = resolve_timeout(options.timeout)?;
1769        env.exec_configured(script, options, None, config, timeout, env.cwd.clone())
1770            .await
1771    }
1772
1773    #[tokio::test]
1774    async fn stdin_transport_drains_output_while_sending_the_script() {
1775        let temp = tempfile::tempdir().unwrap();
1776        let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
1777        let script = long_script(
1778            "head -c 262144 /dev/zero | tr '\\0' a; head -c 262144 /dev/zero | tr '\\0' b >&2",
1779            "printf 'end of script'",
1780        );
1781        let output = tokio::time::timeout(
1782            Duration::from_secs(4),
1783            exec_stdin(
1784                &env,
1785                &script,
1786                ShellExecOptions {
1787                    timeout: Some(3.0),
1788                    ..Default::default()
1789                },
1790            ),
1791        )
1792        .await
1793        .expect("shell blocked feeding stdin while its output pipes were full");
1794        let output = match output {
1795            Err(error) if error.code == ExecutionErrorCode::ShellUnavailable => return,
1796            output => output.unwrap(),
1797        };
1798        assert_eq!(output.exit_code, 0);
1799        assert_eq!(output.stdout.len(), 262144 + "end of script".len());
1800        assert!(output.stdout.ends_with("end of script"));
1801        assert_eq!(output.stderr.len(), 262144);
1802        assert!(output.stderr.bytes().all(|byte| byte == b'b'));
1803    }
1804
1805    #[tokio::test]
1806    async fn stdin_transport_timeout_covers_blocked_script_upload() {
1807        let temp = tempfile::tempdir().unwrap();
1808        let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
1809        let script = long_script("sleep 30", "printf 'unexpected completion'");
1810        let error = tokio::time::timeout(
1811            Duration::from_secs(3),
1812            exec_stdin(
1813                &env,
1814                &script,
1815                ShellExecOptions {
1816                    timeout: Some(0.15),
1817                    ..Default::default()
1818                },
1819            ),
1820        )
1821        .await
1822        .expect("command timeout did not start while stdin was blocked")
1823        .unwrap_err();
1824        if error.code == ExecutionErrorCode::ShellUnavailable {
1825            return;
1826        }
1827        assert_eq!(error.code, ExecutionErrorCode::Timeout);
1828    }
1829
1830    #[tokio::test]
1831    async fn stdin_transport_cancellation_covers_blocked_script_upload() {
1832        let temp = tempfile::tempdir().unwrap();
1833        let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
1834        let script = long_script("sleep 30", "printf 'unexpected completion'");
1835        let signal = CancellationToken::new();
1836        let (result, ()) = tokio::join!(
1837            tokio::time::timeout(
1838                Duration::from_secs(3),
1839                exec_stdin(
1840                    &env,
1841                    &script,
1842                    ShellExecOptions {
1843                        cancel: Some(&signal),
1844                        ..Default::default()
1845                    },
1846                ),
1847            ),
1848            async {
1849                tokio::time::sleep(Duration::from_millis(150)).await;
1850                signal.cancel();
1851            },
1852        );
1853        let error = result
1854            .expect("cancellation was not observed while stdin was blocked")
1855            .unwrap_err();
1856        if error.code == ExecutionErrorCode::ShellUnavailable {
1857            return;
1858        }
1859        assert_eq!(error.code, ExecutionErrorCode::Aborted);
1860    }
1861
1862    #[tokio::test]
1863    async fn stdin_transport_keeps_a_deliberate_early_exit_code() {
1864        let temp = tempfile::tempdir().unwrap();
1865        let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
1866        let script = long_script(
1867            "printf 'early exit'; exit 7",
1868            "printf 'unexpected completion'",
1869        );
1870        let result = tokio::time::timeout(
1871            Duration::from_secs(3),
1872            exec_stdin(&env, &script, ShellExecOptions::default()),
1873        )
1874        .await
1875        .expect("shell blocked after closing its stdin");
1876        let output = match result {
1877            Err(error) if error.code == ExecutionErrorCode::ShellUnavailable => return,
1878            output => output.unwrap(),
1879        };
1880        assert_eq!(output.exit_code, 7);
1881        assert_eq!(output.stdout, "early exit");
1882    }
1883}
1884
1885#[cfg(test)]
1886mod durability_tests {
1887    use super::*;
1888
1889    #[test]
1890    fn queued_overwrite_cancelled_before_open_preserves_existing_bytes() {
1891        let runtime = tokio::runtime::Builder::new_current_thread()
1892            .enable_all()
1893            .max_blocking_threads(1)
1894            .build()
1895            .unwrap();
1896        runtime.block_on(async {
1897            let temp = tempfile::tempdir().unwrap();
1898            let path = temp.path().join("note.txt");
1899            std::fs::write(&path, b"original").unwrap();
1900            let (entered_tx, entered_rx) = tokio::sync::oneshot::channel();
1901            let (release_tx, release_rx) = std::sync::mpsc::channel();
1902            let blocker = tokio::task::spawn_blocking(move || {
1903                entered_tx.send(()).unwrap();
1904                release_rx.recv().unwrap();
1905            });
1906            entered_rx.await.unwrap();
1907
1908            let signal = CancellationToken::new();
1909            let write = write_cancellable(
1910                path.clone(),
1911                FileContent::Text("replacement".into()),
1912                Some(&signal),
1913            );
1914            tokio::pin!(write);
1915            let queued = futures::poll!(&mut write).is_pending();
1916            signal.cancel();
1917            release_tx.send(()).unwrap();
1918            blocker.await.unwrap();
1919
1920            assert!(queued, "overwrite should be queued on the blocking pool");
1921            let result = write.await;
1922            let contents = std::fs::read(&path).unwrap();
1923            assert_eq!(
1924                contents, b"original",
1925                "queued cancellation changed the file (write result: {result:?})"
1926            );
1927            assert_eq!(result.unwrap_err().code, FileErrorCode::Aborted);
1928        });
1929    }
1930
1931    #[tokio::test]
1932    async fn os_backend_syncs_staged_file_and_publication_directory() {
1933        let temp = tempfile::tempdir().unwrap();
1934        let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
1935        env.write_file("staged", FileContent::Text("durable slice".into()), None)
1936            .await
1937            .unwrap();
1938        env.sync_file("staged", false, None).await.unwrap();
1939        env.sync_directory(".", None).await.unwrap();
1940    }
1941
1942    #[tokio::test]
1943    async fn os_writer_lease_persists_and_verifies_a_monotonic_fence() {
1944        let temp = tempfile::tempdir().unwrap();
1945        let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
1946        let first = env
1947            .try_acquire_writer_lease("journal.jsonl")
1948            .await
1949            .unwrap()
1950            .unwrap();
1951        first.verify_fence().unwrap();
1952        drop(first);
1953        let second = env
1954            .try_acquire_writer_lease("journal.jsonl")
1955            .await
1956            .unwrap()
1957            .unwrap();
1958        second.verify_fence().unwrap();
1959        drop(second);
1960        assert_eq!(
1961            std::fs::read_to_string(temp.path().join("journal.jsonl.lock")).unwrap(),
1962            "2"
1963        );
1964    }
1965
1966    #[cfg(unix)]
1967    #[tokio::test]
1968    async fn os_writer_lease_releases_a_shared_open_file_description() {
1969        let temp = tempfile::tempdir().unwrap();
1970        let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
1971        let lock = temp.path().join("journal.jsonl.lock");
1972        std::fs::write(&lock, "1").unwrap();
1973        let file = std::fs::OpenOptions::new()
1974            .read(true)
1975            .write(true)
1976            .open(&lock)
1977            .unwrap();
1978        fs2::FileExt::try_lock_exclusive(&file).unwrap();
1979        let inherited = file.try_clone().unwrap();
1980        let lease = OsWriterLease { file, fence: 1 };
1981        assert!(env.try_acquire_writer_lease("journal.jsonl").await.is_err());
1982        drop(lease);
1983        let next = env
1984            .try_acquire_writer_lease("journal.jsonl")
1985            .await
1986            .expect("retired writer retained a lock through the shared description")
1987            .unwrap();
1988        next.verify_fence().unwrap();
1989        assert_eq!(std::fs::read_to_string(lock).unwrap(), "2");
1990        drop(inherited);
1991    }
1992}
1993
1994/// Validate a timeout (seconds). Mirrors `resolveTimeoutMs` semantics.
1995fn resolve_timeout(timeout: Option<f64>) -> Result<Option<std::time::Duration>, ExecutionError> {
1996    match timeout {
1997        None => Ok(None),
1998        Some(secs) => {
1999            if !secs.is_finite() || secs <= 0.0 {
2000                return Err(ExecutionError::new(
2001                    ExecutionErrorCode::Timeout,
2002                    "Invalid timeout: must be a finite number of seconds",
2003                ));
2004            }
2005            let ms = secs * 1000.0;
2006            if ms > MAX_TIMEOUT_MS as f64 {
2007                return Err(ExecutionError::new(
2008                    ExecutionErrorCode::Timeout,
2009                    format!(
2010                        "Invalid timeout: maximum is {} seconds",
2011                        MAX_TIMEOUT_SECONDS
2012                    ),
2013                ));
2014            }
2015            Ok(Some(std::time::Duration::from_secs_f64(secs)))
2016        }
2017    }
2018}