Skip to main content

merry_process/process_runner/
tokio_runner.rs

1use super::{
2    background::BackgroundSupervisor,
3    environment::{process_current_dir, validate_environment_name, validate_os_string},
4    execution::run_spawned_process,
5};
6use merry_runtime::{
7    BackgroundProcessControl, ProcessActionIntent, ProcessRunner, ProcessRunnerContext,
8    ProcessRunnerError, ProcessRunnerFuture,
9};
10use std::{
11    collections::BTreeSet,
12    ffi::OsString,
13    path::{Path, PathBuf},
14    sync::Arc,
15};
16
17/// Host-process runner backed by [`tokio::process::Command`].
18///
19/// The runner executes the exact validated argv supplied by
20/// [`ProcessActionIntent`], inherits the current process environment, closes
21/// stdin, captures bounded stdout/stderr through the shared process IO path,
22/// and cooperatively cancels by killing the child process. Permission profiles
23/// and sandbox constraints are selected by the owning backend, not by this
24/// executor.
25#[derive(Debug, Default, Clone)]
26pub struct TokioProcessRunner {
27    cwd_root: Option<PathBuf>,
28    environment_overrides: Vec<(OsString, OsString)>,
29    background: BackgroundSupervisor,
30}
31
32impl TokioProcessRunner {
33    /// Creates a Tokio-backed process runner.
34    #[must_use]
35    pub fn new() -> Self {
36        Self {
37            cwd_root: None,
38            environment_overrides: Vec::new(),
39            background: BackgroundSupervisor::new(),
40        }
41    }
42
43    /// Creates a Tokio-backed process runner whose process cwd values are
44    /// resolved under a stable workspace root.
45    #[must_use]
46    pub fn new_at_workspace_root(root: impl Into<PathBuf>) -> Self {
47        Self {
48            cwd_root: Some(root.into()),
49            environment_overrides: Vec::new(),
50            background: BackgroundSupervisor::new(),
51        }
52    }
53
54    /// Validates and applies environment assignments while preserving all
55    /// other variables inherited from the Merry process.
56    pub fn with_environment_overrides(
57        mut self,
58        overrides: impl IntoIterator<Item = (OsString, OsString)>,
59    ) -> Result<Self, ProcessRunnerError> {
60        let mut names = BTreeSet::new();
61        let mut validated = Vec::new();
62        for (name, value) in overrides {
63            validate_environment_name(&name)?;
64            validate_os_string(&value, "host process environment value")?;
65            if !names.insert(name.clone()) {
66                return Err(ProcessRunnerError::infrastructure(
67                    "host process environment contains a duplicate variable",
68                ));
69            }
70            validated.push((name, value));
71        }
72        self.environment_overrides = validated;
73        Ok(self)
74    }
75}
76
77impl ProcessRunner for TokioProcessRunner {
78    fn run<'a>(
79        &'a self,
80        intent: ProcessActionIntent,
81        context: ProcessRunnerContext,
82    ) -> ProcessRunnerFuture<'a> {
83        let cwd_root = self.cwd_root.clone();
84        let environment_overrides = self.environment_overrides.clone();
85        let background = self.background.clone();
86        Box::pin(async move {
87            run_tokio_process(
88                intent,
89                context,
90                cwd_root.as_deref(),
91                &environment_overrides,
92                background,
93            )
94            .await
95        })
96    }
97
98    fn background_control(&self) -> Option<Arc<dyn BackgroundProcessControl>> {
99        Some(Arc::new(self.background.clone()))
100    }
101}
102
103async fn run_tokio_process(
104    intent: ProcessActionIntent,
105    context: ProcessRunnerContext,
106    cwd_root: Option<&Path>,
107    environment_overrides: &[(OsString, OsString)],
108    background: BackgroundSupervisor,
109) -> Result<merry_runtime::ProcessRunnerOutput, ProcessRunnerError> {
110    let Some((program, args)) = intent.argv().split_first() else {
111        return Err(ProcessRunnerError::infrastructure(
112            "validated process argv was unexpectedly empty",
113        ));
114    };
115    let program = program.clone();
116    let program_for_error = program.clone();
117    let args = args.to_vec();
118
119    if context.cancellation_token().is_cancelled() {
120        return Err(ProcessRunnerError::Cancelled);
121    }
122
123    let mut command = tokio::process::Command::new(&program);
124    #[cfg(windows)]
125    let args = prepare_windows_spawn_command(&mut command, &program, args);
126    command
127        .args(&args)
128        .current_dir(process_current_dir(cwd_root, &intent))
129        .envs(
130            environment_overrides
131                .iter()
132                .map(|(name, value)| (name, value)),
133        )
134        .stdin(std::process::Stdio::null())
135        .stdout(std::process::Stdio::piped())
136        .stderr(std::process::Stdio::piped())
137        .kill_on_drop(true);
138
139    run_spawned_process(command, intent, context, program_for_error, background).await
140}
141
142/// Applies Windows-specific UTF-8 and shell-invocation defaults before caller
143/// environment overrides so `intent.argv()` stays untainted for classification,
144/// permissions, and trajectory logging.
145#[cfg(windows)]
146fn prepare_windows_spawn_command(
147    command: &mut tokio::process::Command,
148    program: &str,
149    mut args: Vec<String>,
150) -> Vec<String> {
151    // Prevent Python/CLI tools from falling back to legacy Windows ANSI codepages.
152    command
153        .env("PYTHONUTF8", "1")
154        .env("PYTHONIOENCODING", "utf-8:surrogateescape");
155
156    let lower = program
157        .rsplit(['/', '\\'])
158        .next()
159        .unwrap_or(program)
160        .to_ascii_lowercase();
161
162    // Disable MSYS2 path conversion when invoking Git Bash so `/flag` arguments
163    // for native Windows toolchains (MSBuild, cl.exe) pass through unchanged.
164    if lower == "bash" || lower == "bash.exe" {
165        command
166            .env("MSYS_NO_PATHCONV", "1")
167            .env("MSYS2_ARG_CONV_EXCL", "*");
168        return args;
169    }
170
171    // Force UTF-8 console output for PowerShell piped stdout/stderr without
172    // modifying `$LASTEXITCODE`.
173    if matches!(
174        lower.as_str(),
175        "powershell" | "powershell.exe" | "pwsh" | "pwsh.exe"
176    ) && let Some(command_index) = args
177        .iter()
178        .position(|arg| arg.eq_ignore_ascii_case("-Command"))
179        && let Some(script) = args.get_mut(command_index + 1)
180    {
181        const UTF8_PREAMBLE: &str = "$OutputEncoding = [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false; ";
182        if !script.starts_with(UTF8_PREAMBLE) {
183            script.insert_str(0, UTF8_PREAMBLE);
184        }
185    }
186
187    args
188}