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}
40
41impl ReadFileTool {
42    /// Construct a new `ReadFileTool` scoped to `working_dir`.
43    ///
44    /// Why: The working directory is the security boundary; it must be set at
45    /// construction time so it cannot be changed per-call by the LLM.
46    /// What: Stores `working_dir` for use in every `execute` call.
47    /// Test: `read_round_trips_file`, et al.
48    pub fn new(working_dir: impl Into<PathBuf>) -> Self {
49        Self {
50            working_dir: working_dir.into(),
51        }
52    }
53
54    /// Read file contents with optional line-range slicing.
55    ///
56    /// Why: Centralises the IO path so `execute` stays clean.
57    /// What: Reads the file, enforces size cap, applies optional `[start, end]`
58    /// line range (1-based, inclusive), and returns the text.
59    /// Test: Exercised by all `ReadFileTool` unit tests.
60    fn read_inner(
61        &self,
62        path: &std::path::Path,
63        start_line: Option<usize>,
64        end_line: Option<usize>,
65    ) -> Result<String, FsError> {
66        let scoped = scoped_path(&self.working_dir, path)?;
67
68        let meta = std::fs::metadata(&scoped).map_err(|e| {
69            if e.kind() == std::io::ErrorKind::NotFound {
70                FsError::NotFound(scoped.clone())
71            } else {
72                FsError::io(&scoped, e)
73            }
74        })?;
75
76        if meta.len() > MAX_FILE_BYTES {
77            return Err(FsError::FileTooLarge {
78                path: scoped,
79                bytes: meta.len(),
80                max: MAX_FILE_BYTES,
81            });
82        }
83
84        let content = std::fs::read_to_string(&scoped).map_err(|e| FsError::io(&scoped, e))?;
85
86        // Apply optional line range (1-based inclusive).
87        match (start_line, end_line) {
88            (None, None) => Ok(content),
89            (start, end) => {
90                let start_idx = start.unwrap_or(1).saturating_sub(1); // 0-based
91                let lines: Vec<&str> = content.lines().collect();
92                let end_idx = end.map(|e| e.min(lines.len())).unwrap_or(lines.len());
93                let slice = lines[start_idx.min(lines.len())..end_idx].join("\n");
94                Ok(slice)
95            }
96        }
97    }
98}
99
100#[async_trait]
101impl ToolExecutor for ReadFileTool {
102    fn name(&self) -> &str {
103        "read_file"
104    }
105
106    /// OpenAI function-call schema for `read_file`.
107    ///
108    /// Why: The LLM uses this schema to construct its tool call. Parameters
109    /// mirror the `execute` argument contract exactly.
110    /// What: JSON object with `path` (required), `start_line` and `end_line`
111    /// (optional, 1-based integers).
112    /// Test: `cargo test -p trusty-code -- tools::fs::read::tests::schema_has_required_path`.
113    fn schema(&self) -> Value {
114        json!({
115            "type": "function",
116            "function": {
117                "name": "read_file",
118                "description": "Read the contents of a file. Limited to 1 MiB. Optional start_line/end_line (1-based, inclusive) restrict the returned text.",
119                "parameters": {
120                    "type": "object",
121                    "properties": {
122                        "path": {
123                            "type": "string",
124                            "description": "Relative or absolute path to the file (must be inside the working directory)."
125                        },
126                        "start_line": {
127                            "type": "integer",
128                            "description": "First line to return (1-based, inclusive). Defaults to 1."
129                        },
130                        "end_line": {
131                            "type": "integer",
132                            "description": "Last line to return (1-based, inclusive). Defaults to end-of-file."
133                        }
134                    },
135                    "required": ["path"],
136                    "additionalProperties": false
137                }
138            }
139        })
140    }
141
142    /// Execute a `read_file` tool call.
143    ///
144    /// Why: Reads a file within the working directory, enforcing the size cap
145    /// and optional line range.
146    /// What: Parses `{path, start_line?, end_line?}` from `args`, calls
147    /// `read_inner`, and converts the result into a `ToolResult`.
148    /// Test: `read_round_trips_file`, `read_honors_line_range`, etc.
149    async fn execute(&self, args: Value) -> ToolResult {
150        let Some(path_str) = args.get("path").and_then(Value::as_str) else {
151            return ToolResult::err("read_file: missing required argument 'path'");
152        };
153
154        let start_line = args
155            .get("start_line")
156            .and_then(Value::as_u64)
157            .map(|n| n as usize);
158        let end_line = args
159            .get("end_line")
160            .and_then(Value::as_u64)
161            .map(|n| n as usize);
162
163        match self.read_inner(std::path::Path::new(path_str), start_line, end_line) {
164            Ok(content) => ToolResult::ok(content),
165            Err(e) => ToolResult::err(e.to_string()),
166        }
167    }
168}
169
170// ── Tests ─────────────────────────────────────────────────────────────────────
171
172#[cfg(test)]
173mod tests {
174    use std::fs;
175
176    use serde_json::json;
177
178    use super::*;
179    use crate::tools::traits::ToolExecutor;
180
181    fn make_tool(tmp: &tempfile::TempDir) -> ReadFileTool {
182        ReadFileTool::new(tmp.path())
183    }
184
185    /// `read_file` round-trips a file written to the working directory.
186    ///
187    /// Why: Basic contract — write then read must return the same bytes.
188    /// What: Writes `hello.txt`, calls `execute({path:"hello.txt"})`, asserts content.
189    /// Test: This test.
190    #[tokio::test]
191    async fn read_round_trips_file() {
192        let tmp = tempfile::tempdir().expect("tempdir");
193        fs::write(tmp.path().join("hello.txt"), "line one\nline two\n").expect("write");
194        let tool = make_tool(&tmp);
195        let result = tool.execute(json!({"path": "hello.txt"})).await;
196        assert!(!result.is_error(), "unexpected error: {}", result.content());
197        assert!(result.content().contains("line one"));
198        assert!(result.content().contains("line two"));
199    }
200
201    /// `read_file` with a line range returns only the requested lines.
202    ///
203    /// Why: Agents often need a specific section of a large file.
204    /// What: Writes a three-line file, reads only line 2, asserts only line 2 returned.
205    /// Test: This test.
206    #[tokio::test]
207    async fn read_honors_line_range() {
208        let tmp = tempfile::tempdir().expect("tempdir");
209        fs::write(tmp.path().join("multi.txt"), "a\nb\nc\n").expect("write");
210        let tool = make_tool(&tmp);
211        let result = tool
212            .execute(json!({"path": "multi.txt", "start_line": 2, "end_line": 2}))
213            .await;
214        assert!(!result.is_error());
215        assert_eq!(result.content(), "b");
216    }
217
218    /// `read_file` returns an error for a file exceeding the size cap.
219    ///
220    /// Why: The size cap must be enforced to protect the LLM loop.
221    /// What: Creates a file larger than `MAX_FILE_BYTES`, expects an error
222    /// containing "too large".
223    /// Test: This test.
224    #[tokio::test]
225    async fn read_returns_error_on_oversized_file() {
226        let tmp = tempfile::tempdir().expect("tempdir");
227        let big = vec![b'x'; (MAX_FILE_BYTES + 1) as usize];
228        fs::write(tmp.path().join("big.bin"), &big).expect("write");
229        let tool = make_tool(&tmp);
230        let result = tool.execute(json!({"path": "big.bin"})).await;
231        assert!(result.is_error());
232        assert!(
233            result.content().contains("too large"),
234            "unexpected message: {}",
235            result.content()
236        );
237    }
238
239    /// `read_file` returns an error for a missing file.
240    ///
241    /// Why: Missing-file errors must be surfaced as `ToolResult::Error`, not panic.
242    /// What: `execute({path:"does_not_exist.txt"})` on a non-existent file.
243    /// Test: This test.
244    #[tokio::test]
245    async fn read_returns_error_on_missing_file() {
246        let tmp = tempfile::tempdir().expect("tempdir");
247        let tool = make_tool(&tmp);
248        let result = tool.execute(json!({"path": "does_not_exist.txt"})).await;
249        assert!(result.is_error());
250        assert!(
251            result.content().contains("not found"),
252            "unexpected message: {}",
253            result.content()
254        );
255    }
256
257    /// `read_file` rejects a path that escapes the working directory.
258    ///
259    /// Why: Path traversal must be blocked regardless of the LLM's arguments.
260    /// What: `execute({path:"../../etc/passwd"})` must return `ToolResult::Error`.
261    /// Test: This test.
262    #[tokio::test]
263    async fn path_traversal_is_rejected() {
264        let tmp = tempfile::tempdir().expect("tempdir");
265        let tool = make_tool(&tmp);
266        let result = tool.execute(json!({"path": "../../etc/passwd"})).await;
267        assert!(result.is_error());
268        assert!(
269            result.content().contains("escapes"),
270            "unexpected message: {}",
271            result.content()
272        );
273    }
274
275    /// The schema has `path` in its required list.
276    ///
277    /// Why: The LLM uses the schema to construct calls; a missing `required`
278    /// entry would cause the LLM to omit `path` and the call to fail.
279    /// What: Parses `schema()` and checks `parameters.required` contains "path".
280    /// Test: This test.
281    #[test]
282    fn schema_has_required_path() {
283        let tmp = tempfile::tempdir().expect("tempdir");
284        let tool = make_tool(&tmp);
285        let schema = tool.schema();
286        let required = schema["function"]["parameters"]["required"]
287            .as_array()
288            .expect("required array");
289        assert!(
290            required.iter().any(|v| v.as_str() == Some("path")),
291            "schema must list 'path' as required"
292        );
293    }
294}