Skip to main content

microclaw_engine/tools/
read_file.rs

1use async_trait::async_trait;
2use serde_json::json;
3use std::path::PathBuf;
4use tracing::info;
5
6use crate::config::WorkingDirIsolation;
7use microclaw_core::llm_types::ToolDefinition;
8
9use super::{schema_object, Tool, ToolResult};
10
11pub struct ReadFileTool {
12    working_dir: PathBuf,
13    working_dir_isolation: WorkingDirIsolation,
14    file_state: std::sync::Arc<super::file_state::FileStateTable>,
15}
16
17impl ReadFileTool {
18    pub fn new(working_dir: &str) -> Self {
19        Self::new_with_isolation(working_dir, WorkingDirIsolation::Shared)
20    }
21
22    pub fn new_with_isolation(
23        working_dir: &str,
24        working_dir_isolation: WorkingDirIsolation,
25    ) -> Self {
26        Self {
27            working_dir: PathBuf::from(working_dir),
28            working_dir_isolation,
29            file_state: Default::default(),
30        }
31    }
32
33    /// Share the stale-read table with the other file tools of a registry.
34    pub fn with_file_state(
35        mut self,
36        file_state: std::sync::Arc<super::file_state::FileStateTable>,
37    ) -> Self {
38        self.file_state = file_state;
39        self
40    }
41}
42
43#[async_trait]
44impl Tool for ReadFileTool {
45    fn name(&self) -> &str {
46        "read_file"
47    }
48
49    fn definition(&self) -> ToolDefinition {
50        ToolDefinition {
51            name: "read_file".into(),
52            description: "Read the contents of a file at the given path. Returns the file content with line numbers. Prefer paths relative to the current chat working directory; do not invent machine-specific absolute paths unless the user or a tool already provided them.".into(),
53            input_schema: schema_object(
54                json!({
55                    "path": {
56                        "type": "string",
57                        "description": "The file path to read, usually relative to the current chat working directory"
58                    },
59                    "offset": {
60                        "type": "integer",
61                        "description": "Line number to start reading from (1-based)"
62                    },
63                    "limit": {
64                        "type": "integer",
65                        "description": "Maximum number of lines to read"
66                    }
67                }),
68                &["path"],
69            ),
70        }
71    }
72
73    async fn execute(&self, input: serde_json::Value) -> ToolResult {
74        let path = match input.get("path").and_then(|v| v.as_str()) {
75            Some(p) => p,
76            None => return ToolResult::error("Missing 'path' parameter".into()),
77        };
78        let working_dir =
79            super::resolve_tool_working_dir(&self.working_dir, self.working_dir_isolation, &input);
80        let resolved_path = super::resolve_tool_path(&working_dir, path);
81        let resolved_path_str = resolved_path.to_string_lossy().to_string();
82
83        if let Err(msg) = crate::internal::tool_runtime::path_guard::check_path(&resolved_path_str)
84        {
85            return ToolResult::error(msg);
86        }
87
88        info!("Reading file: {}", resolved_path.display());
89
90        let content = match tokio::fs::read_to_string(&resolved_path).await {
91            Ok(c) => c,
92            Err(e) => return ToolResult::error(format!("Failed to read file: {e}")),
93        };
94        self.file_state.record(&resolved_path, content.as_bytes());
95
96        let lines: Vec<&str> = content.lines().collect();
97        let offset = input
98            .get("offset")
99            .and_then(|v| v.as_u64())
100            .map(|o| (o as usize).saturating_sub(1))
101            .unwrap_or(0)
102            .min(lines.len());
103        let limit = input
104            .get("limit")
105            .and_then(|v| v.as_u64())
106            .map(|l| l as usize)
107            .unwrap_or(2000);
108
109        let end = offset.saturating_add(limit).min(lines.len());
110        let selected: Vec<String> = lines[offset..end]
111            .iter()
112            .enumerate()
113            .map(|(i, line)| format!("{:>6}\t{}", offset + i + 1, line))
114            .collect();
115
116        ToolResult::success(selected.join("\n"))
117    }
118}
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123    use serde_json::json;
124
125    #[test]
126    fn test_read_file_definition_prefers_relative_paths() {
127        let tool = ReadFileTool::new(".");
128        let def = tool.definition();
129        assert!(def
130            .description
131            .contains("Prefer paths relative to the current chat working directory"));
132        assert_eq!(
133            def.input_schema["properties"]["path"]["description"].as_str(),
134            Some("The file path to read, usually relative to the current chat working directory")
135        );
136    }
137
138    #[tokio::test]
139    async fn test_read_file_success() {
140        let dir = std::env::temp_dir().join(format!("microclaw_rf_{}", uuid::Uuid::new_v4()));
141        std::fs::create_dir_all(&dir).unwrap();
142        let file = dir.join("test.txt");
143        std::fs::write(&file, "line1\nline2\nline3\nline4\nline5").unwrap();
144
145        let tool = ReadFileTool::new(".");
146        let result = tool.execute(json!({"path": file.to_str().unwrap()})).await;
147        assert!(!result.is_error);
148        assert!(result.content.contains("line1"));
149        assert!(result.content.contains("line5"));
150        // Should have line numbers
151        assert!(result.content.contains("1\t"));
152
153        let _ = std::fs::remove_dir_all(&dir);
154    }
155
156    #[tokio::test]
157    async fn test_read_file_with_offset_and_limit() {
158        let dir = std::env::temp_dir().join(format!("microclaw_rf2_{}", uuid::Uuid::new_v4()));
159        std::fs::create_dir_all(&dir).unwrap();
160        let file = dir.join("test.txt");
161        std::fs::write(&file, "a\nb\nc\nd\ne").unwrap();
162
163        let tool = ReadFileTool::new(".");
164        // offset=2 (1-based, becomes index 1), limit=2 -> lines 2 and 3
165        let result = tool
166            .execute(json!({"path": file.to_str().unwrap(), "offset": 2, "limit": 2}))
167            .await;
168        assert!(!result.is_error);
169        assert!(result.content.contains("b"));
170        assert!(result.content.contains("c"));
171        assert!(!result.content.contains("\ta\n") && !result.content.contains("\td"));
172
173        let _ = std::fs::remove_dir_all(&dir);
174    }
175
176    #[tokio::test]
177    async fn test_read_file_offset_past_end_returns_empty() {
178        // Regression: when offset exceeds the file's line count, slicing
179        // lines[offset..end] used to panic with "range start index N out of
180        // range for slice of length M" because offset wasn't clamped.
181        let dir =
182            std::env::temp_dir().join(format!("microclaw_rf_offset_past_{}", uuid::Uuid::new_v4()));
183        std::fs::create_dir_all(&dir).unwrap();
184        let file = dir.join("short.txt");
185        std::fs::write(&file, "a\nb\nc").unwrap();
186
187        let tool = ReadFileTool::new(".");
188        let result = tool
189            .execute(json!({"path": file.to_str().unwrap(), "offset": 369, "limit": 100}))
190            .await;
191        assert!(!result.is_error, "expected ok, got: {}", result.content);
192        assert!(result.content.is_empty());
193
194        let _ = std::fs::remove_dir_all(&dir);
195    }
196
197    #[tokio::test]
198    async fn test_read_file_not_found() {
199        let tool = ReadFileTool::new(".");
200        let result = tool.execute(json!({"path": "/nonexistent/file.txt"})).await;
201        assert!(result.is_error);
202        assert!(result.content.contains("Failed to read file"));
203    }
204
205    #[tokio::test]
206    async fn test_read_file_missing_path() {
207        let tool = ReadFileTool::new(".");
208        let result = tool.execute(json!({})).await;
209        assert!(result.is_error);
210        assert!(result.content.contains("Missing 'path'"));
211    }
212
213    #[tokio::test]
214    async fn test_read_file_resolves_relative_to_working_dir() {
215        let root = std::env::temp_dir().join(format!("microclaw_rf3_{}", uuid::Uuid::new_v4()));
216        let work = root.join("workspace");
217        let shared = work.join("shared");
218        std::fs::create_dir_all(&shared).unwrap();
219        std::fs::write(shared.join("test.txt"), "inside").unwrap();
220
221        let tool = ReadFileTool::new(work.to_str().unwrap());
222        let result = tool.execute(json!({"path": "test.txt"})).await;
223        assert!(!result.is_error);
224        assert!(result.content.contains("inside"));
225
226        let _ = std::fs::remove_dir_all(&root);
227    }
228}