codive-tools 0.1.0

Tool implementations for Codive
Documentation
//! Bash tool for executing shell commands
//!
//! This tool allows the agent to execute shell commands and capture their output.
//!
//! # Security Considerations
//!
//! Command execution is inherently dangerous. This tool should be used with caution
//! and potentially sandboxed in production environments.

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};

/// Default timeout for command execution (2 minutes)
const DEFAULT_TIMEOUT_SECS: u64 = 120;

/// Maximum output size to capture (50KB - larger outputs can blow up context)
const MAX_OUTPUT_SIZE: usize = 50 * 1024;

/// Tool for executing bash commands
pub struct BashTool {
    /// Default timeout for commands
    timeout: Duration,
    /// Working directory for commands (None = inherit)
    working_dir: Option<String>,
}

impl BashTool {
    /// Create a new BashTool with default settings
    pub fn new() -> Self {
        Self {
            timeout: Duration::from_secs(DEFAULT_TIMEOUT_SECS),
            working_dir: None,
        }
    }

    /// Set the default timeout for commands
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Set the working directory for commands
    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()
    }
}

/// Parameters for the bash tool
#[derive(Debug, Deserialize)]
struct BashParams {
    /// The command to execute
    command: String,
    /// Optional timeout in seconds (defaults to 120)
    #[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 {
        // Parse parameters
        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");

        // Determine timeout
        let timeout_duration = params
            .timeout
            .map(Duration::from_secs)
            .unwrap_or(self.timeout);

        // Build the command
        let mut cmd = Command::new("bash");
        cmd.arg("-c").arg(&params.command);
        cmd.stdout(Stdio::piped());
        cmd.stderr(Stdio::piped());

        // Set working directory if configured
        if let Some(ref dir) = self.working_dir {
            cmd.current_dir(dir);
        }

        // Execute with timeout
        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);

                // Truncate output if too large
                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() {
                    // Success - return stdout (and stderr if present)
                    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 {
                    // Command failed
                    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()
                ))
            }
        }
    }
}

/// Truncate output if it exceeds the maximum size
/// Returns (truncated_output, was_truncated)
fn truncate_output(output: &str, max_size: usize) -> (&str, bool) {
    if output.len() > max_size {
        // Find a safe UTF-8 boundary
        let truncated = &output[..max_size];
        // Find the last newline to truncate at a clean boundary
        let result = if let Some(last_newline) = truncated.rfind('\n') {
            &truncated[..last_newline]
        } else {
            truncated
        };
        (result, true)
    } else {
        (output, false)
    }
}

// ============================================================================
// Tests
// ============================================================================

#[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);
    }
}