#[cfg(test)]
mod tests;
use std::path::PathBuf;
use std::time::Duration;
use async_trait::async_trait;
use serde_json::{Value, json};
use tokio::io::AsyncReadExt;
use tokio::process::Command;
use tokio::time::timeout;
use crate::tools::traits::{ServiceTier, ToolExecutor, ToolResult};
pub(crate) const MAX_OUTPUT_BYTES: usize = 100 * 1024;
const DEFAULT_TIMEOUT_SECS: u64 = 120;
pub struct BashTool {
pub working_dir: Option<PathBuf>,
pub default_timeout: Duration,
}
impl BashTool {
pub fn new(working_dir: Option<PathBuf>, default_timeout: Duration) -> Self {
Self {
working_dir,
default_timeout,
}
}
pub fn default_config() -> Self {
Self::new(None, Duration::from_secs(DEFAULT_TIMEOUT_SECS))
}
}
#[async_trait]
impl ToolExecutor for BashTool {
fn name(&self) -> &str {
"bash"
}
fn schema(&self) -> Value {
json!({
"type": "function",
"function": {
"name": "bash",
"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.",
"parameters": {
"type": "object",
"properties": {
"command": {
"type": "string",
"description": "Shell command to run (passed to `sh -c`)."
},
"timeout_secs": {
"type": "integer",
"description": "Optional timeout in seconds. Defaults to 120. The child process (and its group) is killed on expiry.",
"minimum": 1
}
},
"required": ["command"],
"additionalProperties": false
}
}
})
}
fn restricted_tiers(&self) -> &[ServiceTier] {
&[ServiceTier::ReadOnly, ServiceTier::Analytics]
}
async fn execute(&self, args: Value) -> ToolResult {
let Some(command) = args.get("command").and_then(Value::as_str) else {
return ToolResult::err("bash: missing required 'command' parameter");
};
if command.trim().is_empty() {
return ToolResult::err("bash: 'command' must not be empty");
}
let timeout_secs: u64 = args
.get("timeout_secs")
.and_then(Value::as_u64)
.unwrap_or(self.default_timeout.as_secs());
let call_timeout = Duration::from_secs(timeout_secs);
let mut cmd = Command::new("sh");
cmd.arg("-c").arg(command);
cmd.stdout(std::process::Stdio::piped());
cmd.stderr(std::process::Stdio::piped());
cmd.stdin(std::process::Stdio::null());
if let Some(ref dir) = self.working_dir {
cmd.current_dir(dir);
}
#[cfg(unix)]
unsafe {
cmd.pre_exec(|| {
if libc::setsid() == -1 {
}
Ok(())
});
}
let mut child = match cmd.spawn() {
Ok(c) => c,
Err(e) => {
return ToolResult::err(format!("bash: failed to spawn command: {e}"));
}
};
let mut stdout_handle = child.stdout.take().expect("stdout is piped");
let mut stderr_handle = child.stderr.take().expect("stderr is piped");
let run_result = timeout(call_timeout, async {
let mut stdout_bytes = Vec::new();
let mut stderr_bytes = Vec::new();
let (stdout_res, stderr_res, wait_res) = tokio::join!(
read_capped(&mut stdout_handle, MAX_OUTPUT_BYTES),
read_capped(&mut stderr_handle, MAX_OUTPUT_BYTES),
child.wait()
);
stdout_bytes.extend_from_slice(&stdout_res);
stderr_bytes.extend_from_slice(&stderr_res);
let status = wait_res?;
Ok::<_, std::io::Error>((stdout_bytes, stderr_bytes, status))
})
.await;
match run_result {
Err(_elapsed) => {
#[cfg(unix)]
{
if let Some(pid) = child.id() {
if let Ok(signed_pid) = i32::try_from(pid) {
unsafe {
libc::kill(-signed_pid, libc::SIGKILL);
}
}
}
}
let _ = child.kill().await;
let _ = child.wait().await;
ToolResult::err(format!(
"bash: command timed out after {timeout_secs}s and was killed\ncommand: {command}"
))
}
Ok(Ok((stdout_bytes, stderr_bytes, status))) => {
let stdout = lossy_truncated(&stdout_bytes, MAX_OUTPUT_BYTES);
let stderr = lossy_truncated(&stderr_bytes, MAX_OUTPUT_BYTES);
let exit_code = status.code().unwrap_or(-1);
let mut out = String::new();
if !stdout.is_empty() {
out.push_str("stdout:\n");
out.push_str(&stdout);
if !stdout.ends_with('\n') {
out.push('\n');
}
}
if !stderr.is_empty() {
if !out.is_empty() {
out.push('\n');
}
out.push_str("stderr:\n");
out.push_str(&stderr);
if !stderr.ends_with('\n') {
out.push('\n');
}
}
out.push_str(&format!("exit_code: {exit_code}"));
ToolResult::ok(out)
}
Ok(Err(io_err)) => {
ToolResult::err(format!("bash: IO error while waiting for child: {io_err}"))
}
}
}
}
pub(crate) async fn read_capped<R: AsyncReadExt + Unpin>(reader: &mut R, cap: usize) -> Vec<u8> {
let mut buf = Vec::with_capacity(cap.min(4096));
let mut tmp = [0u8; 4096];
loop {
match reader.read(&mut tmp).await {
Ok(0) => break,
Ok(n) => {
let remaining = cap.saturating_sub(buf.len());
if remaining == 0 {
break;
}
buf.extend_from_slice(&tmp[..n.min(remaining)]);
}
Err(_) => break,
}
}
buf
}
pub(crate) fn lossy_truncated(bytes: &[u8], cap: usize) -> String {
let s = String::from_utf8_lossy(bytes).into_owned();
if bytes.len() >= cap {
format!("{s}\n[... output truncated at {cap} bytes ...]")
} else {
s
}
}