Skip to main content

trusty_code/tools/fs/
read.rs

1//! `read_file` tool — read file contents, optionally limited to a line range.
2//!
3//! Why: AI agents need to inspect existing files before editing them. A structured
4//! `ToolExecutor` with explicit size and line-range parameters is safer than
5//! passing raw `cat` arguments to a shell tool.
6//! What: `ReadFileTool` reads up to `MAX_FILE_BYTES` (1 MiB) from the path,
7//! optionally slicing to `[start_line, end_line]` (1-based, inclusive). All paths
8//! are scoped to the provided working directory; traversal attempts are rejected.
9//! Test: See `#[cfg(test)]` below — covers round-trip, line range, size cap,
10//! missing file, and path traversal.
11
12use std::path::PathBuf;
13
14use async_trait::async_trait;
15use serde_json::{Value, json};
16
17use crate::tools::fs::{FsError, scoped_path};
18use crate::tools::traits::{ToolExecutor, ToolResult};
19
20/// Maximum file size allowed by `ReadFileTool` (1 MiB).
21///
22/// Why: LLM context windows are finite; a 1 GiB file would freeze the loop.
23/// Rejecting early gives the agent a clear error rather than an OOM or timeout.
24/// What: Constant used both for the runtime guard and exposed via the schema
25/// description.
26/// Test: `read_returns_error_on_oversized_file`.
27pub const MAX_FILE_BYTES: u64 = 1024 * 1024; // 1 MiB
28
29/// `ToolExecutor` that reads the contents of a file.
30///
31/// Why: Provides agents with a safe, sandboxed way to read files inside the
32/// working directory. Construction requires an explicit `working_dir` so the
33/// scoping contract is compile-time visible.
34/// What: Implements `ToolExecutor` with `name = "read_file"`. Reads the whole
35/// file (up to `MAX_FILE_BYTES`) and optionally slices to a 1-based line range.
36/// Test: `cargo test -p trusty-code -- tools::fs::read`.
37pub struct ReadFileTool {
38    working_dir: PathBuf,
39    /// #7727: skill-refs root whose embedded files this tool serves.
40    skill_refs: Option<PathBuf>,
41}
42
43impl ReadFileTool {
44    /// Construct a new `ReadFileTool` scoped to `working_dir`.
45    ///
46    /// Why: The working directory is the security boundary; it must be set at
47    /// construction time so it cannot be changed per-call by the LLM.
48    /// What: Stores `working_dir` for use in every `execute` call.
49    /// Test: `read_round_trips_file`, et al.
50    pub fn new(working_dir: impl Into<PathBuf>) -> Self {
51        Self {
52            working_dir: working_dir.into(),
53            skill_refs: None,
54        }
55    }
56
57    /// Also serve the skill files an agent body points at beneath `dir` (#7727).
58    ///
59    /// Why: an in-process compose resolves `{{TM_SKILLS}}` to
60    /// `crate::agents::skill_refs::user_skill_refs_dir`, which lies outside the
61    /// working directory; without this the scope check refuses every pointer.
62    /// What: a request whose absolute path is exactly `dir/<entry>` for an
63    /// entry of `crate::agents::skill_refs::REFERENCED_SKILL_FILES` returns that
64    /// entry's embedded content — no disk read, so nothing else outside the
65    /// working directory becomes readable and nothing has to be written first.
66    /// Test: `skill_ref_pointer_is_served_outside_the_working_dir`,
67    /// `skill_refs_do_not_widen_the_scope`.
68    pub fn with_skill_refs(mut self, dir: impl Into<PathBuf>) -> Self {
69        self.skill_refs = Some(dir.into());
70        self
71    }
72
73    /// The embedded skill file `path` names, when it is one this tool serves.
74    fn skill_ref(&self, path: &std::path::Path) -> Option<&'static str> {
75        let dir = self.skill_refs.as_deref().filter(|d| d.is_absolute())?;
76        let relative = path.strip_prefix(dir).ok()?;
77        crate::agents::skill_refs::embedded_skill_ref(relative)
78    }
79
80    /// Read file contents with optional line-range slicing.
81    ///
82    /// Why: Centralises the IO path so `execute` stays clean.
83    /// What: Reads the file, enforces size cap, applies optional `[start, end]`
84    /// line range (1-based, inclusive), and returns the text.
85    /// Test: Exercised by all `ReadFileTool` unit tests.
86    fn read_inner(
87        &self,
88        path: &std::path::Path,
89        start_line: Option<usize>,
90        end_line: Option<usize>,
91    ) -> Result<String, FsError> {
92        let content = match self.skill_ref(path) {
93            Some(embedded) => embedded.to_string(),
94            None => self.read_scoped(path)?,
95        };
96
97        // Apply optional line range (1-based inclusive).
98        match (start_line, end_line) {
99            (None, None) => Ok(content),
100            (start, end) => {
101                let start_idx = start.unwrap_or(1).saturating_sub(1); // 0-based
102                let lines: Vec<&str> = content.lines().collect();
103                let end_idx = end.map(|e| e.min(lines.len())).unwrap_or(lines.len());
104                let slice = lines[start_idx.min(lines.len())..end_idx].join("\n");
105                Ok(slice)
106            }
107        }
108    }
109
110    /// Read `path` from disk inside the working directory, enforcing the size cap.
111    fn read_scoped(&self, path: &std::path::Path) -> Result<String, FsError> {
112        let scoped = scoped_path(&self.working_dir, path)?;
113
114        let meta = std::fs::metadata(&scoped).map_err(|e| {
115            if e.kind() == std::io::ErrorKind::NotFound {
116                FsError::NotFound(scoped.clone())
117            } else {
118                FsError::io(&scoped, e)
119            }
120        })?;
121
122        if meta.len() > MAX_FILE_BYTES {
123            return Err(FsError::FileTooLarge {
124                path: scoped,
125                bytes: meta.len(),
126                max: MAX_FILE_BYTES,
127            });
128        }
129
130        std::fs::read_to_string(&scoped).map_err(|e| FsError::io(&scoped, e))
131    }
132}
133
134#[async_trait]
135impl ToolExecutor for ReadFileTool {
136    fn name(&self) -> &str {
137        "read_file"
138    }
139
140    /// OpenAI function-call schema for `read_file`.
141    ///
142    /// Why: The LLM uses this schema to construct its tool call. Parameters
143    /// mirror the `execute` argument contract exactly.
144    /// What: JSON object with `path` (required), `start_line` and `end_line`
145    /// (optional, 1-based integers).
146    /// Test: `cargo test -p trusty-code -- tools::fs::read::tests::schema_has_required_path`.
147    fn schema(&self) -> Value {
148        json!({
149            "type": "function",
150            "function": {
151                "name": "read_file",
152                "description": "Read the contents of a file. Limited to 1 MiB. Optional start_line/end_line (1-based, inclusive) restrict the returned text.",
153                "parameters": {
154                    "type": "object",
155                    "properties": {
156                        "path": {
157                            "type": "string",
158                            "description": "Relative or absolute path to the file (must be inside the working directory)."
159                        },
160                        "start_line": {
161                            "type": "integer",
162                            "description": "First line to return (1-based, inclusive). Defaults to 1."
163                        },
164                        "end_line": {
165                            "type": "integer",
166                            "description": "Last line to return (1-based, inclusive). Defaults to end-of-file."
167                        }
168                    },
169                    "required": ["path"],
170                    "additionalProperties": false
171                }
172            }
173        })
174    }
175
176    /// Execute a `read_file` tool call.
177    ///
178    /// Why: Reads a file within the working directory, enforcing the size cap
179    /// and optional line range.
180    /// What: Parses `{path, start_line?, end_line?}` from `args`, calls
181    /// `read_inner`, and converts the result into a `ToolResult`.
182    /// Test: `read_round_trips_file`, `read_honors_line_range`, etc.
183    async fn execute(&self, args: Value) -> ToolResult {
184        let Some(path_str) = args.get("path").and_then(Value::as_str) else {
185            return ToolResult::err("read_file: missing required argument 'path'");
186        };
187
188        let start_line = args
189            .get("start_line")
190            .and_then(Value::as_u64)
191            .map(|n| n as usize);
192        let end_line = args
193            .get("end_line")
194            .and_then(Value::as_u64)
195            .map(|n| n as usize);
196
197        match self.read_inner(std::path::Path::new(path_str), start_line, end_line) {
198            Ok(content) => ToolResult::ok(content),
199            Err(e) => ToolResult::err(e.to_string()),
200        }
201    }
202}
203
204// ── Tests ─────────────────────────────────────────────────────────────────────
205
206#[cfg(test)]
207mod tests {
208    use std::fs;
209
210    use serde_json::json;
211
212    use super::*;
213    use crate::tools::traits::ToolExecutor;
214
215    fn make_tool(tmp: &tempfile::TempDir) -> ReadFileTool {
216        ReadFileTool::new(tmp.path())
217    }
218
219    /// `read_file` round-trips a file written to the working directory.
220    ///
221    /// Why: Basic contract — write then read must return the same bytes.
222    /// What: Writes `hello.txt`, calls `execute({path:"hello.txt"})`, asserts content.
223    /// Test: This test.
224    #[tokio::test]
225    async fn read_round_trips_file() {
226        let tmp = tempfile::tempdir().expect("tempdir");
227        fs::write(tmp.path().join("hello.txt"), "line one\nline two\n").expect("write");
228        let tool = make_tool(&tmp);
229        let result = tool.execute(json!({"path": "hello.txt"})).await;
230        assert!(!result.is_error(), "unexpected error: {}", result.content());
231        assert!(result.content().contains("line one"));
232        assert!(result.content().contains("line two"));
233    }
234
235    /// `read_file` with a line range returns only the requested lines.
236    ///
237    /// Why: Agents often need a specific section of a large file.
238    /// What: Writes a three-line file, reads only line 2, asserts only line 2 returned.
239    /// Test: This test.
240    #[tokio::test]
241    async fn read_honors_line_range() {
242        let tmp = tempfile::tempdir().expect("tempdir");
243        fs::write(tmp.path().join("multi.txt"), "a\nb\nc\n").expect("write");
244        let tool = make_tool(&tmp);
245        let result = tool
246            .execute(json!({"path": "multi.txt", "start_line": 2, "end_line": 2}))
247            .await;
248        assert!(!result.is_error());
249        assert_eq!(result.content(), "b");
250    }
251
252    /// `read_file` returns an error for a file exceeding the size cap.
253    ///
254    /// Why: The size cap must be enforced to protect the LLM loop.
255    /// What: Creates a file larger than `MAX_FILE_BYTES`, expects an error
256    /// containing "too large".
257    /// Test: This test.
258    #[tokio::test]
259    async fn read_returns_error_on_oversized_file() {
260        let tmp = tempfile::tempdir().expect("tempdir");
261        let big = vec![b'x'; (MAX_FILE_BYTES + 1) as usize];
262        fs::write(tmp.path().join("big.bin"), &big).expect("write");
263        let tool = make_tool(&tmp);
264        let result = tool.execute(json!({"path": "big.bin"})).await;
265        assert!(result.is_error());
266        assert!(
267            result.content().contains("too large"),
268            "unexpected message: {}",
269            result.content()
270        );
271    }
272
273    /// `read_file` returns an error for a missing file.
274    ///
275    /// Why: Missing-file errors must be surfaced as `ToolResult::Error`, not panic.
276    /// What: `execute({path:"does_not_exist.txt"})` on a non-existent file.
277    /// Test: This test.
278    #[tokio::test]
279    async fn read_returns_error_on_missing_file() {
280        let tmp = tempfile::tempdir().expect("tempdir");
281        let tool = make_tool(&tmp);
282        let result = tool.execute(json!({"path": "does_not_exist.txt"})).await;
283        assert!(result.is_error());
284        assert!(
285            result.content().contains("not found"),
286            "unexpected message: {}",
287            result.content()
288        );
289    }
290
291    /// `read_file` rejects a path that escapes the working directory.
292    ///
293    /// Why: Path traversal must be blocked regardless of the LLM's arguments.
294    /// What: `execute({path:"../../etc/passwd"})` must return `ToolResult::Error`.
295    /// Test: This test.
296    #[tokio::test]
297    async fn path_traversal_is_rejected() {
298        let tmp = tempfile::tempdir().expect("tempdir");
299        let tool = make_tool(&tmp);
300        let result = tool.execute(json!({"path": "../../etc/passwd"})).await;
301        assert!(result.is_error());
302        assert!(
303            result.content().contains("escapes"),
304            "unexpected message: {}",
305            result.content()
306        );
307    }
308
309    /// The schema has `path` in its required list.
310    ///
311    /// Why: The LLM uses the schema to construct calls; a missing `required`
312    /// entry would cause the LLM to omit `path` and the call to fail.
313    /// What: Parses `schema()` and checks `parameters.required` contains "path".
314    /// Test: This test.
315    #[test]
316    fn schema_has_required_path() {
317        let tmp = tempfile::tempdir().expect("tempdir");
318        let tool = make_tool(&tmp);
319        let schema = tool.schema();
320        let required = schema["function"]["parameters"]["required"]
321            .as_array()
322            .expect("required array");
323        assert!(
324            required.iter().any(|v| v.as_str() == Some("path")),
325            "schema must list 'path' as required"
326        );
327    }
328
329    /// #7727: a skill-refs pointer outside the working directory is served,
330    /// line ranges included, with nothing on disk.
331    #[tokio::test]
332    async fn skill_ref_pointer_is_served_outside_the_working_dir() {
333        use crate::agents::skill_refs::REFERENCED_SKILL_FILES;
334
335        let tmp = tempfile::tempdir().expect("tempdir");
336        let refs = tempfile::tempdir().expect("refs");
337        let tool = make_tool(&tmp).with_skill_refs(refs.path());
338        let (relative, content) = REFERENCED_SKILL_FILES[0];
339        let path = refs.path().join(relative).display().to_string();
340        let result = tool.execute(json!({ "path": path })).await;
341        assert!(!result.is_error(), "unexpected error: {}", result.content());
342        assert_eq!(result.content(), content);
343        let first = tool
344            .execute(json!({ "path": path, "start_line": 1, "end_line": 1 }))
345            .await;
346        assert_eq!(first.content(), content.lines().next().expect("line"));
347    }
348
349    /// #7727: serving skill refs admits only the embedded entries — any other
350    /// path beneath or above the refs root is still refused.
351    #[tokio::test]
352    async fn skill_refs_do_not_widen_the_scope() {
353        let tmp = tempfile::tempdir().expect("tempdir");
354        let refs = tempfile::tempdir().expect("refs");
355        fs::write(refs.path().join("secret.txt"), "no").expect("write");
356        let tool = make_tool(&tmp).with_skill_refs(refs.path());
357        for path in [
358            refs.path().join("secret.txt"),
359            refs.path().join("x/../secret.txt"),
360            refs.path().join("self-improvement-loop/../../etc/passwd"),
361        ] {
362            let result = tool.execute(json!({ "path": path })).await;
363            assert!(result.is_error(), "{} must be refused", path.display());
364        }
365    }
366}