1use std::path::PathBuf;
4use std::process::Stdio;
5use std::sync::Arc;
6use std::time::Duration;
7
8use async_trait::async_trait;
9use serde::Deserialize;
10use serde_json::{json, Value};
11use tokio::io::AsyncReadExt;
12use tokio::process::Command;
13use tokio::sync::Mutex;
14use tokio_util::sync::CancellationToken;
15
16use crate::agent::tool::{AgentTool, ToolResult};
17use crate::tools::truncate::{format_size, truncate_tail, DEFAULT_MAX_BYTES};
18
19#[cfg(unix)]
20fn kill_process_group(pid: u32) {
21 extern "C" {
23 fn kill(pid: i32, sig: i32) -> i32;
24 }
25 const SIGKILL: i32 = 9;
26 unsafe {
27 kill(-(pid as i32), SIGKILL);
28 }
29}
30
31#[cfg(not(unix))]
32fn kill_process_group(pid: u32) {
33 let _ = pid;
34}
35
36pub struct BashTool {
37 pub cwd: PathBuf,
38}
39
40#[derive(Debug, Deserialize)]
41struct BashInput {
42 #[serde(default)]
43 command: Option<String>,
44 #[serde(default)]
45 timeout: Option<u64>,
46}
47
48fn shell_program() -> (String, Vec<&'static str>) {
49 #[cfg(unix)]
50 {
51 let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string());
55 (shell, vec!["-c"])
56 }
57 #[cfg(not(unix))]
58 {
59 ("cmd.exe".to_string(), vec!["/C"])
60 }
61}
62
63#[async_trait]
64impl AgentTool for BashTool {
65 fn name(&self) -> &str {
66 "bash"
67 }
68 fn description(&self) -> &str {
69 "Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to the last 2000 lines or 50KB (whichever is hit first); when truncated the full output is saved to a temp file. Optionally provide a timeout in seconds."
70 }
71 fn input_schema(&self) -> Value {
72 json!({
73 "type": "object",
74 "properties": {
75 "command": { "type": "string", "description": "Bash command to execute" },
76 "timeout": { "type": "number", "description": "Timeout in seconds (optional, no default timeout)" }
77 },
78 "required": ["command"]
79 })
80 }
81
82 async fn execute(&self, args: Value, cancel: CancellationToken) -> anyhow::Result<ToolResult> {
83 let input: BashInput = serde_json::from_value(args)?;
84 let command = input
85 .command
86 .ok_or_else(|| anyhow::anyhow!("bash requires a 'command' parameter"))?;
87
88 if !self.cwd.exists() {
89 anyhow::bail!(
90 "Working directory does not exist: {}\nCannot execute bash commands.",
91 self.cwd.display()
92 );
93 }
94
95 let (program, args_vec) = shell_program();
96 let mut cmd = Command::new(program);
97 cmd.args(&args_vec).arg(&command);
98 cmd.current_dir(&self.cwd);
99 cmd.stdin(Stdio::null());
100 cmd.stdout(Stdio::piped());
101 cmd.stderr(Stdio::piped());
102 #[cfg(unix)]
103 {
104 cmd.process_group(0);
106 }
107 cmd.kill_on_drop(true);
108
109 let mut child = cmd.spawn()?;
110
111 let pid = child.id();
112 let buffer: Arc<Mutex<Vec<u8>>> = Arc::new(Mutex::new(Vec::new()));
114 let mut stdout = child.stdout.take();
115 let mut stderr = child.stderr.take();
116 let buf1 = buffer.clone();
117 let buf2 = buffer.clone();
118 let stdout_task = tokio::spawn(async move {
119 if let Some(out) = stdout.as_mut() {
120 let mut tmp = [0u8; 8192];
121 loop {
122 match out.read(&mut tmp).await {
123 Ok(0) | Err(_) => break,
124 Ok(n) => buf1.lock().await.extend_from_slice(&tmp[..n]),
125 }
126 }
127 }
128 });
129 let stderr_task = tokio::spawn(async move {
130 if let Some(err) = stderr.as_mut() {
131 let mut tmp = [0u8; 8192];
132 loop {
133 match err.read(&mut tmp).await {
134 Ok(0) | Err(_) => break,
135 Ok(n) => buf2.lock().await.extend_from_slice(&tmp[..n]),
136 }
137 }
138 }
139 });
140
141 let timeout_secs = input.timeout.filter(|&t| t > 0);
142 let wait = child.wait();
143
144 let exit_status = tokio::select! {
145 _ = cancel.cancelled() => {
146 if let Some(pid) = pid { kill_process_group(pid); }
147 let _ = child.wait().await;
148 return Err(anyhow::anyhow!("Command aborted"));
149 }
150 _ = async {
151 if let Some(secs) = timeout_secs {
152 let _ = tokio::time::sleep(Duration::from_secs(secs)).await;
153 } else {
154 std::future::pending::<()>().await;
155 }
156 } => {
157 if let Some(pid) = pid { kill_process_group(pid); }
158 let _ = child.wait().await;
159 stdout_task.await.ok();
169 stderr_task.await.ok();
170 let output = drain(buffer).await;
171 let (text, _details) = format_output(&output, true);
172 return Err(anyhow::anyhow!(
173 "{text}\n\nCommand timed out after {secs} seconds",
174 secs = timeout_secs.unwrap_or(0)
175 ));
176 }
177 status = wait => status,
178 };
179
180 stdout_task.await.ok();
181 stderr_task.await.ok();
182 let output = drain(buffer).await;
183
184 let status = exit_status?;
185 let code = status.code();
186 if !matches!(code, Some(0) | None) {
187 let (text, _) = format_output(&output, true);
188 return Err(anyhow::anyhow!(
189 "{text}\n\nCommand exited with code {}",
190 code.unwrap_or(-1)
191 ));
192 }
193
194 let (text, details) = format_output(&output, false);
195 Ok(ToolResult {
196 content: vec![crate::ai::types::ToolResultContent::Text { text }],
197 details,
198 terminate: false,
199 })
200 }
201}
202
203async fn drain(buffer: Arc<Mutex<Vec<u8>>>) -> Vec<u8> {
204 std::mem::take(&mut *buffer.lock().await)
205}
206
207fn format_output(output: &[u8], _truncated_by_limit: bool) -> (String, Value) {
210 let content = String::from_utf8_lossy(output).to_string();
211 if content.trim().is_empty() {
212 return ("(no output)".to_string(), Value::Null);
213 }
214 let trunc = truncate_tail(&content, None, None);
215 if trunc.truncated {
216 let temp_path = std::env::temp_dir().join(format!("pi-bash-{}.log", uuid_brief()));
217 let _ = std::fs::write(&temp_path, output);
218 let start = trunc.total_lines.saturating_sub(trunc.output_lines) + 1;
219 let end = trunc.total_lines;
220 let notice = match trunc.truncated_by.as_deref() {
221 Some("lines") => format!(
222 "\n\n[Showing lines {start}-{end} of {}. Full output: {}]",
223 trunc.total_lines,
224 temp_path.display()
225 ),
226 _ => format!(
227 "\n\n[Showing lines {start}-{end} of {} ({} limit). Full output: {}]",
228 trunc.total_lines,
229 format_size(DEFAULT_MAX_BYTES),
230 temp_path.display()
231 ),
232 };
233 let details = json!({
234 "truncated": true,
235 "fullOutputPath": temp_path.to_string_lossy(),
236 });
237 (format!("{}{notice}", trunc.content), details)
238 } else {
239 (content, Value::Null)
240 }
241}
242
243fn uuid_brief() -> String {
244 uuid::Uuid::new_v4().simple().to_string()
245}
246
247#[cfg(all(test, unix))]
251mod tests {
252 use super::*;
253 use crate::agent::tool::AgentTool;
254 use tokio_util::sync::CancellationToken;
255
256 fn result_text(res: ToolResult) -> String {
257 match res.content.into_iter().next() {
258 Some(crate::ai::types::ToolResultContent::Text { text }) => text,
259 _ => panic!("expected text tool result"),
260 }
261 }
262
263 #[tokio::test]
264 async fn runs_a_simple_command_and_captures_stdout() {
265 let cwd = std::env::temp_dir().to_path_buf();
267 let tool = BashTool { cwd };
268 let args = serde_json::json!({ "command": "printf 'pi-bash-ok\\n'" });
269 let res = tool.execute(args, CancellationToken::new()).await.unwrap();
270 assert!(result_text(res).contains("pi-bash-ok"));
271 }
272
273 #[tokio::test]
274 async fn timeout_kills_and_surfaces_output_produced_before_the_kill() {
275 let cwd = std::env::temp_dir().to_path_buf();
288 let tool = BashTool { cwd };
289 let args = serde_json::json!({
290 "command": "printf 'before-timeout-marker\\n'; sleep 30",
291 "timeout": 1
292 });
293 let err = tool
294 .execute(args, CancellationToken::new())
295 .await
296 .unwrap_err()
297 .to_string();
298 assert!(
299 err.contains("before-timeout-marker"),
300 "output produced before the kill must be surfaced: {err}"
301 );
302 assert!(
303 err.contains("Command timed out after 1 second"),
304 "timeout must be reported: {err}"
305 );
306 }
307
308 #[tokio::test]
309 async fn cancellation_aborts_the_command() {
310 let cwd = std::env::temp_dir().to_path_buf();
311 let tool = BashTool { cwd };
312 let cancel = CancellationToken::new();
313 let cancel2 = cancel.clone();
314 let canceller = tokio::spawn(async move {
316 tokio::time::sleep(Duration::from_millis(150)).await;
317 cancel2.cancel();
318 });
319 let args = serde_json::json!({ "command": "sleep 30" });
320 let err = tool
321 .execute(args, cancel)
322 .await
323 .unwrap_err()
324 .to_string();
325 canceller.await.ok();
326 assert!(err.contains("aborted"), "cancel must abort: {err}");
327 }
328}