Skip to main content

codive_tools/
read_file.rs

1//! ReadFile tool for reading file contents
2//!
3//! This tool reads the contents of files and returns them to the agent.
4//! It supports reading specific line ranges for large files.
5
6use codive_core::tool::{Tool, ToolOutput};
7use async_trait::async_trait;
8use serde::Deserialize;
9use std::path::Path;
10use tokio::fs;
11use tracing::debug;
12
13/// Maximum file size to read (10MB)
14const MAX_FILE_SIZE: u64 = 10 * 1024 * 1024;
15
16/// Default number of lines to return
17const DEFAULT_MAX_LINES: usize = 2000;
18
19/// Tool for reading file contents
20pub struct ReadFileTool {
21    /// Maximum file size to read
22    max_file_size: u64,
23    /// Maximum lines to return by default
24    max_lines: usize,
25}
26
27impl ReadFileTool {
28    /// Create a new ReadFileTool with default settings
29    pub fn new() -> Self {
30        Self {
31            max_file_size: MAX_FILE_SIZE,
32            max_lines: DEFAULT_MAX_LINES,
33        }
34    }
35
36    /// Set the maximum file size
37    pub fn with_max_file_size(mut self, size: u64) -> Self {
38        self.max_file_size = size;
39        self
40    }
41
42    /// Set the maximum lines to return
43    pub fn with_max_lines(mut self, lines: usize) -> Self {
44        self.max_lines = lines;
45        self
46    }
47}
48
49impl Default for ReadFileTool {
50    fn default() -> Self {
51        Self::new()
52    }
53}
54
55/// Parameters for the read_file tool
56#[derive(Debug, Deserialize)]
57struct ReadFileParams {
58    /// Path to the file to read
59    path: String,
60    /// Line number to start from (1-indexed, optional)
61    #[serde(default)]
62    offset: Option<usize>,
63    /// Maximum number of lines to read (optional)
64    #[serde(default)]
65    limit: Option<usize>,
66}
67
68#[async_trait]
69impl Tool for ReadFileTool {
70    fn name(&self) -> &str {
71        "read_file"
72    }
73
74    fn description(&self) -> &str {
75        "Read the contents of a file. Returns the file content with line numbers. \
76         For large files, use offset and limit to read specific sections."
77    }
78
79    fn parameters_schema(&self) -> serde_json::Value {
80        serde_json::json!({
81            "type": "object",
82            "properties": {
83                "path": {
84                    "type": "string",
85                    "description": "The path to the file to read"
86                },
87                "offset": {
88                    "type": "integer",
89                    "description": "Line number to start from (1-indexed). Default: 1"
90                },
91                "limit": {
92                    "type": "integer",
93                    "description": "Maximum number of lines to read. Default: 2000"
94                }
95            },
96            "required": ["path"]
97        })
98    }
99
100    async fn execute(&self, params: serde_json::Value) -> ToolOutput {
101        // Parse parameters
102        let params: ReadFileParams = match serde_json::from_value(params) {
103            Ok(p) => p,
104            Err(e) => return ToolOutput::error(format!("Invalid parameters: {}", e)),
105        };
106
107        let path = Path::new(&params.path);
108        debug!(path = %path.display(), "Reading file");
109
110        // Check if file exists
111        if !path.exists() {
112            return ToolOutput::error(format!("File not found: {}", path.display()));
113        }
114
115        // Check if it's a file (not a directory)
116        if !path.is_file() {
117            return ToolOutput::error(format!("Not a file: {}", path.display()));
118        }
119
120        // Check file size
121        let metadata = match fs::metadata(path).await {
122            Ok(m) => m,
123            Err(e) => return ToolOutput::error(format!("Failed to read file metadata: {}", e)),
124        };
125
126        if metadata.len() > self.max_file_size {
127            return ToolOutput::error(format!(
128                "File too large: {} bytes (max: {} bytes). Use offset/limit to read sections.",
129                metadata.len(),
130                self.max_file_size
131            ));
132        }
133
134        // Read the file
135        let content = match fs::read_to_string(path).await {
136            Ok(c) => c,
137            Err(e) => {
138                // Try reading as binary if UTF-8 fails
139                if e.kind() == std::io::ErrorKind::InvalidData {
140                    return ToolOutput::error(
141                        "File appears to be binary and cannot be read as text",
142                    );
143                }
144                return ToolOutput::error(format!("Failed to read file: {}", e));
145            }
146        };
147
148        // Split into lines and apply offset/limit
149        let lines: Vec<&str> = content.lines().collect();
150        let total_lines = lines.len();
151
152        let offset = params.offset.unwrap_or(1).saturating_sub(1); // Convert to 0-indexed
153        let limit = params.limit.unwrap_or(self.max_lines);
154
155        // Slice the lines
156        let start = offset.min(lines.len());
157        let end = (start + limit).min(lines.len());
158        let selected_lines = &lines[start..end];
159
160        // Format with line numbers
161        let mut output = String::new();
162
163        // Add header if we're not showing the whole file
164        if start > 0 || end < total_lines {
165            output.push_str(&format!(
166                "Showing lines {}-{} of {} total\n\n",
167                start + 1,
168                end,
169                total_lines
170            ));
171        }
172
173        // Add lines with line numbers
174        for (i, line) in selected_lines.iter().enumerate() {
175            let line_num = start + i + 1;
176            output.push_str(&format!("{:>6}│{}\n", line_num, line));
177        }
178
179        // Add footer if there are more lines
180        if end < total_lines {
181            output.push_str(&format!(
182                "\n... {} more lines. Use offset={} to continue.",
183                total_lines - end,
184                end + 1
185            ));
186        }
187
188        ToolOutput::success(output)
189    }
190}
191
192// ============================================================================
193// Tests
194// ============================================================================
195
196#[cfg(test)]
197mod tests {
198    use super::*;
199    use std::io::Write;
200    use tempfile::NamedTempFile;
201
202    #[test]
203    fn test_read_file_tool_name() {
204        let tool = ReadFileTool::new();
205        assert_eq!(tool.name(), "read_file");
206    }
207
208    #[test]
209    fn test_read_file_schema() {
210        let tool = ReadFileTool::new();
211        let schema = tool.parameters_schema();
212        assert_eq!(schema["type"], "object");
213        assert!(schema["properties"]["path"].is_object());
214        assert_eq!(schema["required"][0], "path");
215    }
216
217    #[tokio::test]
218    async fn test_read_simple_file() {
219        let mut file = NamedTempFile::new().unwrap();
220        writeln!(file, "line 1").unwrap();
221        writeln!(file, "line 2").unwrap();
222        writeln!(file, "line 3").unwrap();
223
224        let tool = ReadFileTool::new();
225        let output = tool
226            .execute(serde_json::json!({
227                "path": file.path().to_str().unwrap()
228            }))
229            .await;
230
231        assert!(output.is_success());
232        assert!(output.content.contains("line 1"));
233        assert!(output.content.contains("line 2"));
234        assert!(output.content.contains("line 3"));
235    }
236
237    #[tokio::test]
238    async fn test_read_with_line_numbers() {
239        let mut file = NamedTempFile::new().unwrap();
240        writeln!(file, "first").unwrap();
241        writeln!(file, "second").unwrap();
242
243        let tool = ReadFileTool::new();
244        let output = tool
245            .execute(serde_json::json!({
246                "path": file.path().to_str().unwrap()
247            }))
248            .await;
249
250        assert!(output.is_success());
251        // Should have line numbers
252        assert!(output.content.contains("1│"));
253        assert!(output.content.contains("2│"));
254    }
255
256    #[tokio::test]
257    async fn test_read_with_offset() {
258        let mut file = NamedTempFile::new().unwrap();
259        for i in 1..=10 {
260            writeln!(file, "line {}", i).unwrap();
261        }
262
263        let tool = ReadFileTool::new();
264        let output = tool
265            .execute(serde_json::json!({
266                "path": file.path().to_str().unwrap(),
267                "offset": 5
268            }))
269            .await;
270
271        assert!(output.is_success());
272        assert!(output.content.contains("line 5"));
273        assert!(!output.content.contains("│line 4"));
274    }
275
276    #[tokio::test]
277    async fn test_read_with_limit() {
278        let mut file = NamedTempFile::new().unwrap();
279        for i in 1..=10 {
280            writeln!(file, "line {}", i).unwrap();
281        }
282
283        let tool = ReadFileTool::new();
284        let output = tool
285            .execute(serde_json::json!({
286                "path": file.path().to_str().unwrap(),
287                "limit": 3
288            }))
289            .await;
290
291        assert!(output.is_success());
292        assert!(output.content.contains("line 1"));
293        assert!(output.content.contains("line 2"));
294        assert!(output.content.contains("line 3"));
295        assert!(!output.content.contains("│line 4"));
296        assert!(output.content.contains("more lines"));
297    }
298
299    #[tokio::test]
300    async fn test_read_nonexistent_file() {
301        let tool = ReadFileTool::new();
302        let output = tool
303            .execute(serde_json::json!({
304                "path": "/nonexistent/file/path/12345.txt"
305            }))
306            .await;
307
308        assert!(output.is_error);
309        assert!(output.content.contains("not found"));
310    }
311
312    #[tokio::test]
313    async fn test_read_directory() {
314        let tool = ReadFileTool::new();
315        let output = tool
316            .execute(serde_json::json!({
317                "path": "/tmp"
318            }))
319            .await;
320
321        assert!(output.is_error);
322        assert!(output.content.contains("Not a file"));
323    }
324
325    #[tokio::test]
326    async fn test_read_invalid_params() {
327        let tool = ReadFileTool::new();
328        let output = tool.execute(serde_json::json!({})).await;
329
330        assert!(output.is_error);
331        assert!(output.content.contains("Invalid parameters"));
332    }
333
334    #[tokio::test]
335    async fn test_read_empty_file() {
336        let file = NamedTempFile::new().unwrap();
337
338        let tool = ReadFileTool::new();
339        let output = tool
340            .execute(serde_json::json!({
341                "path": file.path().to_str().unwrap()
342            }))
343            .await;
344
345        assert!(output.is_success());
346    }
347}