Skip to main content

codive_tools/
bash.rs

1//! Bash tool for executing shell commands
2//!
3//! This tool allows the agent to execute shell commands and capture their output.
4//!
5//! # Security Considerations
6//!
7//! Command execution is inherently dangerous. This tool should be used with caution
8//! and potentially sandboxed in production environments.
9
10use codive_core::tool::{Tool, ToolOutput};
11use async_trait::async_trait;
12use serde::Deserialize;
13use std::process::Stdio;
14use std::time::Duration;
15use tokio::process::Command;
16use tokio::time::timeout;
17use tracing::{debug, warn};
18
19/// Default timeout for command execution (2 minutes)
20const DEFAULT_TIMEOUT_SECS: u64 = 120;
21
22/// Maximum output size to capture (50KB - larger outputs can blow up context)
23const MAX_OUTPUT_SIZE: usize = 50 * 1024;
24
25/// Tool for executing bash commands
26pub struct BashTool {
27    /// Default timeout for commands
28    timeout: Duration,
29    /// Working directory for commands (None = inherit)
30    working_dir: Option<String>,
31}
32
33impl BashTool {
34    /// Create a new BashTool with default settings
35    pub fn new() -> Self {
36        Self {
37            timeout: Duration::from_secs(DEFAULT_TIMEOUT_SECS),
38            working_dir: None,
39        }
40    }
41
42    /// Set the default timeout for commands
43    pub fn with_timeout(mut self, timeout: Duration) -> Self {
44        self.timeout = timeout;
45        self
46    }
47
48    /// Set the working directory for commands
49    pub fn with_working_dir(mut self, dir: impl Into<String>) -> Self {
50        self.working_dir = Some(dir.into());
51        self
52    }
53}
54
55impl Default for BashTool {
56    fn default() -> Self {
57        Self::new()
58    }
59}
60
61/// Parameters for the bash tool
62#[derive(Debug, Deserialize)]
63struct BashParams {
64    /// The command to execute
65    command: String,
66    /// Optional timeout in seconds (defaults to 120)
67    #[serde(default)]
68    timeout: Option<u64>,
69}
70
71#[async_trait]
72impl Tool for BashTool {
73    fn name(&self) -> &str {
74        "bash"
75    }
76
77    fn description(&self) -> &str {
78        "Execute a bash command and return its output. \
79         Use this for running shell commands, scripts, or system operations. \
80         Commands are executed with bash -c."
81    }
82
83    fn parameters_schema(&self) -> serde_json::Value {
84        serde_json::json!({
85            "type": "object",
86            "properties": {
87                "command": {
88                    "type": "string",
89                    "description": "The bash command to execute"
90                },
91                "timeout": {
92                    "type": "integer",
93                    "description": "Optional timeout in seconds (default: 120)"
94                }
95            },
96            "required": ["command"]
97        })
98    }
99
100    async fn execute(&self, params: serde_json::Value) -> ToolOutput {
101        // Parse parameters
102        let params: BashParams = match serde_json::from_value(params) {
103            Ok(p) => p,
104            Err(e) => return ToolOutput::error(format!("Invalid parameters: {}", e)),
105        };
106
107        debug!(command = %params.command, "Executing bash command");
108
109        // Determine timeout
110        let timeout_duration = params
111            .timeout
112            .map(Duration::from_secs)
113            .unwrap_or(self.timeout);
114
115        // Build the command
116        let mut cmd = Command::new("bash");
117        cmd.arg("-c").arg(&params.command);
118        cmd.stdout(Stdio::piped());
119        cmd.stderr(Stdio::piped());
120
121        // Set working directory if configured
122        if let Some(ref dir) = self.working_dir {
123            cmd.current_dir(dir);
124        }
125
126        // Execute with timeout
127        let result = timeout(timeout_duration, cmd.output()).await;
128
129        match result {
130            Ok(Ok(output)) => {
131                let stdout = String::from_utf8_lossy(&output.stdout);
132                let stderr = String::from_utf8_lossy(&output.stderr);
133
134                // Truncate output if too large
135                let (stdout, stdout_truncated) = truncate_output(&stdout, MAX_OUTPUT_SIZE);
136                let (stderr, stderr_truncated) = truncate_output(&stderr, MAX_OUTPUT_SIZE);
137
138                let exit_code = output.status.code().unwrap_or(-1);
139
140                if output.status.success() {
141                    // Success - return stdout (and stderr if present)
142                    let mut result = stdout.to_string();
143                    if stdout_truncated {
144                        result.push_str("\n... [output truncated, exceeded 50KB limit]");
145                    }
146                    if !stderr.is_empty() {
147                        result.push_str("\n--- stderr ---\n");
148                        result.push_str(stderr);
149                        if stderr_truncated {
150                            result.push_str("\n... [stderr truncated]");
151                        }
152                    }
153                    ToolOutput::success(result)
154                } else {
155                    // Command failed
156                    let mut result = format!("Command failed with exit code {}\n", exit_code);
157                    if !stdout.is_empty() {
158                        result.push_str("--- stdout ---\n");
159                        result.push_str(stdout);
160                        if stdout_truncated {
161                            result.push_str("\n... [output truncated]");
162                        }
163                        result.push('\n');
164                    }
165                    if !stderr.is_empty() {
166                        result.push_str("--- stderr ---\n");
167                        result.push_str(stderr);
168                        if stderr_truncated {
169                            result.push_str("\n... [stderr truncated]");
170                        }
171                    }
172                    ToolOutput::error(result)
173                }
174            }
175            Ok(Err(e)) => {
176                warn!(error = %e, "Failed to execute command");
177                ToolOutput::error(format!("Failed to execute command: {}", e))
178            }
179            Err(_) => {
180                warn!(timeout = ?timeout_duration, "Command timed out");
181                ToolOutput::error(format!(
182                    "Command timed out after {} seconds",
183                    timeout_duration.as_secs()
184                ))
185            }
186        }
187    }
188}
189
190/// Truncate output if it exceeds the maximum size
191/// Returns (truncated_output, was_truncated)
192fn truncate_output(output: &str, max_size: usize) -> (&str, bool) {
193    if output.len() > max_size {
194        // Find a safe UTF-8 boundary
195        let truncated = &output[..max_size];
196        // Find the last newline to truncate at a clean boundary
197        let result = if let Some(last_newline) = truncated.rfind('\n') {
198            &truncated[..last_newline]
199        } else {
200            truncated
201        };
202        (result, true)
203    } else {
204        (output, false)
205    }
206}
207
208// ============================================================================
209// Tests
210// ============================================================================
211
212#[cfg(test)]
213mod tests {
214    use super::*;
215
216    #[test]
217    fn test_bash_tool_name() {
218        let tool = BashTool::new();
219        assert_eq!(tool.name(), "bash");
220    }
221
222    #[test]
223    fn test_bash_tool_schema() {
224        let tool = BashTool::new();
225        let schema = tool.parameters_schema();
226        assert_eq!(schema["type"], "object");
227        assert!(schema["properties"]["command"].is_object());
228        assert_eq!(schema["required"][0], "command");
229    }
230
231    #[test]
232    fn test_bash_params_parsing() {
233        let params = serde_json::json!({
234            "command": "echo hello"
235        });
236        let parsed: BashParams = serde_json::from_value(params).unwrap();
237        assert_eq!(parsed.command, "echo hello");
238        assert!(parsed.timeout.is_none());
239    }
240
241    #[test]
242    fn test_bash_params_with_timeout() {
243        let params = serde_json::json!({
244            "command": "sleep 1",
245            "timeout": 5
246        });
247        let parsed: BashParams = serde_json::from_value(params).unwrap();
248        assert_eq!(parsed.timeout, Some(5));
249    }
250
251    #[tokio::test]
252    async fn test_bash_echo() {
253        let tool = BashTool::new();
254        let output = tool
255            .execute(serde_json::json!({
256                "command": "echo 'hello world'"
257            }))
258            .await;
259
260        assert!(output.is_success());
261        assert!(output.content.contains("hello world"));
262    }
263
264    #[tokio::test]
265    async fn test_bash_invalid_command() {
266        let tool = BashTool::new();
267        let output = tool
268            .execute(serde_json::json!({
269                "command": "this_command_does_not_exist_12345"
270            }))
271            .await;
272
273        assert!(output.is_error);
274        assert!(output.content.contains("not found") || output.content.contains("exit code"));
275    }
276
277    #[tokio::test]
278    async fn test_bash_exit_code() {
279        let tool = BashTool::new();
280        let output = tool
281            .execute(serde_json::json!({
282                "command": "exit 42"
283            }))
284            .await;
285
286        assert!(output.is_error);
287        assert!(output.content.contains("42"));
288    }
289
290    #[tokio::test]
291    async fn test_bash_stderr() {
292        let tool = BashTool::new();
293        let output = tool
294            .execute(serde_json::json!({
295                "command": "echo 'stdout message' && echo 'stderr message' >&2"
296            }))
297            .await;
298
299        assert!(output.is_success());
300        assert!(output.content.contains("stdout message"));
301        assert!(output.content.contains("stderr message"));
302    }
303
304    #[tokio::test]
305    async fn test_bash_timeout() {
306        let tool = BashTool::new().with_timeout(Duration::from_millis(100));
307        let output = tool
308            .execute(serde_json::json!({
309                "command": "sleep 10"
310            }))
311            .await;
312
313        assert!(output.is_error);
314        assert!(output.content.contains("timed out"));
315    }
316
317    #[tokio::test]
318    async fn test_bash_invalid_params() {
319        let tool = BashTool::new();
320        let output = tool.execute(serde_json::json!({})).await;
321
322        assert!(output.is_error);
323        assert!(output.content.contains("Invalid parameters"));
324    }
325
326    #[test]
327    fn test_truncate_output() {
328        let long_output = "a".repeat(2000);
329        let (truncated, was_truncated) = truncate_output(&long_output, 1000);
330        assert!(truncated.len() <= 1000);
331        assert!(was_truncated);
332    }
333
334    #[test]
335    fn test_truncate_at_newline() {
336        let output = "line1\nline2\nline3\nline4";
337        let (truncated, was_truncated) = truncate_output(output, 15);
338        assert!(truncated.len() <= 15);
339        assert!(was_truncated);
340    }
341
342    #[test]
343    fn test_no_truncation_needed() {
344        let output = "short output";
345        let (result, was_truncated) = truncate_output(output, 1000);
346        assert_eq!(result, output);
347        assert!(!was_truncated);
348    }
349}