Skip to main content

trusty_code/tools/bash/
mod.rs

1//! `bash` tool — execute a shell command with timeout enforcement and output capture.
2//!
3//! Why: The coder agent loop needs to run commands (pytest, cargo test, etc.)
4//! and read their output to iterate. Surfacing a non-zero exit code as a
5//! recoverable `ToolResult` (not a hard error) lets the LLM read failing test
6//! output and self-correct without aborting the loop.
7//! What: `BashTool` implements `ToolExecutor`; it runs a command via `sh -c`
8//! inside `tokio::process::Command`, enforces a configurable timeout, kills the
9//! child (and its process group on Unix) on expiry, captures stdout + stderr
10//! (each truncated to 100 KB), and returns a structured result that includes
11//! the exit code, captured output, and a timeout flag.
12//! Test: Unit tests live in `bash::tests`; they cover fast success, non-zero
13//! exit, timeout-kill, cwd honoring, stdout/stderr truncation, registry
14//! registration, and dispatch.
15
16#[cfg(test)]
17mod tests;
18
19use std::path::PathBuf;
20use std::time::Duration;
21
22use async_trait::async_trait;
23use serde_json::{Value, json};
24use tokio::io::AsyncReadExt;
25use tokio::process::Command;
26use tokio::time::timeout;
27
28use crate::tools::traits::{ServiceTier, ToolExecutor, ToolResult};
29
30/// Maximum bytes captured from stdout or stderr before truncation.
31pub(crate) const MAX_OUTPUT_BYTES: usize = 100 * 1024; // 100 KB
32
33/// Default command timeout in seconds.
34const DEFAULT_TIMEOUT_SECS: u64 = 120;
35
36/// The tool's registered/advertised name.
37///
38/// Why: Shared literal between the `ToolExecutor` impl and
39/// `crate::verify_gate`'s bash-call scan (#2279), so the two can never drift
40/// — mirrors `finish_task::FINISH_TASK_TOOL_NAME`'s existing convention.
41/// Test: `bash::tests::name_matches_constant`.
42pub const BASH_TOOL_NAME: &str = "bash";
43
44/// Executes arbitrary shell commands on behalf of the coder agent loop.
45///
46/// Why: Lets the LLM run test suites (pytest, cargo test, etc.), build steps,
47/// and diagnostic commands without a separate MCP bridge. Capturing output
48/// as a `ToolResult` (not a fatal error) on non-zero exit means the model
49/// can read failing test output and iterate.
50/// What: Wraps `tokio::process::Command` launched via `sh -c`; enforces a
51/// configurable per-call timeout; kills the child process group (POSIX) on
52/// expiry; truncates large outputs.
53/// Test: `bash::tests::fast_command_exit_zero`, `nonzero_exit_is_recoverable`,
54/// `timeout_kills_child`, `cwd_is_honored`, `stdout_truncation`,
55/// `registry_registration_and_dispatch`.
56pub struct BashTool {
57    /// Working directory for the spawned process. `None` means inherit the
58    /// tcode process's current directory.
59    pub working_dir: Option<PathBuf>,
60    /// Default timeout applied when the caller does not supply `timeout_secs`.
61    pub default_timeout: Duration,
62}
63
64impl BashTool {
65    /// Construct with an optional working directory and default timeout.
66    ///
67    /// Why: Callers providing a `RunContext` can inject `working_dir` so the
68    /// shell respects the project root without mutating global process state.
69    /// What: Stores `working_dir` and `default_timeout`.
70    /// Test: Constructed in all `BashTool` tests.
71    pub fn new(working_dir: Option<PathBuf>, default_timeout: Duration) -> Self {
72        Self {
73            working_dir,
74            default_timeout,
75        }
76    }
77
78    /// Construct with default settings (no cwd override, 120 s timeout).
79    ///
80    /// Why: Convenience constructor for callers that accept process defaults.
81    /// What: Delegates to `new(None, DEFAULT_TIMEOUT_SECS seconds)`.
82    /// Test: `bash::tests::fast_command_exit_zero`.
83    pub fn default_config() -> Self {
84        Self::new(None, Duration::from_secs(DEFAULT_TIMEOUT_SECS))
85    }
86}
87
88#[async_trait]
89impl ToolExecutor for BashTool {
90    fn name(&self) -> &str {
91        BASH_TOOL_NAME
92    }
93
94    /// OpenAI-function schema for the bash tool.
95    ///
96    /// Why: The LLM function-calling loop requires a JSON schema to generate
97    /// valid calls. Declaring `command` as required and `timeout_secs` as
98    /// optional keeps the schema minimal while supporting per-call overrides.
99    /// What: Returns a `{ type: "function", function: { … } }` Value.
100    /// Test: Checked via `bash::tests::registry_registration_and_dispatch`.
101    fn schema(&self) -> Value {
102        json!({
103            "type": "function",
104            "function": {
105                "name": "bash",
106                "description": "Execute a shell command and return its stdout, stderr, and exit code. Non-zero exit codes are surfaced as recoverable results, not errors — the model should read the output and iterate.",
107                "parameters": {
108                    "type": "object",
109                    "properties": {
110                        "command": {
111                            "type": "string",
112                            "description": "Shell command to run (passed to `sh -c`)."
113                        },
114                        "timeout_secs": {
115                            "type": "integer",
116                            "description": "Optional timeout in seconds. Defaults to 120. The child process (and its group) is killed on expiry.",
117                            "minimum": 1
118                        }
119                    },
120                    "required": ["command"],
121                    "additionalProperties": false
122                }
123            }
124        })
125    }
126
127    /// Mark as RESTRICTED so ReadOnly/Analytics callers cannot invoke it.
128    ///
129    /// Why: Shell execution is a privileged capability. Untrusted or
130    /// analytics-only callers must not be able to run arbitrary commands.
131    /// What: Returns `[ReadOnly, Analytics]` — callers in either tier are
132    /// blocked at the registry's `dispatch_for_user` boundary.
133    /// Test: Covered by `crate::tools::registry` tier-gating tests; also
134    /// checked via `bash::tests::restricted_tiers_includes_readonly_and_analytics`.
135    fn restricted_tiers(&self) -> &[ServiceTier] {
136        &[ServiceTier::ReadOnly, ServiceTier::Analytics]
137    }
138
139    async fn execute(&self, args: Value) -> ToolResult {
140        // ── Parse arguments ────────────────────────────────────────────────
141        let Some(command) = args.get("command").and_then(Value::as_str) else {
142            return ToolResult::err("bash: missing required 'command' parameter");
143        };
144        if command.trim().is_empty() {
145            return ToolResult::err("bash: 'command' must not be empty");
146        }
147
148        let timeout_secs: u64 = args
149            .get("timeout_secs")
150            .and_then(Value::as_u64)
151            .unwrap_or(self.default_timeout.as_secs());
152        let call_timeout = Duration::from_secs(timeout_secs);
153
154        // ── Build the subprocess ───────────────────────────────────────────
155        let mut cmd = Command::new("sh");
156        cmd.arg("-c").arg(command);
157        cmd.stdout(std::process::Stdio::piped());
158        cmd.stderr(std::process::Stdio::piped());
159        cmd.stdin(std::process::Stdio::null());
160
161        if let Some(ref dir) = self.working_dir {
162            cmd.current_dir(dir);
163        }
164
165        // On Unix, spawn the child into its own process group so that a
166        // timeout kill reaches the entire process tree, not just the shell.
167        // SAFETY: `setsid()` is documented async-signal-safe. The closure
168        // runs in the forked child after `fork()` but before `exec()`.
169        #[cfg(unix)]
170        unsafe {
171            cmd.pre_exec(|| {
172                // Create a new session; this process becomes the leader of
173                // a new process group with pgid == pid.
174                if libc::setsid() == -1 {
175                    // Non-fatal: fall back to the parent's pgid.
176                }
177                Ok(())
178            });
179        }
180
181        let mut child = match cmd.spawn() {
182            Ok(c) => c,
183            Err(e) => {
184                return ToolResult::err(format!("bash: failed to spawn command: {e}"));
185            }
186        };
187
188        // Grab the piped handles before consuming `child` in the wait call.
189        let mut stdout_handle = child.stdout.take().expect("stdout is piped");
190        let mut stderr_handle = child.stderr.take().expect("stderr is piped");
191
192        // ── Read stdout + stderr + wait with timeout ───────────────────────
193        let run_result = timeout(call_timeout, async {
194            let mut stdout_bytes = Vec::new();
195            let mut stderr_bytes = Vec::new();
196
197            // Read both streams concurrently to avoid pipe deadlocks.
198            let (stdout_res, stderr_res, wait_res) = tokio::join!(
199                read_capped(&mut stdout_handle, MAX_OUTPUT_BYTES),
200                read_capped(&mut stderr_handle, MAX_OUTPUT_BYTES),
201                child.wait()
202            );
203
204            stdout_bytes.extend_from_slice(&stdout_res);
205            stderr_bytes.extend_from_slice(&stderr_res);
206
207            let status = wait_res?;
208            Ok::<_, std::io::Error>((stdout_bytes, stderr_bytes, status))
209        })
210        .await;
211
212        match run_result {
213            // ── Timed out ─────────────────────────────────────────────────
214            Err(_elapsed) => {
215                // Kill the child's entire process group on Unix so background
216                // processes spawned by the shell are also reaped.
217                #[cfg(unix)]
218                {
219                    if let Some(pid) = child.id() {
220                        // SAFETY: `kill` is a safe POSIX syscall. The pid value
221                        // comes from the kernel; `i32::try_from` is fallible but
222                        // realistically cannot overflow for valid process IDs.
223                        if let Ok(signed_pid) = i32::try_from(pid) {
224                            // Negative pgid means "kill the whole process group".
225                            unsafe {
226                                libc::kill(-signed_pid, libc::SIGKILL);
227                            }
228                        }
229                    }
230                }
231                // Always attempt child.kill() as a fallback (handles non-Unix
232                // or the case where setsid failed and we fall back to the child
233                // itself).
234                let _ = child.kill().await;
235                let _ = child.wait().await;
236
237                ToolResult::err(format!(
238                    "bash: command timed out after {timeout_secs}s and was killed\ncommand: {command}"
239                ))
240            }
241
242            // ── Completed (exit 0 or non-zero) ────────────────────────────
243            Ok(Ok((stdout_bytes, stderr_bytes, status))) => {
244                let stdout = lossy_truncated(&stdout_bytes, MAX_OUTPUT_BYTES);
245                let stderr = lossy_truncated(&stderr_bytes, MAX_OUTPUT_BYTES);
246                let exit_code = status.code().unwrap_or(-1);
247
248                let mut out = String::new();
249                if !stdout.is_empty() {
250                    out.push_str("stdout:\n");
251                    out.push_str(&stdout);
252                    if !stdout.ends_with('\n') {
253                        out.push('\n');
254                    }
255                }
256                if !stderr.is_empty() {
257                    if !out.is_empty() {
258                        out.push('\n');
259                    }
260                    out.push_str("stderr:\n");
261                    out.push_str(&stderr);
262                    if !stderr.ends_with('\n') {
263                        out.push('\n');
264                    }
265                }
266                out.push_str(&format!("exit_code: {exit_code}"));
267
268                // Non-zero exit is a *recoverable* result (failing pytest output
269                // should be fed back to the model, not abort the loop).
270                ToolResult::ok(out)
271            }
272
273            // ── IO error from wait() ───────────────────────────────────────
274            Ok(Err(io_err)) => {
275                ToolResult::err(format!("bash: IO error while waiting for child: {io_err}"))
276            }
277        }
278    }
279}
280
281// ── Helpers ───────────────────────────────────────────────────────────────────
282
283/// Read up to `cap` bytes from an async reader without exceeding memory.
284///
285/// Why: Commands like `find /` can produce GB of output; we must bound
286/// memory without blocking the executor.
287/// What: Reads the full stream into a `Vec<u8>` capped at `cap` bytes;
288/// silently discards the remainder (the caller appends a truncation notice).
289/// Test: `bash::tests::stdout_truncation`.
290pub(crate) async fn read_capped<R: AsyncReadExt + Unpin>(reader: &mut R, cap: usize) -> Vec<u8> {
291    let mut buf = Vec::with_capacity(cap.min(4096));
292    let mut tmp = [0u8; 4096];
293    loop {
294        match reader.read(&mut tmp).await {
295            Ok(0) => break,
296            Ok(n) => {
297                let remaining = cap.saturating_sub(buf.len());
298                if remaining == 0 {
299                    break;
300                }
301                buf.extend_from_slice(&tmp[..n.min(remaining)]);
302            }
303            Err(_) => break,
304        }
305    }
306    buf
307}
308
309/// Convert bytes to a lossy UTF-8 string, appending a truncation notice when
310/// the captured byte count exactly equals `cap`.
311///
312/// Why: The LLM needs text; raw bytes are not useful. The truncation notice
313/// tells the model that output was cut so it can adjust.
314/// What: Calls `String::from_utf8_lossy`, then checks for truncation.
315/// Test: `bash::tests::stdout_truncation`.
316pub(crate) fn lossy_truncated(bytes: &[u8], cap: usize) -> String {
317    let s = String::from_utf8_lossy(bytes).into_owned();
318    if bytes.len() >= cap {
319        format!("{s}\n[... output truncated at {cap} bytes ...]")
320    } else {
321        s
322    }
323}