codive-tools 0.1.0

Tool implementations for Codive
Documentation
//! ReadFile tool for reading file contents
//!
//! This tool reads the contents of files and returns them to the agent.
//! It supports reading specific line ranges for large files.

use codive_core::tool::{Tool, ToolOutput};
use async_trait::async_trait;
use serde::Deserialize;
use std::path::Path;
use tokio::fs;
use tracing::debug;

/// Maximum file size to read (10MB)
const MAX_FILE_SIZE: u64 = 10 * 1024 * 1024;

/// Default number of lines to return
const DEFAULT_MAX_LINES: usize = 2000;

/// Tool for reading file contents
pub struct ReadFileTool {
    /// Maximum file size to read
    max_file_size: u64,
    /// Maximum lines to return by default
    max_lines: usize,
}

impl ReadFileTool {
    /// Create a new ReadFileTool with default settings
    pub fn new() -> Self {
        Self {
            max_file_size: MAX_FILE_SIZE,
            max_lines: DEFAULT_MAX_LINES,
        }
    }

    /// Set the maximum file size
    pub fn with_max_file_size(mut self, size: u64) -> Self {
        self.max_file_size = size;
        self
    }

    /// Set the maximum lines to return
    pub fn with_max_lines(mut self, lines: usize) -> Self {
        self.max_lines = lines;
        self
    }
}

impl Default for ReadFileTool {
    fn default() -> Self {
        Self::new()
    }
}

/// Parameters for the read_file tool
#[derive(Debug, Deserialize)]
struct ReadFileParams {
    /// Path to the file to read
    path: String,
    /// Line number to start from (1-indexed, optional)
    #[serde(default)]
    offset: Option<usize>,
    /// Maximum number of lines to read (optional)
    #[serde(default)]
    limit: Option<usize>,
}

#[async_trait]
impl Tool for ReadFileTool {
    fn name(&self) -> &str {
        "read_file"
    }

    fn description(&self) -> &str {
        "Read the contents of a file. Returns the file content with line numbers. \
         For large files, use offset and limit to read specific sections."
    }

