Skip to main content

pixie_pi/tools/
read.rs

1//! `read` tool — read file contents (text or image).
2
3use std::path::PathBuf;
4
5use async_trait::async_trait;
6use serde::Deserialize;
7use serde_json::{json, Value};
8use tokio_util::sync::CancellationToken;
9
10use crate::ai::types::{ToolResultContent};
11use crate::agent::tool::{AgentTool, ToolResult};
12use crate::tools::truncate::{format_size, truncate_head, DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES};
13use crate::tools::util::{display_path, resolve_read_path};
14
15pub struct ReadTool {
16    pub cwd: PathBuf,
17}
18
19#[derive(Debug, Deserialize)]
20struct ReadInput {
21    #[serde(default)]
22    path: Option<String>,
23    #[serde(default, alias = "file_path")]
24    file_path: Option<String>,
25    #[serde(default)]
26    offset: Option<usize>,
27    #[serde(default)]
28    limit: Option<usize>,
29}
30
31fn detect_image_mime(path: &str) -> Option<&'static str> {
32    let lower = path.to_ascii_lowercase();
33    if lower.ends_with(".jpg") || lower.ends_with(".jpeg") {
34        Some("image/jpeg")
35    } else if lower.ends_with(".png") {
36        Some("image/png")
37    } else if lower.ends_with(".gif") {
38        Some("image/gif")
39    } else if lower.ends_with(".webp") {
40        Some("image/webp")
41    } else {
42        None
43    }
44}
45
46#[async_trait]
47impl AgentTool for ReadTool {
48    fn name(&self) -> &str {
49        "read"
50    }
51    fn description(&self) -> &str {
52        "Read the contents of a file. Supports text files and images (jpg, png, gif, webp); images are sent as attachments. For text files, output is truncated to 2000 lines or 50KB (whichever is hit first). Use offset/limit for large files; continue with offset until complete."
53    }
54    fn input_schema(&self) -> Value {
55        json!({
56            "type": "object",
57            "properties": {
58                "path": { "type": "string", "description": "Path to the file to read (relative or absolute)" },
59                "offset": { "type": "number", "description": "Line number to start reading from (1-indexed)" },
60                "limit": { "type": "number", "description": "Maximum number of lines to read" }
61            },
62            "required": ["path"]
63        })
64    }
65
66    async fn execute(&self, args: Value, cancel: CancellationToken) -> anyhow::Result<ToolResult> {
67        let input: ReadInput = serde_json::from_value(args)?;
68        let path_str = input.path.or(input.file_path).ok_or_else(|| {
69            anyhow::anyhow!("read requires a 'path' parameter")
70        })?;
71        if cancel.is_cancelled() {
72            anyhow::bail!("Operation aborted");
73        }
74        let abs = resolve_read_path(&path_str, &self.cwd);
75        let display = display_path(&path_str, &self.cwd);
76
77        // Existence + readability.
78        if !abs.exists() {
79            anyhow::bail!("File not found: {display}");
80        }
81        if abs.is_dir() {
82            anyhow::bail!("Path is a directory, not a file: {display}");
83        }
84
85        // Image branch.
86        if let Some(mime) = detect_image_mime(&path_str) {
87            let bytes = tokio::fs::read(&abs).await?;
88            let b64 = base64_encode(&bytes);
89            let note = format!("Read image file [{mime}]");
90            return Ok(ToolResult {
91                content: vec![
92                    ToolResultContent::Text { text: note },
93                    ToolResultContent::Image {
94                        data: b64,
95                        mime_type: mime.into(),
96                    },
97                ],
98                details: Value::Null,
99                terminate: false,
100            });
101        }
102
103        let raw = tokio::fs::read_to_string(&abs).await?;
104        // `split('\n')` yields a trailing empty element when the file ends with a
105        // newline (i.e. virtually every source file). Drop it so a 3-line file
106        // counts as 3 lines, not 4: offset validation is then exact, partial
107        // reads report the true remaining-line count, and the tail doesn't carry
108        // a phantom blank line. Mirrors the same fix in `generate_diff`.
109        let mut all_lines: Vec<&str> = raw.split('\n').collect();
110        if raw.ends_with('\n') {
111            all_lines.pop();
112        }
113        let total_file_lines = all_lines.len();
114
115        let start_line = input.offset.map(|o| o.saturating_sub(1)).unwrap_or(0);
116        if start_line >= total_file_lines {
117            anyhow::bail!(
118                "Offset {} is beyond end of file ({} lines total)",
119                input.offset.unwrap_or(0),
120                total_file_lines
121            );
122        }
123
124        let selected: String;
125        let user_limited: Option<usize>;
126        if let Some(raw_limit) = input.limit {
127            // Clamp to >= 1 (see find.rs / ls.rs / grep.rs): a degenerate
128            // `limit: 0` would otherwise read nothing and emit a continuation
129            // hint that points back at the same offset (`Use offset=X` where X
130            // is the line we just asked for) — a no-op the model can loop on.
131            let limit = raw_limit.max(1);
132            let end = (start_line + limit).min(total_file_lines);
133            selected = all_lines[start_line..end].join("\n");
134            user_limited = Some(end - start_line);
135        } else {
136            selected = all_lines[start_line..].join("\n");
137            user_limited = None;
138        }
139
140        let trunc = truncate_head(&selected, None, None);
141        let start_display = start_line + 1;
142
143        let output_text = if trunc.first_line_exceeds_limit {
144            format!(
145                "[Line {start_display} exceeds {} limit. Use bash: sed -n '{start_display}p' {display} | head -c {}]",
146                format_size(DEFAULT_MAX_BYTES),
147                DEFAULT_MAX_BYTES
148            )
149        } else if trunc.truncated {
150            let end_display = start_display + trunc.output_lines - 1;
151            let next = end_display + 1;
152            let suffix = match trunc.truncated_by.as_deref() {
153                Some("lines") => format!(
154                    "\n\n[Showing lines {start_display}-{end_display} of {total_file_lines}. Use offset={next} to continue.]"
155                ),
156                _ => format!(
157                    "\n\n[Showing lines {start_display}-{end_display} of {total_file_lines} ({} limit). Use offset={next} to continue.]",
158                    format_size(DEFAULT_MAX_BYTES)
159                ),
160            };
161            format!("{}{suffix}", trunc.content)
162        } else if let Some(n) = user_limited {
163            if start_line + n < total_file_lines {
164                let remaining = total_file_lines - (start_line + n);
165                let next = start_line + n + 1;
166                format!(
167                    "{}\n\n[{remaining} more lines in file. Use offset={next} to continue.]",
168                    trunc.content
169                )
170            } else {
171                trunc.content
172            }
173        } else {
174            trunc.content
175        };
176
177        let _ = DEFAULT_MAX_LINES; // referenced in the description above
178        Ok(ToolResult::text(output_text))
179    }
180}
181
182/// Minimal base64 encoder (avoids pulling a base64 dependency).
183fn base64_encode(input: &[u8]) -> String {
184    const TABLE: &[u8; 64] =
185        b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
186    let mut out = String::with_capacity(input.len().div_ceil(3) * 4);
187    let mut chunks = input.chunks_exact(3);
188    for chunk in chunks.by_ref() {
189        let n = ((chunk[0] as u32) << 16) | ((chunk[1] as u32) << 8) | chunk[2] as u32;
190        out.push(TABLE[((n >> 18) & 63) as usize] as char);
191        out.push(TABLE[((n >> 12) & 63) as usize] as char);
192        out.push(TABLE[((n >> 6) & 63) as usize] as char);
193        out.push(TABLE[(n & 63) as usize] as char);
194    }
195    let rem = chunks.remainder();
196    match rem.len() {
197        1 => {
198            let n = (rem[0] as u32) << 16;
199            out.push(TABLE[((n >> 18) & 63) as usize] as char);
200            out.push(TABLE[((n >> 12) & 63) as usize] as char);
201            out.push('=');
202            out.push('=');
203        }
204        2 => {
205            let n = ((rem[0] as u32) << 16) | ((rem[1] as u32) << 8);
206            out.push(TABLE[((n >> 18) & 63) as usize] as char);
207            out.push(TABLE[((n >> 12) & 63) as usize] as char);
208            out.push(TABLE[((n >> 6) & 63) as usize] as char);
209            out.push('=');
210        }
211        _ => {}
212    }
213    out
214}
215
216#[cfg(test)]
217mod tests {
218    use super::*;
219    use crate::agent::tool::AgentTool;
220    use tokio_util::sync::CancellationToken;
221
222    fn scratch_file(body: &str) -> PathBuf {
223        let path = std::env::temp_dir().join(format!("pi-read-test-{}.txt", uuid::Uuid::new_v4()));
224        std::fs::write(&path, body).unwrap();
225        path
226    }
227
228    /// Run the read tool; returns `Ok(text)` on success or `Err(message)` on bail.
229    async fn run_read(cwd: PathBuf, args: serde_json::Value) -> Result<String, String> {
230        let tool = ReadTool { cwd };
231        match tool.execute(args, CancellationToken::new()).await {
232            Ok(res) => match res.content.into_iter().next() {
233                Some(crate::ai::types::ToolResultContent::Text { text }) => Ok(text),
234                _ => panic!("expected text tool result"),
235            },
236            Err(e) => Err(e.to_string()),
237        }
238    }
239
240    #[tokio::test]
241    async fn trailing_newline_does_not_inflate_line_count() {
242        // A 3-line file with the usual trailing newline. With `limit: 2` the
243        // remaining count must be 1 — the trailing newline must not be counted
244        // as a phantom 4th line (previously reported "2 more lines").
245        let path = scratch_file("l1\nl2\nl3\n");
246        let cwd = std::env::temp_dir().to_path_buf();
247        let out = run_read(
248            cwd,
249            serde_json::json!({ "path": path.to_string_lossy(), "limit": 2 }),
250        )
251        .await
252        .unwrap();
253        assert!(
254            out.contains("[1 more lines in file. Use offset=3 to continue.]"),
255            "expected exact remaining-count message, got:\n{out}"
256        );
257        let _ = std::fs::remove_file(&path);
258    }
259
260    #[tokio::test]
261    async fn offset_beyond_end_uses_exact_line_count() {
262        // Requesting offset 4 on a 3-line file must bail with "3 lines total",
263        // not silently return a phantom line. (Previously offset 4 returned the
264        // trailing-empty element and only offset 5 errored, as "4 lines total".)
265        let path = scratch_file("l1\nl2\nl3\n");
266        let cwd = std::env::temp_dir().to_path_buf();
267        let err = run_read(
268            cwd,
269            serde_json::json!({ "path": path.to_string_lossy(), "offset": 4 }),
270        )
271        .await
272        .unwrap_err();
273        assert!(
274            err.contains("3 lines total"),
275            "expected '3 lines total' in error, got: {err}"
276        );
277        let _ = std::fs::remove_file(&path);
278    }
279
280    #[tokio::test]
281    async fn limit_zero_is_clamped_to_one_not_an_empty_no_op() {
282        // A degenerate `limit: 0` is clamped to 1 (see find.rs / ls.rs / grep.rs):
283        // the first line is returned and the continuation hint advances to
284        // offset 2, instead of an empty read whose hint points back at offset 1
285        // (which the model could loop on forever).
286        let path = scratch_file("l1\nl2\nl3\n");
287        let cwd = std::env::temp_dir().to_path_buf();
288        let out = run_read(
289            cwd,
290            serde_json::json!({ "path": path.to_string_lossy(), "limit": 0 }),
291        )
292        .await
293        .unwrap();
294        assert!(
295            out.contains("l1"),
296            "limit:0 must still return the first line, got: {out}"
297        );
298        assert!(
299            !out.starts_with('\n'),
300            "limit:0 must not return an empty/leading-blank read: {out:?}"
301        );
302        assert!(
303            out.contains("Use offset=2"),
304            "continuation hint must advance to offset 2, not point back at offset 1: {out}"
305        );
306        let _ = std::fs::remove_file(&path);
307    }
308
309    #[tokio::test]
310    async fn full_read_of_trailing_newline_file_has_no_phantom_blank_line() {
311        // Reading the whole file must not surface a phantom trailing blank line.
312        let path = scratch_file("a\nb\nc\n");
313        let cwd = std::env::temp_dir().to_path_buf();
314        let out = run_read(cwd, serde_json::json!({ "path": path.to_string_lossy() }))
315            .await
316            .unwrap();
317        assert!(!out.ends_with('\n'), "no trailing newline/blank line: {out:?}");
318        assert_eq!(out, "a\nb\nc");
319        let _ = std::fs::remove_file(&path);
320    }
321}