Skip to main content

tinyharness_lib/tools/
run.rs

1use std::collections::HashMap;
2use std::time::Instant;
3
4use tokio::io::AsyncReadExt;
5
6use crate::extract_args;
7use crate::sandbox::Sandbox;
8use crate::tools::tool::{ToolCategory, build_string_params_schema, make_tool};
9
10/// Terminate a child process and, on Unix, its entire process group.
11pub(crate) async fn kill_child(mut child: tokio::process::Child) {
12    #[cfg(unix)]
13    {
14        if let Some(id) = child.id() {
15            // Send SIGKILL to the process group (-pgid)
16            unsafe {
17                libc::kill(-(id as libc::pid_t), libc::SIGKILL);
18            }
19        }
20    }
21    let _ = child.kill().await;
22    let _ = child.wait().await; // reap zombie process
23}
24
25/// Build the `run` tool.
26///
27/// `sandbox` is captured by the handler: when present, every command is
28/// executed through the OS-level process sandbox instead of directly. It has
29/// to be supplied here (rather than consulted at call time) because tool
30/// handlers are opaque `Fn` closures that outlive the `ToolManager`.
31pub fn run_tool_entry(sandbox: Option<Sandbox>) -> crate::tools::tool::Tool {
32    make_tool(
33        "run",
34        "Execute a shell command and return its output. Use for building, testing, running git commands, or any terminal operation. Returns stdout, stderr (if any), exit code, and duration. stdout is truncated at 5000 chars and stderr at 2000 chars. Default timeout is 30 seconds.",
35        ToolCategory::Destructive,
36        build_string_params_schema(
37            &[("command", "The shell command to execute")],
38            &[
39                (
40                    "timeout",
41                    "Timeout in milliseconds (default: 30000)",
42                    "30000",
43                ),
44                (
45                    "cwd",
46                    "Working directory for the command (default: project root)",
47                    "",
48                ),
49            ],
50        ),
51        move |args| {
52            // The future must be 'static, so the sandbox is moved into it
53            // rather than borrowed from the closure.
54            let sb = sandbox.clone();
55            Box::pin(async move { run_tool_inner(args, sb.as_ref()).await })
56        },
57    )
58}
59
60/// Execute a shell command asynchronously with a timeout.
61/// Returns stdout, stderr, exit code, and duration.
62pub async fn run_tool(args: HashMap<String, String>) -> String {
63    run_tool_inner(args, None).await
64}
65
66async fn run_tool_inner(args: HashMap<String, String>, sandbox: Option<&Sandbox>) -> String {
67    extract_args!(args, command);
68
69    let timeout_ms: u64 = args
70        .get("timeout")
71        .and_then(|t| t.parse().ok())
72        .unwrap_or(30_000);
73
74    let cwd = args.get("cwd").filter(|s| !s.trim().is_empty()).cloned();
75
76    let mut cmd = match (sandbox, cfg!(target_os = "windows")) {
77        // Sandboxed: bwrap/firejail wrap the shell invocation. The sandbox
78        // sets its own working directory (--chdir), so `current_dir` is left
79        // alone unless the host can honour it.
80        (Some(sb), _) => {
81            let (program, sb_args) = sb.argv(&command, cwd.as_deref().map(std::path::Path::new));
82            let mut c = tokio::process::Command::new(program);
83            c.args(sb_args);
84            c
85        }
86        (None, true) => {
87            let mut c = tokio::process::Command::new("cmd");
88            c.arg("/C");
89            c.arg(&command);
90            c
91        }
92        (None, false) => {
93            let mut c = tokio::process::Command::new("sh");
94            c.arg("-c");
95            c.arg(&command);
96            c
97        }
98    };
99
100    // Outside the sandbox the command inherits the host CWD, so honour `cwd`
101    // directly. Inside it, `--chdir` already placed the process there — but
102    // setting the outer CWD too is harmless (the workspace is bound at the
103    // same absolute path) and keeps firejail, which has no --chdir, correct.
104    if let Some(dir) = &cwd {
105        cmd.current_dir(dir);
106    }
107
108    #[cfg(unix)]
109    cmd.process_group(0);
110
111    // Start the command non-interactively with stdin disconnected
112    let mut child = match cmd
113        .stdin(std::process::Stdio::null())
114        .stdout(std::process::Stdio::piped())
115        .stderr(std::process::Stdio::piped())
116        .spawn()
117    {
118        Ok(c) => c,
119        Err(e) => return format!("Error: Failed to spawn command: {}", e),
120    };
121
122    let start = Instant::now();
123
124    // Wait for the command with a timeout
125    let wait_result =
126        tokio::time::timeout(tokio::time::Duration::from_millis(timeout_ms), child.wait()).await;
127
128    let elapsed = start.elapsed();
129
130    match wait_result {
131        Ok(Ok(status)) => {
132            // Read stdout
133            let stdout = if let Some(mut out) = child.stdout.take() {
134                let mut buf = String::new();
135                let _ = out.read_to_string(&mut buf).await;
136                buf
137            } else {
138                String::new()
139            };
140
141            // Read stderr
142            let stderr = if let Some(mut err) = child.stderr.take() {
143                let mut buf = String::new();
144                let _ = err.read_to_string(&mut buf).await;
145                buf
146            } else {
147                String::new()
148            };
149
150            let mut result = String::new();
151
152            if !stdout.is_empty() {
153                // Truncate stdout if too large
154                let max_chars = 5000;
155                if stdout.chars().count() > max_chars {
156                    let truncated: String = stdout.chars().take(max_chars).collect();
157                    result.push_str(&format!(
158                        "{}\n... (truncated to {} chars)\n",
159                        truncated, max_chars
160                    ));
161                } else {
162                    result.push_str(stdout.trim_end());
163                }
164            }
165
166            if !stderr.is_empty() {
167                let max_chars = 2000;
168                if stderr.chars().count() > max_chars {
169                    let truncated: String = stderr.chars().take(max_chars).collect();
170                    result.push_str(&format!(
171                        "\n{}... (stderr truncated to {} chars)\n",
172                        truncated, max_chars
173                    ));
174                } else {
175                    result.push_str(&format!("\n{}", stderr.trim_end()));
176                }
177            }
178
179            let exit_summary = format!(
180                "(exit {} in {:.1}s)",
181                status.code().unwrap_or(-1),
182                elapsed.as_secs_f64()
183            );
184            if result.is_empty() {
185                result.push_str(&exit_summary);
186            } else {
187                result.push_str(&format!("\n{}", exit_summary));
188            }
189
190            result
191        }
192        Ok(Err(e)) => {
193            // Error while waiting for the command
194            kill_child(child).await;
195            format!("Error: Failed to wait for command: {}", e)
196        }
197        Err(_elapsed) => {
198            // Command timed out — kill the process and its child processes
199            kill_child(child).await;
200            format!(
201                "Error: Command timed out after {}ms\nCommand: {}\nConsider increasing the timeout or simplifying the command.",
202                timeout_ms, command
203            )
204        }
205    }
206}
207
208#[cfg(test)]
209mod tests {
210    use super::*;
211
212    #[tokio::test]
213    async fn test_run_tool_timeout_kills_process_group() {
214        let mut args = HashMap::new();
215        let cmd = if cfg!(target_os = "windows") {
216            "ping -n 100 127.0.0.1 > NUL"
217        } else {
218            "sh -c 'sleep 10'"
219        };
220        args.insert("command".to_string(), cmd.to_string());
221        args.insert("timeout".to_string(), "100".to_string());
222
223        let res = run_tool(args).await;
224        assert!(res.contains("timed out after 100ms"), "result was: {res}");
225    }
226
227    #[tokio::test]
228    async fn test_run_tool_stdin_is_null() {
229        let mut args = HashMap::new();
230        let cmd = if cfg!(target_os = "windows") {
231            "findstr /r \".*\""
232        } else {
233            "head -n 1"
234        };
235        args.insert("command".to_string(), cmd.to_string());
236        args.insert("timeout".to_string(), "2000".to_string());
237
238        let res = run_tool(args).await;
239        assert!(res.contains("(exit"), "result was: {res}");
240    }
241}