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