    fn parameters_schema(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "The path to the file to read"
                },
                "offset": {
                    "type": "integer",
                    "description": "Line number to start from (1-indexed). Default: 1"
                },
                "limit": {
                    "type": "integer",
                    "description": "Maximum number of lines to read. Default: 2000"
                }
            },
            "required": ["path"]
        })
    }

    async fn execute(&self, params: serde_json::Value) -> ToolOutput {
        // Parse parameters
        let params: ReadFileParams = match serde_json::from_value(params) {
            Ok(p) => p,
            Err(e) => return ToolOutput::error(format!("Invalid parameters: {}", e)),
        };

        let path = Path::new(&params.path);
        debug!(path = %path.display(), "Reading file");

        // Check if file exists
        if !path.exists() {
            return ToolOutput::error(format!("File not found: {}", path.display()));
        }

        // Check if it's a file (not a directory)
        if !path.is_file() {
            return ToolOutput::error(format!("Not a file: {}", path.display()));
        }

        // Check file size
        let metadata = match fs::metadata(path).await {
            Ok(m) => m,
            Err(e) => return ToolOutput::error(format!("Failed to read file metadata: {}", e)),
        };

        if metadata.len() > self.max_file_size {
            return ToolOutput::error(format!(
                "File too large: {} bytes (max: {} bytes). Use offset/limit to read sections.",
                metadata.len(),
                self.max_file_size
            ));
        }

        // Read the file
        let content = match fs::read_to_string(path).await {
            Ok(c) => c,
            Err(e) => {
                // Try reading as binary if UTF-8 fails
                if e.kind() == std::io::ErrorKind::InvalidData {
                    return ToolOutput::error(
                        "File appears to be binary and cannot be read as text",
                    );
                }
                return ToolOutput::error(format!("Failed to read file: {}", e));
            }
        };

        // Split into lines and apply offset/limit
        let lines: Vec<&str> = content.lines().collect();
        let total_lines = lines.len();

        let offset = params.offset.unwrap_or(1).saturating_sub(1); // Convert to 0-indexed
        let limit = params.limit.unwrap_or(self.max_lines);

        // Slice the lines
        let start = offset.min(lines.len());
        let end = (start + limit).min(lines.len());
        let selected_lines = &lines[start..end];

        // Format with line numbers
        let mut output = String::new();

        // Add header if we're not showing the whole file
        if start > 0 || end < total_lines {
            output.push_str(&format!(
                "Showing lines {}-{} of {} total\n\n",
                start + 1,
                end,
                total_lines
            ));
        }

        // Add lines with line numbers
        for (i, line) in selected_lines.iter().enumerate() {
            let line_num = start + i + 1;
            output.push_str(&format!("{:>6}│{}\n", line_num, line));
        }

        // Add footer if there are more lines
        if end < total_lines {
            output.push_str(&format!(
                "\n... {} more lines. Use offset={} to continue.",
                total_lines - end,
                end + 1
            ));
        }

        ToolOutput::success(output)
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    #[test]
    fn test_read_file_tool_name() {
        let tool = ReadFileTool::new();
        assert_eq!(tool.name(), "read_file");
    }

    #[test]
    fn test_read_file_schema() {
        let tool = ReadFileTool::new();
        let schema = tool.parameters_schema();
        assert_eq!(schema["type"], "object");
        assert!(schema["properties"]["path"].is_object());
        assert_eq!(schema["required"][0], "path");
    }

    #[tokio::test]
    async fn test_read_simple_file() {
        let mut file = NamedTempFile::new().unwrap();
        writeln!(file, "line 1").unwrap();
        writeln!(file, "line 2").unwrap();
        writeln!(file, "line 3").unwrap();

        let tool = ReadFileTool::new();
        let output = tool
            .execute(serde_json::json!({
                "path": file.path().to_str().unwrap()
            }))
            .await;

        assert!(output.is_success());
        assert!(output.content.contains("line 1"));
        assert!(output.content.contains("line 2"));
        assert!(output.content.contains("line 3"));
    }

    #[tokio::test]
    async fn test_read_with_line_numbers() {
        let mut file = NamedTempFile::new().unwrap();
        writeln!(file, "first").unwrap();
        writeln!(file, "second").unwrap();

        let tool = ReadFileTool::new();
        let output = tool
            .execute(serde_json::json!({
                "path": file.path().to_str().unwrap()
            }))
            .await;

        assert!(output.is_success());
        // Should have line numbers
        assert!(output.content.contains("1│"));
        assert!(output.content.contains("2│"));
    }

    #[tokio::test]
    async fn test_read_with_offset() {
        let mut file = NamedTempFile::new().unwrap();
        for i in 1..=10 {
            writeln!(file, "line {}", i).unwrap();
        }

        let tool = ReadFileTool::new();
        let output = tool
            .execute(serde_json::json!({
                "path": file.path().to_str().unwrap(),
                "offset": 5
            }))
            .await;

        assert!(output.is_success());
        assert!(output.content.contains("line 5"));
        assert!(!output.content.contains("│line 4"));
    }

    #[tokio::test]
    async fn test_read_with_limit() {
        let mut file = NamedTempFile::new().unwrap();
        for i in 1..=10 {
            writeln!(file, "line {}", i).unwrap();
        }

        let tool = ReadFileTool::new();
        let output = tool
            .execute(serde_json::json!({
                "path": file.path().to_str().unwrap(),
                "limit": 3
            }))
            .await;

        assert!(output.is_success());
        assert!(output.content.contains("line 1"));
        assert!(output.content.contains("line 2"));
        assert!(output.content.contains("line 3"));
        assert!(!output.content.contains("│line 4"));
        assert!(output.content.contains("more lines"));
    }

    #[tokio::test]
    async fn test_read_nonexistent_file() {
        let tool = ReadFileTool::new();
        let output = tool
            .execute(serde_json::json!({
                "path": "/nonexistent/file/path/12345.txt"
            }))
            .await;

        assert!(output.is_error);
        assert!(output.content.contains("not found"));
    }

    #[tokio::test]
    async fn test_read_directory() {
        let tool = ReadFileTool::new();
        let output = tool
            .execute(serde_json::json!({
                "path": "/tmp"
            }))
            .await;

        assert!(output.is_error);
        assert!(output.content.contains("Not a file"));
    }

    #[tokio::test]
    async fn test_read_invalid_params() {
        let tool = ReadFileTool::new();
        let output = tool.execute(serde_json::json!({})).await;

        assert!(output.is_error);
        assert!(output.content.contains("Invalid parameters"));
    }

    #[tokio::test]
    async fn test_read_empty_file() {
        let file = NamedTempFile::new().unwrap();

        let tool = ReadFileTool::new();
        let output = tool
            .execute(serde_json::json!({
                "path": file.path().to_str().unwrap()
            }))
            .await;

        assert!(output.is_success());
    }
}