use codive_core::tool::{Tool, ToolOutput};
use async_trait::async_trait;
use serde::Deserialize;
use std::process::Stdio;
use std::time::Duration;
use tokio::process::Command;
use tokio::time::timeout;
use tracing::{debug, warn};
const DEFAULT_TIMEOUT_SECS: u64 = 120;
const MAX_OUTPUT_SIZE: usize = 50 * 1024;
pub struct BashTool {
timeout: Duration,
working_dir: Option<String>,
}
impl BashTool {
pub fn new() -> Self {
Self {
timeout: Duration::from_secs(DEFAULT_TIMEOUT_SECS),
working_dir: None,
}
}
pub fn with_timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
pub fn with_working_dir(mut self, dir: impl Into<String>) -> Self {
self.working_dir = Some(dir.into());
self
}
}
impl Default for BashTool {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Deserialize)]
struct BashParams {
command: String,
#[serde(default)]
timeout: Option<u64>,
}
#[async_trait]
impl Tool for BashTool {
fn name(&self) -> &str {
"bash"
}
fn description(&self) -> &str {
"Execute a bash command and return its output. \
Use this for running shell commands, scripts, or system operations. \
Commands are executed with bash -c."
}
fn parameters_schema(&self) -> serde_json::Value {
serde_json::json!({
"type": "object",
"properties": {
"command": {
"type": "string",
"description": "The bash command to execute"
},
"timeout": {
"type": "integer",
"description": "Optional timeout in seconds (default: 120)"
}
},
"required": ["command"]
})
}
async fn execute(&self, params: serde_json::Value) -> ToolOutput {
let params: BashParams = match serde_json::from_value(params) {
Ok(p) => p,
Err(e) => return ToolOutput::error(format!("Invalid parameters: {}", e)),
};
debug!(command = %params.command, "Executing bash command");
let timeout_duration = params
.timeout
.map(Duration::from_secs)
.unwrap_or(self.timeout);
let mut cmd = Command::new("bash");
cmd.arg("-c").arg(¶ms.command);
cmd.stdout(Stdio::piped());
cmd.stderr(Stdio::piped());
if let Some(ref dir) = self.working_dir {
cmd.current_dir(dir);
}
let result = timeout(timeout_duration, cmd.output()).await;
match result {
Ok(Ok(output)) => {
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let (stdout, stdout_truncated) = truncate_output(&stdout, MAX_OUTPUT_SIZE);
let (stderr, stderr_truncated) = truncate_output(&stderr, MAX_OUTPUT_SIZE);
let exit_code = output.status.code().unwrap_or(-1);
if output.status.success() {
let mut result = stdout.to_string();
if stdout_truncated {
result.push_str("\n... [output truncated, exceeded 50KB limit]");
}
if !stderr.is_empty() {
result.push_str("\n--- stderr ---\n");
result.push_str(stderr);
if stderr_truncated {
result.push_str("\n... [stderr truncated]");
}
}
ToolOutput::success(result)
} else {
let mut result = format!("Command failed with exit code {}\n", exit_code);
if !stdout.is_empty() {
result.push_str("--- stdout ---\n");
result.push_str(stdout);
if stdout_truncated {
result.push_str("\n... [output truncated]");
}
result.push('\n');
}
if !stderr.is_empty() {
result.push_str("--- stderr ---\n");
result.push_str(stderr);
if stderr_truncated {
result.push_str("\n... [stderr truncated]");
}
}
ToolOutput::error(result)
}
}
Ok(Err(e)) => {
warn!(error = %e, "Failed to execute command");
ToolOutput::error(format!("Failed to execute command: {}", e))
}
Err(_) => {
warn!(timeout = ?timeout_duration, "Command timed out");
ToolOutput::error(format!(
"Command timed out after {} seconds",
timeout_duration.as_secs()
))
}
}
}
}
fn truncate_output(output: &str, max_size: usize) -> (&str, bool) {
if output.len() > max_size {
let truncated = &output[..max_size];
let result = if let Some(last_newline) = truncated.rfind('\n') {
&truncated[..last_newline]
} else {
truncated
};
(result, true)
} else {
(output, false)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_bash_tool_name() {
let tool = BashTool::new();
assert_eq!(tool.name(), "bash");
}
#[test]
fn test_bash_tool_schema() {
let tool = BashTool::new();
let schema = tool.parameters_schema();
assert_eq!(schema["type"], "object");
assert!(schema["properties"]["command"].is_object());
assert_eq!(schema["required"][0], "command");
}
#[test]
fn test_bash_params_parsing() {
let params = serde_json::json!({
"command": "echo hello"
});
let parsed: BashParams = serde_json::from_value(params).unwrap();
assert_eq!(parsed.command, "echo hello");
assert!(parsed.timeout.is_none());
}
#[test]
fn test_bash_params_with_timeout() {
let params = serde_json::json!({
"command": "sleep 1",
"timeout": 5
});
let parsed: BashParams = serde_json::from_value(params).unwrap();
assert_eq!(parsed.timeout, Some(5));
}
#[tokio::test]
async fn test_bash_echo() {
let tool = BashTool::new();
let output = tool
.execute(serde_json::json!({
"command": "echo 'hello world'"
}))
.await;
assert!(output.is_success());
assert!(output.content.contains("hello world"));
}
#[tokio::test]
async fn test_bash_invalid_command() {
let tool = BashTool::new();
let output = tool
.execute(serde_json::json!({
"command": "this_command_does_not_exist_12345"
}))
.await;
assert!(output.is_error);
assert!(output.content.contains("not found") || output.content.contains("exit code"));
}
#[tokio::test]
async fn test_bash_exit_code() {
let tool = BashTool::new();
let output = tool
.execute(serde_json::json!({
"command": "exit 42"
}))
.await;
assert!(output.is_error);
assert!(output.content.contains("42"));
}
#[tokio::test]
async fn test_bash_stderr() {
let tool = BashTool::new();
let output = tool
.execute(serde_json::json!({
"command": "echo 'stdout message' && echo 'stderr message' >&2"
}))
.await;
assert!(output.is_success());
assert!(output.content.contains("stdout message"));
assert!(output.content.contains("stderr message"));
}
#[tokio::test]
async fn test_bash_timeout() {
let tool = BashTool::new().with_timeout(Duration::from_millis(100));
let output = tool
.execute(serde_json::json!({
"command": "sleep 10"
}))
.await;
assert!(output.is_error);
assert!(output.content.contains("timed out"));
}
#[tokio::test]
async fn test_bash_invalid_params() {
let tool = BashTool::new();
let output = tool.execute(serde_json::json!({})).await;
assert!(output.is_error);
assert!(output.content.contains("Invalid parameters"));
}
#[test]
fn test_truncate_output() {
let long_output = "a".repeat(2000);
let (truncated, was_truncated) = truncate_output(&long_output, 1000);
assert!(truncated.len() <= 1000);
assert!(was_truncated);
}
#[test]
fn test_truncate_at_newline() {
let output = "line1\nline2\nline3\nline4";
let (truncated, was_truncated) = truncate_output(output, 15);
assert!(truncated.len() <= 15);
assert!(was_truncated);
}
#[test]
fn test_no_truncation_needed() {
let output = "short output";
let (result, was_truncated) = truncate_output(output, 1000);
assert_eq!(result, output);
assert!(!was_truncated);
}
}