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_lines(
858        &self,
859        path: &str,
860        max_lines: Option<usize>,
861        cancel: Option<&CancellationToken>,
862    ) -> Result<Vec<String>, FileError> {
863        check_cancel_file(cancel, Some(path))?;
864        if max_lines.map(|m| m == 0).unwrap_or(false) {
865            return Ok(Vec::new());
866        }
867        let abs = self.resolve_path(path);
868        read::read_text_lines(&abs, max_lines, cancel).await
869    }
870
871    async fn read_binary_file(
872        &self,
873        path: &str,
874        cancel: Option<&CancellationToken>,
875    ) -> Result<Vec<u8>, FileError> {
876        check_cancel_file(cancel, Some(path))?;
877        let abs = self.resolve_path(path);
878        read_cancellable(&abs, cancel).await
879    }
880
881    async fn write_file(
882        &self,
883        path: &str,
884        content: FileContent,
885        cancel: Option<&CancellationToken>,
886    ) -> Result<(), FileError> {
887        check_cancel_file(cancel, Some(path))?;
888        let abs = self.resolve_path(path);
889        // mkdir parent (recursive).
890        if let Some(parent) = abs.parent() {
891            if !parent.as_os_str().is_empty() {
892                if let Err(e) = tokio::fs::create_dir_all(parent).await {
893                    return Err(io_to_file_error(e, Some(&abs.to_string_lossy())));
894                }
895            }
896        }
897        check_cancel_file(cancel, Some(&abs.to_string_lossy()))?;
898        write_cancellable(abs, content, cancel).await
899    }
900
901    async fn write_new_file(
902        &self,
903        path: &str,
904        content: FileContent,
905        cancel: Option<&CancellationToken>,
906    ) -> Result<(), FileError> {
907        check_cancel_file(cancel, Some(path))?;
908        let abs = self.resolve_path(path);
909        let cancel = cancel.cloned();
910        // One owned blocking operation retains the opened descriptor even if
911        // its async waiter disappears. O_EXCL/create_new is the authority: no
912        // separate metadata check, parent mkdir, truncation or cleanup unlink.
913        tokio::task::spawn_blocking(move || {
914            let display = abs.to_string_lossy();
915            check_cancel_file(cancel.as_ref(), Some(&display))?;
916            let mut options = std::fs::OpenOptions::new();
917            options.write(true).create_new(true);
918            #[cfg(unix)]
919            {
920                use std::os::unix::fs::OpenOptionsExt;
921                options.mode(0o600);
922            }
923            let mut file = options
924                .open(&abs)
925                .map_err(|error| io_to_file_error(error, Some(&display)))?;
926            for chunk in content.as_bytes().chunks(64 * 1024) {
927                check_cancel_file(cancel.as_ref(), Some(&display))?;
928                file.write_all(chunk)
929                    .map_err(|error| io_to_file_error(error, Some(&display)))?;
930            }
931            file.flush()
932                .map_err(|error| io_to_file_error(error, Some(&display)))
933        })
934        .await
935        .map_err(|_| {
936            FileError::new(
937                FileErrorCode::Unknown,
938                "exclusive file creation task stopped",
939            )
940        })?
941    }
942
943    async fn append_file(
944        &self,
945        path: &str,
946        content: FileContent,
947        cancel: Option<&CancellationToken>,
948    ) -> Result<(), FileError> {
949        check_cancel_file(cancel, Some(path))?;
950        let abs = self.resolve_path(path);
951        if let Some(parent) = abs.parent() {
952            if !parent.as_os_str().is_empty() {
953                let _ = tokio::fs::create_dir_all(parent).await;
954            }
955        }
956        use tokio::io::AsyncWriteExt;
957        let res = match tokio::fs::OpenOptions::new()
958            .create(true)
959            .append(true)
960            .open(&abs)
961            .await
962        {
963            Ok(mut f) => {
964                // Tokio may acknowledge a buffered write before the blocking
965                // filesystem operation completes. Await it before returning so
966                // an immediate read/metadata call observes the appended bytes.
967                match f.write_all(content.as_bytes()).await {
968                    Ok(()) => f.flush().await,
969                    Err(error) => Err(error),
970                }
971            }
972            Err(e) => return Err(io_to_file_error(e, Some(&abs.to_string_lossy()))),
973        };
974        res.map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))
975    }
976
977    async fn rename_file(
978        &self,
979        source: &str,
980        dest: &str,
981        cancel: Option<&CancellationToken>,
982    ) -> Result<(), FileError> {
983        check_cancel_file(cancel, Some(source))?;
984        let src = self.resolve_path(source);
985        let dst = self.resolve_path(dest);
986        tokio::fs::rename(&src, &dst)
987            .await
988            .map_err(|e| io_to_file_error(e, Some(&src.to_string_lossy())))
989    }
990
991    async fn file_info(
992        &self,
993        path: &str,
994        cancel: Option<&CancellationToken>,
995    ) -> Result<FileInfo, FileError> {
996        check_cancel_file(cancel, Some(path))?;
997        let abs = self.resolve_path(path);
998        let meta = tokio::fs::symlink_metadata(&abs)
999            .await
1000            .map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))?;
1001        let ft = meta.file_type();
1002        let kind = if ft.is_file() {
1003            FileKind::File
1004        } else if ft.is_dir() {
1005            FileKind::Directory
1006        } else if ft.is_symlink() {
1007            FileKind::Symlink
1008        } else {
1009            return Err(
1010                FileError::new(FileErrorCode::Invalid, "Unsupported file type")
1011                    .with_path(abs.to_string_lossy()),
1012            );
1013        };
1014        let mtime_ms = meta
1015            .modified()
1016            .ok()
1017            .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1018            .map(|d| d.as_millis() as i64)
1019            .unwrap_or(0);
1020        Ok(FileInfo {
1021            name: abs
1022                .file_name()
1023                .map(|n| n.to_string_lossy().into_owned())
1024                .unwrap_or_else(|| abs.to_string_lossy().into_owned()),
1025            path: abs.clone(),
1026            kind,
1027            size: meta.len(),
1028            mtime_ms,
1029        })
1030    }
1031
1032    async fn list_dir(
1033        &self,
1034        path: &str,
1035        cancel: Option<&CancellationToken>,
1036    ) -> Result<Vec<FileInfo>, FileError> {
1037        check_cancel_file(cancel, Some(path))?;
1038        let abs = self.resolve_path(path);
1039        let mut entries = tokio::fs::read_dir(&abs)
1040            .await
1041            .map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))?;
1042        let mut out = Vec::new();
1043        while let Some(entry) = entries
1044            .next_entry()
1045            .await
1046            .map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))?
1047        {
1048            if let Some(t) = cancel {
1049                if t.is_cancelled() {
1050                    return Err(FileError::aborted().with_path(abs.to_string_lossy()));
1051                }
1052            }
1053            let ep = entry.path();
1054            let meta = match tokio::fs::symlink_metadata(&ep).await {
1055                Ok(m) => m,
1056                Err(e) => {
1057                    // Skip unsupported types silently; propagate real stat errors.
1058                    let code = crate::error::io_to_file_code(&e);
1059                    if code == FileErrorCode::NotSupported {
1060                        continue;
1061                    }
1062                    return Err(io_to_file_error(e, Some(&ep.to_string_lossy())));
1063                }
1064            };
1065            let ft = meta.file_type();
1066            let kind = if ft.is_file() {
1067                FileKind::File
1068            } else if ft.is_dir() {
1069                FileKind::Directory
1070            } else if ft.is_symlink() {
1071                FileKind::Symlink
1072            } else {
1073                continue; // silently skip sockets/fifos/etc.
1074            };
1075            let mtime_ms = meta
1076                .modified()
1077                .ok()
1078                .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1079                .map(|d| d.as_millis() as i64)
1080                .unwrap_or(0);
1081            out.push(FileInfo {
1082                name: entry.file_name().to_string_lossy().into_owned(),
1083                path: ep,
1084                kind,
1085                size: meta.len(),
1086                mtime_ms,
1087            });
1088        }
1089        Ok(out)
1090    }
1091
1092    async fn has_file_with_suffix(
1093        &self,
1094        path: &str,
1095        suffix: &str,
1096        cancel: Option<&CancellationToken>,
1097    ) -> Result<bool, FileError> {
1098        check_cancel_file(cancel, Some(path))?;
1099        let abs = self.resolve_path(path);
1100        let error_path = abs.to_string_lossy().into_owned();
1101        let suffix = String::from(suffix);
1102        let cancel = cancel.cloned();
1103        // One blocking job, not one lstat + runtime round-trip per entry. Session
1104        // existence checks need names/types only, not every sidecar's metadata.
1105        tokio::task::spawn_blocking(move || {
1106            check_cancel_file(cancel.as_ref(), Some(&abs.to_string_lossy()))?;
1107            let entries = std::fs::read_dir(&abs)
1108                .map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))?;
1109            for entry in entries {
1110                check_cancel_file(cancel.as_ref(), Some(&abs.to_string_lossy()))?;
1111                let entry = entry.map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))?;
1112                if !entry.file_name().to_string_lossy().ends_with(&suffix) {
1113                    continue;
1114                }
1115                let kind = match entry.file_type() {
1116                    Ok(kind) => kind,
1117                    Err(error)
1118                        if crate::error::io_to_file_code(&error) == FileErrorCode::NotSupported =>
1119                    {
1120                        continue
1121                    }
1122                    Err(error) => {
1123                        return Err(io_to_file_error(
1124                            error,
1125                            Some(&entry.path().to_string_lossy()),
1126                        ))
1127                    }
1128                };
1129                check_cancel_file(cancel.as_ref(), Some(&abs.to_string_lossy()))?;
1130                if kind.is_file() || kind.is_symlink() {
1131                    return Ok(true);
1132                }
1133            }
1134            check_cancel_file(cancel.as_ref(), Some(&abs.to_string_lossy()))?;
1135            Ok(false)
1136        })
1137        .await
1138        .map_err(|error| {
1139            FileError::new(
1140                FileErrorCode::Unknown,
1141                format!("directory scan task failed: {error}"),
1142            )
1143            .with_path(error_path)
1144        })?
1145    }
1146
1147    async fn canonical_path(
1148        &self,
1149        path: &str,
1150        cancel: Option<&CancellationToken>,
1151    ) -> Result<PathBuf, FileError> {
1152        check_cancel_file(cancel, Some(path))?;
1153        let abs = self.resolve_path(path);
1154        tokio::fs::canonicalize(&abs)
1155            .await
1156            .map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))
1157    }
1158
1159    async fn exists(
1160        &self,
1161        path: &str,
1162        cancel: Option<&CancellationToken>,
1163    ) -> Result<bool, FileError> {
1164        check_cancel_file(cancel, Some(path))?;
1165        let abs = self.resolve_path(path);
1166        match tokio::fs::symlink_metadata(&abs).await {
1167            Ok(_) => Ok(true),
1168            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
1169            Err(e) => Err(io_to_file_error(e, Some(&abs.to_string_lossy()))),
1170        }
1171    }
1172
1173    async fn create_dir(
1174        &self,
1175        path: &str,
1176        recursive: bool,
1177        cancel: Option<&CancellationToken>,
1178    ) -> Result<(), FileError> {
1179        check_cancel_file(cancel, Some(path))?;
1180        let abs = self.resolve_path(path);
1181        let res = if recursive {
1182            tokio::fs::create_dir_all(&abs).await
1183        } else {
1184            tokio::fs::create_dir(&abs).await
1185        };
1186        res.map_err(|e| io_to_file_error(e, Some(&abs.to_string_lossy())))
1187    }
1188
1189    async fn remove(
1190        &self,
1191        path: &str,
1192        recursive: bool,
1193        force: bool,
1194        cancel: Option<&CancellationToken>,
1195    ) -> Result<(), FileError> {
1196        check_cancel_file(cancel, Some(path))?;
1197        let abs = self.resolve_path(path);
1198        let res = if recursive {
1199            tokio::fs::remove_dir_all(&abs).await
1200        } else {
1201            // Try file first, then empty dir.
1202            match tokio::fs::remove_file(&abs).await {
1203                Ok(()) => Ok(()),
1204                Err(_) => tokio::fs::remove_dir(&abs).await,
1205            }
1206        };
1207        match res {
1208            Ok(()) => Ok(()),
1209            Err(e) if e.kind() == std::io::ErrorKind::NotFound && force => Ok(()),
1210            Err(e) => Err(io_to_file_error(e, Some(&abs.to_string_lossy()))),
1211        }
1212    }
1213
1214    async fn create_temp_dir(
1215        &self,
1216        prefix: Option<&str>,
1217        cancel: Option<&CancellationToken>,
1218    ) -> Result<PathBuf, FileError> {
1219        check_cancel_file(cancel, None)?;
1220        let prefix = prefix.unwrap_or("tmp-");
1221        // Use tempfile's NamedTempFile-less builder for a dir.
1222        let tmp =
1223            tempfile::tempdir_in(std::env::temp_dir()).map_err(|e| io_to_file_error(e, None))?;
1224        // tempfile picks a random name; rename to include the prefix.
1225        let path = tmp.path().to_path_buf();
1226        std::mem::forget(tmp); // keep the dir alive; caller manages cleanup.
1227                               // Build a prefixed sibling.
1228        let final_path = std::env::temp_dir().join(format!("{}{}", prefix, random_suffix()));
1229        // Rename the tempdir into the prefixed path.
1230        if let Err(e) = tokio::fs::rename(&path, &final_path).await {
1231            // Fallback: just return the original random path.
1232            let _ = e;
1233            return Ok(path);
1234        }
1235        Ok(final_path)
1236    }
1237
1238    async fn create_temp_file(
1239        &self,
1240        prefix: &str,
1241        suffix: &str,
1242        cancel: Option<&CancellationToken>,
1243    ) -> Result<PathBuf, FileError> {
1244        check_cancel_file(cancel, None)?;
1245        // Create an isolated temp dir (matching the TS pattern of one dir per
1246        // file), then write an empty file named `<prefix><random><suffix>`.
1247        let dir = self.create_temp_dir(Some("tmp-"), cancel).await?;
1248        let name = format!("{}{}{}", prefix, random_suffix(), suffix);
1249        let path = dir.join(name);
1250        tokio::fs::File::create(&path)
1251            .await
1252            .map_err(|e| io_to_file_error(e, Some(&path.to_string_lossy())))?;
1253        Ok(path)
1254    }
1255
1256    async fn cleanup(&self) {
1257        let pids: Vec<u32> = self
1258            .active_pids
1259            .lock()
1260            .unwrap_or_else(|e| e.into_inner())
1261            .iter()
1262            .copied()
1263            .collect();
1264        for pid in pids {
1265            kill_process_tree(pid).await;
1266        }
1267        self.active_pids
1268            .lock()
1269            .unwrap_or_else(|e| e.into_inner())
1270            .clear();
1271    }
1272}
1273
1274/// Read a file to bytes, honoring cooperative cancellation.
1275async fn read_cancellable(
1276    path: &Path,
1277    cancel: Option<&CancellationToken>,
1278) -> Result<Vec<u8>, FileError> {
1279    let read = tokio::fs::read(path);
1280    let res = match cancel {
1281        Some(t) => tokio::select! {
1282            r = read => r,
1283            _ = t.cancelled() => return Err(FileError::aborted().with_path(path.to_string_lossy())),
1284        },
1285        None => read.await,
1286    };
1287    res.map_err(|e| io_to_file_error(e, Some(&path.to_string_lossy())))
1288}
1289
1290/// Observe cancellation immediately before opening the destination. Once
1291/// truncation can begin, wait for the write and report its actual I/O result.
1292async fn write_cancellable(
1293    path: PathBuf,
1294    content: FileContent,
1295    cancel: Option<&CancellationToken>,
1296) -> Result<(), FileError> {
1297    let task_path = path.clone();
1298    let cancel = cancel.cloned();
1299    tokio::task::spawn_blocking(move || {
1300        let path = task_path.to_string_lossy();
1301        check_cancel_file(cancel.as_ref(), Some(&path))?;
1302        let write = || -> std::io::Result<()> {
1303            let mut file = std::fs::File::create(&task_path)?;
1304            file.write_all(content.as_bytes())?;
1305            file.flush()
1306        };
1307        write().map_err(|error| io_to_file_error(error, Some(&path)))
1308    })
1309    .await
1310    .map_err(|error| {
1311        FileError::new(FileErrorCode::Unknown, "file write task failed")
1312            .with_path(path.to_string_lossy())
1313            .with_source(Box::new(error))
1314    })?
1315}
1316
1317fn random_suffix() -> String {
1318    // Short random suffix via uuid v4 (no Time—it's a UUID, not a timestamp).
1319    uuid::Uuid::new_v4().simple().to_string()
1320}
1321
1322async fn drain_shell_pipe(
1323    pipe: Option<impl tokio::io::AsyncRead + Unpin>,
1324    mut callback: Option<Box<dyn FnMut(&str) + Send + '_>>,
1325    retained: &mut String,
1326    streamed: Option<&tokio::sync::mpsc::Sender<String>>,
1327    shell_exited: &CancellationToken,
1328    cancel: Option<&CancellationToken>,
1329) {
1330    use tokio::io::AsyncReadExt;
1331    use tokio::time::{timeout, Duration, Instant};
1332
1333    let Some(mut pipe) = pipe else { return };
1334    let mut buffer = [0u8; 8192];
1335    let mut decoder = crate::output_decode::StreamDecoder::new();
1336    let mut drain_budget = Duration::from_millis(EXIT_STDIO_GRACE_MS);
1337    let cancelled = async {
1338        match cancel {
1339            Some(token) => token.cancelled().await,
1340            None => std::future::pending::<()>().await,
1341        }
1342    };
1343    tokio::pin!(cancelled);
1344    loop {
1345        let read = async {
1346            let read = pipe.read(&mut buffer);
1347            tokio::pin!(read);
1348            tokio::select! {
1349                biased;
1350                _ = shell_exited.cancelled() => {},
1351                result = &mut read => return result.unwrap_or(0),
1352            }
1353
1354            // Apply the post-exit budget only to reading the pipe. Time spent
1355            // delivering a chunk to a slow consumer must not cut off later reads.
1356            if drain_budget.is_zero() {
1357                return 0;
1358            }
1359            let started = Instant::now();
1360            let result = timeout(drain_budget, &mut read).await;
1361            drain_budget = drain_budget.saturating_sub(started.elapsed());
1362            result.ok().and_then(Result::ok).unwrap_or(0)
1363        };
1364        let count = tokio::select! {
1365            biased;
1366            _ = &mut cancelled => 0,
1367            count = read => count,
1368        };
1369        let chunk = if count == 0 {
1370            decoder.finish()
1371        } else {
1372            decoder.push(&buffer[..count])
1373        };
1374        if !chunk.is_empty() {
1375            if let Some(callback) = callback.as_mut() {
1376                callback(&chunk);
1377            }
1378            if let Some(sender) = streamed {
1379                let _ = sender.send(chunk).await;
1380            } else {
1381                retained.push_str(&chunk);
1382            }
1383        }
1384        if count == 0 {
1385            break;
1386        }
1387    }
1388}
1389
1390impl OsExecutionEnv {
1391    async fn exec_inner(
1392        &self,
1393        command: &str,
1394        options: ShellExecOptions<'_>,
1395        streamed: Option<tokio::sync::mpsc::Sender<String>>,
1396    ) -> Result<ShellOutput, ExecutionError> {
1397        // Pre-flight abort.
1398        check_cancel_exec(options.cancel)?;
1399        // Resolve timeout.
1400        let timeout = match resolve_timeout(options.timeout) {
1401            Ok(t) => t,
1402            Err(e) => return Err(e),
1403        };
1404        // Resolve cwd.
1405        let cwd = match &options.cwd {
1406            Some(c) => self.resolve_path(&c.to_string_lossy()),
1407            None => self.cwd.clone(),
1408        };
1409        // Shell config. An explicit override is used by native shell tools
1410        // such as PowerShell; otherwise preserve the default Bash behavior.
1411        let shell_cfg = match &options.shell {
1412            Some(override_shell) => ShellConfig {
1413                shell: override_shell.program.clone(),
1414                args: override_shell.args.clone(),
1415                transport: CommandTransport::Argv,
1416            },
1417            None => self.get_shell_config().await?,
1418        };
1419        self.exec_configured(command, options, streamed, shell_cfg, timeout, cwd)
1420            .await
1421    }
1422
1423    async fn exec_configured(
1424        &self,
1425        command: &str,
1426        options: ShellExecOptions<'_>,
1427        streamed: Option<tokio::sync::mpsc::Sender<String>>,
1428        shell_cfg: ShellConfig,
1429        timeout: Option<std::time::Duration>,
1430        cwd: PathBuf,
1431    ) -> Result<ShellOutput, ExecutionError> {
1432        // Verify cwd exists.
1433        if !cwd.exists() {
1434            return Err(ExecutionError::new(
1435                ExecutionErrorCode::SpawnError,
1436                format!(
1437                    "Working directory does not exist: {}\nCannot execute bash commands.",
1438                    cwd.display()
1439                ),
1440            ));
1441        }
1442
1443        check_cancel_exec(options.cancel)?;
1444        // Build the spawn.
1445        let mut cmd = tokio::process::Command::new(&shell_cfg.shell);
1446        cmd.current_dir(&cwd);
1447        cmd.env_clear();
1448        // Non-interactive defaults apply even when `inherit_env` is false: a
1449        // caller asking for a clean environment is not asking for a prompt.
1450        // They sit before the inherit loop so any explicit value wins.
1451        for (k, v) in NON_INTERACTIVE_SHELL_ENV {
1452            cmd.env(k, v);
1453        }
1454        // Environment: inherit + shell_env + per-call. The host's own private
1455        // plumbing (`HOST_PRIVATE_ENV`) is skipped: it describes *this* process,
1456        // not the shell or anything the shell runs, and inheriting it makes a
1457        // nested `rpi` misreport its session. A caller that genuinely wants a
1458        // value passed down can still set it explicitly through `env`/`shell_env`
1459        // below (those are applied after this loop and win).
1460        if options.inherit_env {
1461            let mut inherit = |name: &str, value: &str| {
1462                if !is_host_private_env(name) {
1463                    cmd.env(name, value);
1464                }
1465            };
1466            match &self.environment {
1467                Some(environment) => {
1468                    for (name, value) in environment {
1469                        inherit(name, value);
1470                    }
1471                }
1472                None => {
1473                    for (name, value) in std::env::vars() {
1474                        inherit(&name, &value);
1475                    }
1476                }
1477            }
1478        }
1479        if let Some(base) = &self.shell_env {
1480            for (k, v) in base {
1481                cmd.env(k, v);
1482            }
1483        }
1484        if let Some(extra) = &options.env {
1485            for (k, v) in extra {
1486                cmd.env(k, v);
1487            }
1488        }
1489        // stdio.
1490        cmd.kill_on_drop(true);
1491        cmd.stdout(std::process::Stdio::piped());
1492        cmd.stderr(std::process::Stdio::piped());
1493        #[cfg(unix)]
1494        {
1495            cmd.process_group(0); // child becomes its own group leader.
1496        }
1497        #[cfg(windows)]
1498        {
1499            use windows_sys::Win32::System::Threading::{CREATE_NO_WINDOW, CREATE_SUSPENDED};
1500            // Suspended until it is in its job (see `shell_jobs::start`).
1501            cmd.creation_flags(CREATE_NO_WINDOW | CREATE_SUSPENDED);
1502        }
1503
1504        cmd.args(&shell_cfg.args);
1505        match shell_cfg.transport {
1506            CommandTransport::Argv => {
1507                // Commands given as arguments have no input. Provide EOF from
1508                // spawn, even while another thread is launching a process.
1509                cmd.stdin(std::process::Stdio::null());
1510                cmd.arg(command);
1511            }
1512            CommandTransport::Stdin => {
1513                // Legacy WSL bash reads the script from stdin via `bash -s`.
1514                cmd.stdin(std::process::Stdio::piped());
1515            }
1516        }
1517
1518        let mut child = match cmd.spawn() {
1519            Ok(c) => c,
1520            Err(e) => {
1521                return Err(ExecutionError::new(
1522                    ExecutionErrorCode::SpawnError,
1523                    format!("failed to spawn shell: {e}"),
1524                ));
1525            }
1526        };
1527        let pid = child.id();
1528        let mut process_guard = ShellProcessGuard {
1529            pid,
1530            active: self.active_pids.clone(),
1531        };
1532        #[cfg(windows)]
1533        {
1534            let started = match (pid, child.raw_handle()) {
1535                (Some(pid), Some(process)) => shell_jobs::start(pid, process),
1536                _ => Err("the shell has no process handle".to_owned()),
1537            };
1538            if let Err(error) = started {
1539                if let Some(pid) = pid {
1540                    shell_jobs::forget(pid);
1541                }
1542                let _ = child.start_kill();
1543                return Err(ExecutionError::new(
1544                    ExecutionErrorCode::SpawnError,
1545                    format!("failed to start shell: {error}"),
1546                ));
1547            }
1548        }
1549        if let Some(pid) = pid {
1550            self.active_pids
1551                .lock()
1552                .unwrap_or_else(|e| e.into_inner())
1553                .insert(pid);
1554        }
1555
1556        let stdin = child.stdin.take();
1557        let stop_input = CancellationToken::new();
1558        let deadline = timeout.map(|duration| tokio::time::Instant::now() + duration);
1559        let mut stdout_buf = String::new();
1560        let mut stderr_buf = String::new();
1561        let cancel = options.cancel;
1562        let shell_exited = CancellationToken::new();
1563        let stdout_task = drain_shell_pipe(
1564            child.stdout.take(),
1565            options.on_stdout,
1566            &mut stdout_buf,
1567            streamed.as_ref(),
1568            &shell_exited,
1569            cancel,
1570        );
1571        let stderr_task = drain_shell_pipe(
1572            child.stderr.take(),
1573            options.on_stderr,
1574            &mut stderr_buf,
1575            streamed.as_ref(),
1576            &shell_exited,
1577            cancel,
1578        );
1579
1580        // Drive script input, both output pipes, and process termination
1581        // together. A shell can fill an output pipe before reading more stdin.
1582        let mut timed_out = false;
1583        let exit_status = {
1584            let status_fut = async {
1585                let expired = async {
1586                    match deadline {
1587                        Some(at) => tokio::time::sleep_until(at).await,
1588                        None => std::future::pending::<()>().await,
1589                    }
1590                };
1591                let cancelled = async {
1592                    match cancel {
1593                        Some(token) => token.cancelled().await,
1594                        None => std::future::pending::<()>().await,
1595                    }
1596                };
1597                tokio::select! {
1598                    status = child.wait() => return status,
1599                    () = expired => timed_out = true,
1600                    () = cancelled => {}
1601                }
1602                stop_input.cancel();
1603                if let Some(pid) = child.id() {
1604                    kill_process_tree(pid).await;
1605                }
1606                child.wait().await
1607            };
1608            tokio::pin!(status_fut, stdout_task, stderr_task);
1609            let (mut stdout_done, mut stderr_done) = (false, false);
1610            let status_res = {
1611                let stdin_task = async {
1612                    let Some(mut stdin) = stdin else { return };
1613                    use tokio::io::AsyncWriteExt;
1614
1615                    // Dropping the pipe signals EOF to bash -s. A shell that
1616                    // exits early can close it first and still report its own
1617                    // exit status.
1618                    tokio::select! {
1619                        biased;
1620                        () = stop_input.cancelled() => {}
1621                        () = async {
1622                            if stdin.write_all(command.as_bytes()).await.is_ok() {
1623                                let _ = stdin.flush().await;
1624                            }
1625                        } => {}
1626                    }
1627                };
1628                tokio::pin!(stdin_task);
1629                let mut stdin_done = false;
1630                loop {
1631                    tokio::select! {
1632                        status = &mut status_fut => break status,
1633                        () = &mut stdin_task, if !stdin_done => stdin_done = true,
1634                        () = &mut stdout_task, if !stdout_done => stdout_done = true,
1635                        () = &mut stderr_task, if !stderr_done => stderr_done = true,
1636                    }
1637                }
1638            };
1639            // Disarm immediately after a successful wait, before any await:
1640            // the shell has been reaped and its PID may now be reused.
1641            if status_res.is_ok() {
1642                process_guard.finish();
1643            }
1644            // Each reader now limits time spent on its pipe so an inherited
1645            // pipe can't hold the call open. Join both readers through delivery.
1646            shell_exited.cancel();
1647            tokio::join!(
1648                async {
1649                    if !stdout_done {
1650                        (&mut stdout_task).await;
1651                    }
1652                },
1653                async {
1654                    if !stderr_done {
1655                        (&mut stderr_task).await;
1656                    }
1657                },
1658            );
1659            status_res
1660        };
1661
1662        // Give trailing stdio a brief grace period. Only the timed-out and
1663        // cancelled paths still owe a wait: on the normal path the drain above
1664        // already capped it.
1665        if timed_out {
1666            let _ = tokio::time::sleep(std::time::Duration::from_millis(EXIT_STDIO_GRACE_MS)).await;
1667        }
1668
1669        // Resolution priority: timedOut → cancelled → status.
1670        let status = match exit_status {
1671            Ok(s) => s,
1672            Err(e) => {
1673                return Err(ExecutionError::new(
1674                    ExecutionErrorCode::SpawnError,
1675                    format!("child wait failed: {e}"),
1676                ));
1677            }
1678        };
1679        if timed_out {
1680            return Err(ExecutionError::timeout(
1681                options.timeout.map(|f| f as u64).unwrap_or(0),
1682            ));
1683        }
1684        if cancel.map(|t| t.is_cancelled()).unwrap_or(false) {
1685            return Err(ExecutionError::aborted());
1686        }
1687        let exit_code = status.code().unwrap_or(0);
1688        Ok(ShellOutput {
1689            stdout: stdout_buf,
1690            stderr: stderr_buf,
1691            exit_code,
1692        })
1693    }
1694}
1695
1696#[async_trait]
1697impl Shell for OsExecutionEnv {
1698    async fn exec<'a>(
1699        &'a self,
1700        command: &str,
1701        options: ShellExecOptions<'a>,
1702    ) -> Result<ShellOutput, ExecutionError> {
1703        self.exec_inner(command, options, None).await
1704    }
1705
1706    async fn exec_streamed<'a>(
1707        &'a self,
1708        command: &str,
1709        options: ShellExecOptions<'a>,
1710        output: tokio::sync::mpsc::Sender<String>,
1711    ) -> Result<i32, ExecutionError> {
1712        self.exec_inner(command, options, Some(output))
1713            .await
1714            .map(|result| result.exit_code)
1715    }
1716
1717    async fn cleanup(&self) {
1718        FileSystem::cleanup(self).await
1719    }
1720}
1721
1722#[async_trait]
1723impl ExecutionEnv for OsExecutionEnv {}
1724
1725#[async_trait]
1726impl MutatingEnv for OsExecutionEnv {
1727    fn as_env(&self) -> &dyn ExecutionEnv {
1728        self
1729    }
1730    fn mutation_registry(&self) -> &MutationQueueRegistry {
1731        &self.registry
1732    }
1733}
1734
1735#[cfg(test)]
1736mod stdin_transport_tests {
1737    use super::*;
1738    use std::time::Duration;
1739
1740    fn long_script(first: &str, last: &str) -> String {
1741        format!(
1742            "{first}\n{}{last}\n",
1743            "# benign stdin pipe fixture data\n".repeat(64 * 1024)
1744        )
1745    }
1746
1747    async fn exec_stdin(
1748        env: &OsExecutionEnv,
1749        script: &str,
1750        options: ShellExecOptions<'_>,
1751    ) -> Result<ShellOutput, ExecutionError> {
1752        let config = ShellConfig {
1753            shell: env.get_shell_config().await?.shell,
1754            args: vec!["-s".to_owned()],
1755            transport: CommandTransport::Stdin,
1756        };
1757        let timeout = resolve_timeout(options.timeout)?;
1758        env.exec_configured(script, options, None, config, timeout, env.cwd.clone())
1759            .await
1760    }
1761
1762    #[tokio::test]
1763    async fn stdin_transport_drains_output_while_sending_the_script() {
1764        let temp = tempfile::tempdir().unwrap();
1765        let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
1766        let script = long_script(
1767            "head -c 262144 /dev/zero | tr '\\0' a; head -c 262144 /dev/zero | tr '\\0' b >&2",
1768            "printf 'end of script'",
1769        );
1770        let output = tokio::time::timeout(
1771            Duration::from_secs(4),
1772            exec_stdin(
1773                &env,
1774                &script,
1775                ShellExecOptions {
1776                    timeout: Some(3.0),
1777                    ..Default::default()
1778                },
1779            ),
1780        )
1781        .await
1782        .expect("shell blocked feeding stdin while its output pipes were full");
1783        let output = match output {
1784            Err(error) if error.code == ExecutionErrorCode::ShellUnavailable => return,
1785            output => output.unwrap(),
1786        };
1787        assert_eq!(output.exit_code, 0);
1788        assert_eq!(output.stdout.len(), 262144 + "end of script".len());
1789        assert!(output.stdout.ends_with("end of script"));
1790        assert_eq!(output.stderr.len(), 262144);
1791        assert!(output.stderr.bytes().all(|byte| byte == b'b'));
1792    }
1793
1794    #[tokio::test]
1795    async fn stdin_transport_timeout_covers_blocked_script_upload() {
1796        let temp = tempfile::tempdir().unwrap();
1797        let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
1798        let script = long_script("sleep 30", "printf 'unexpected completion'");
1799        let error = tokio::time::timeout(
1800            Duration::from_secs(3),
1801            exec_stdin(
1802                &env,
1803                &script,
1804                ShellExecOptions {
1805                    timeout: Some(0.15),
1806                    ..Default::default()
1807                },
1808            ),
1809        )
1810        .await
1811        .expect("command timeout did not start while stdin was blocked")
1812        .unwrap_err();
1813        if error.code == ExecutionErrorCode::ShellUnavailable {
1814            return;
1815        }
1816        assert_eq!(error.code, ExecutionErrorCode::Timeout);
1817    }
1818
1819    #[tokio::test]
1820    async fn stdin_transport_cancellation_covers_blocked_script_upload() {
1821        let temp = tempfile::tempdir().unwrap();
1822        let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
1823        let script = long_script("sleep 30", "printf 'unexpected completion'");
1824        let signal = CancellationToken::new();
1825        let (result, ()) = tokio::join!(
1826            tokio::time::timeout(
1827                Duration::from_secs(3),
1828                exec_stdin(
1829                    &env,
1830                    &script,
1831                    ShellExecOptions {
1832                        cancel: Some(&signal),
1833                        ..Default::default()
1834                    },
1835                ),
1836            ),
1837            async {
1838                tokio::time::sleep(Duration::from_millis(150)).await;
1839                signal.cancel();
1840            },
1841        );
1842        let error = result
1843            .expect("cancellation was not observed while stdin was blocked")
1844            .unwrap_err();
1845        if error.code == ExecutionErrorCode::ShellUnavailable {
1846            return;
1847        }
1848        assert_eq!(error.code, ExecutionErrorCode::Aborted);
1849    }
1850
1851    #[tokio::test]
1852    async fn stdin_transport_keeps_a_deliberate_early_exit_code() {
1853        let temp = tempfile::tempdir().unwrap();
1854        let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
1855        let script = long_script(
1856            "printf 'early exit'; exit 7",
1857            "printf 'unexpected completion'",
1858        );
1859        let result = tokio::time::timeout(
1860            Duration::from_secs(3),
1861            exec_stdin(&env, &script, ShellExecOptions::default()),
1862        )
1863        .await
1864        .expect("shell blocked after closing its stdin");
1865        let output = match result {
1866            Err(error) if error.code == ExecutionErrorCode::ShellUnavailable => return,
1867            output => output.unwrap(),
1868        };
1869        assert_eq!(output.exit_code, 7);
1870        assert_eq!(output.stdout, "early exit");
1871    }
1872}
1873
1874#[cfg(test)]
1875mod durability_tests {
1876    use super::*;
1877
1878    #[test]
1879    fn queued_overwrite_cancelled_before_open_preserves_existing_bytes() {
1880        let runtime = tokio::runtime::Builder::new_current_thread()
1881            .enable_all()
1882            .max_blocking_threads(1)
1883            .build()
1884            .unwrap();
1885        runtime.block_on(async {
1886            let temp = tempfile::tempdir().unwrap();
1887            let path = temp.path().join("note.txt");
1888            std::fs::write(&path, b"original").unwrap();
1889            let (entered_tx, entered_rx) = tokio::sync::oneshot::channel();
1890            let (release_tx, release_rx) = std::sync::mpsc::channel();
1891            let blocker = tokio::task::spawn_blocking(move || {
1892                entered_tx.send(()).unwrap();
1893                release_rx.recv().unwrap();
1894            });
1895            entered_rx.await.unwrap();
1896
1897            let signal = CancellationToken::new();
1898            let write = write_cancellable(
1899                path.clone(),
1900                FileContent::Text("replacement".into()),
1901                Some(&signal),
1902            );
1903            tokio::pin!(write);
1904            let queued = futures::poll!(&mut write).is_pending();
1905            signal.cancel();
1906            release_tx.send(()).unwrap();
1907            blocker.await.unwrap();
1908
1909            assert!(queued, "overwrite should be queued on the blocking pool");
1910            let result = write.await;
1911            let contents = std::fs::read(&path).unwrap();
1912            assert_eq!(
1913                contents, b"original",
1914                "queued cancellation changed the file (write result: {result:?})"
1915            );
1916            assert_eq!(result.unwrap_err().code, FileErrorCode::Aborted);
1917        });
1918    }
1919
1920    #[tokio::test]
1921    async fn os_backend_syncs_staged_file_and_publication_directory() {
1922        let temp = tempfile::tempdir().unwrap();
1923        let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
1924        env.write_file("staged", FileContent::Text("durable slice".into()), None)
1925            .await
1926            .unwrap();
1927        env.sync_file("staged", false, None).await.unwrap();
1928        env.sync_directory(".", None).await.unwrap();
1929    }
1930
1931    #[tokio::test]
1932    async fn os_writer_lease_persists_and_verifies_a_monotonic_fence() {
1933        let temp = tempfile::tempdir().unwrap();
1934        let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
1935        let first = env
1936            .try_acquire_writer_lease("journal.jsonl")
1937            .await
1938            .unwrap()
1939            .unwrap();
1940        first.verify_fence().unwrap();
1941        drop(first);
1942        let second = env
1943            .try_acquire_writer_lease("journal.jsonl")
1944            .await
1945            .unwrap()
1946            .unwrap();
1947        second.verify_fence().unwrap();
1948        drop(second);
1949        assert_eq!(
1950            std::fs::read_to_string(temp.path().join("journal.jsonl.lock")).unwrap(),
1951            "2"
1952        );
1953    }
1954
1955    #[cfg(unix)]
1956    #[tokio::test]
1957    async fn os_writer_lease_releases_a_shared_open_file_description() {
1958        let temp = tempfile::tempdir().unwrap();
1959        let env = OsExecutionEnv::with_cwd(temp.path().to_path_buf());
1960        let lock = temp.path().join("journal.jsonl.lock");
1961        std::fs::write(&lock, "1").unwrap();
1962        let file = std::fs::OpenOptions::new()
1963            .read(true)
1964            .write(true)
1965            .open(&lock)
1966            .unwrap();
1967        fs2::FileExt::try_lock_exclusive(&file).unwrap();
1968        let inherited = file.try_clone().unwrap();
1969        let lease = OsWriterLease { file, fence: 1 };
1970        assert!(env.try_acquire_writer_lease("journal.jsonl").await.is_err());
1971        drop(lease);
1972        let next = env
1973            .try_acquire_writer_lease("journal.jsonl")
1974            .await
1975            .expect("retired writer retained a lock through the shared description")
1976            .unwrap();
1977        next.verify_fence().unwrap();
1978        assert_eq!(std::fs::read_to_string(lock).unwrap(), "2");
1979        drop(inherited);
1980    }
1981}
1982
1983/// Validate a timeout (seconds). Mirrors `resolveTimeoutMs` semantics.
1984fn resolve_timeout(timeout: Option<f64>) -> Result<Option<std::time::Duration>, ExecutionError> {
1985    match timeout {
1986        None => Ok(None),
1987        Some(secs) => {
1988            if !secs.is_finite() || secs <= 0.0 {
1989                return Err(ExecutionError::new(
1990                    ExecutionErrorCode::Timeout,
1991                    "Invalid timeout: must be a finite number of seconds",
1992                ));
1993            }
1994            let ms = secs * 1000.0;
1995            if ms > MAX_TIMEOUT_MS as f64 {
1996                return Err(ExecutionError::new(
1997                    ExecutionErrorCode::Timeout,
1998                    format!(
1999                        "Invalid timeout: maximum is {} seconds",
2000                        MAX_TIMEOUT_SECONDS
2001                    ),
2002                ));
2003            }
2004            Ok(Some(std::time::Duration::from_secs_f64(secs)))
2005        }
2006    }
2007}