Skip to main content

adk_devtools/tools/
read.rs

1//! `read_file` — return the (optionally sliced) contents of a file, or an image or PDF as
2//! inline data (spec 3.1 §10 D6).
3
4use std::sync::Arc;
5
6use adk_core::{Result, Tool, ToolContext};
7use async_trait::async_trait;
8use serde_json::{Value, json};
9
10use crate::error::DevToolError;
11use crate::workspace::Workspace;
12
13/// The largest image or PDF `read_file` returns as inline data by default: 4 MiB
14/// (spec 3.1 §10 D6). A larger file gets the text stub only.
15///
16/// # Example
17///
18/// ```rust
19/// assert_eq!(adk_devtools::DEFAULT_MAX_INLINE_BYTES, 4 * 1024 * 1024);
20/// assert!(adk_devtools::DEFAULT_MAX_INLINE_BYTES < adk_core::MAX_INLINE_DATA_SIZE);
21/// ```
22pub const DEFAULT_MAX_INLINE_BYTES: usize = 4 * 1024 * 1024;
23
24/// Reads a file from the workspace: UTF-8 text with line numbers, or a PNG, JPEG, GIF, WebP
25/// or PDF as an inline data part the model can look at (spec 3.1 §10 D6).
26///
27/// A file matching the workspace's exclusion patterns ([`Workspace::exclude_globs`]),
28/// by its requested path or the path a symlink resolves to, is refused with
29/// [`DevToolError::Excluded`]. On Unix the file is opened without following a symlink on
30/// any component of the target the containment check resolved, and a file with more
31/// than one hard link is refused (spec 3.1 §10 D4). Binary content follows the same rules.
32///
33/// The type comes from the file's first bytes, never its extension: a text file named
34/// `diagram.png` is read as text, and `notes.txt` holding a PNG is returned as an image.
35/// The result of a binary read is `{ "response": { path, mime_type, bytes, content },
36/// "inline_data": [{ mime_type, data }] }`, which the agent loop turns into a function
37/// response with an inline part; `content` is a stub naming the type and size, so a
38/// provider that cannot take the bytes still learns what the file is. Over
39/// [`max_inline_bytes`](Self::max_inline_bytes), or under [`text_only`](Self::text_only),
40/// only the stub is returned. The bytes are never interpreted here (spec 3.1 §9.2 I55).
41///
42/// # Example
43///
44/// ```rust
45/// use adk_devtools::{ReadFileTool, Workspace};
46///
47/// let read = ReadFileTool::new(Workspace::new("./my-repo")).max_inline_bytes(1024 * 1024);
48/// # let _ = read;
49/// ```
50pub struct ReadFileTool {
51    workspace: Workspace,
52    max_inline_bytes: usize,
53    inline_data: bool,
54}
55
56impl ReadFileTool {
57    /// Create a `read_file` tool bound to `workspace`.
58    pub fn new(workspace: Workspace) -> Self {
59        Self { workspace, max_inline_bytes: DEFAULT_MAX_INLINE_BYTES, inline_data: true }
60    }
61
62    /// The largest image or PDF returned as inline data; capped at
63    /// [`adk_core::MAX_INLINE_DATA_SIZE`]. A larger file gets the text stub only.
64    #[must_use]
65    pub fn max_inline_bytes(mut self, bytes: usize) -> Self {
66        self.max_inline_bytes = bytes.min(adk_core::MAX_INLINE_DATA_SIZE);
67        self
68    }
69
70    /// Returns the text stub for images and PDFs and never their bytes, for a model
71    /// without vision.
72    #[must_use]
73    pub fn text_only(mut self) -> Self {
74        self.inline_data = false;
75        self
76    }
77}
78
79/// The MIME type of `bytes` when they start like a PNG, JPEG, GIF, WebP or PDF
80/// (spec 3.1 §10 D6: magic bytes, not the extension).
81///
82/// # Example
83///
84/// ```rust
85/// use adk_devtools::sniff_inline_mime;
86///
87/// assert_eq!(sniff_inline_mime(b"\x89PNG\r\n\x1a\n...."), Some("image/png"));
88/// assert_eq!(sniff_inline_mime(b"%PDF-1.7\n"), Some("application/pdf"));
89/// assert_eq!(sniff_inline_mime(b"fn main() {}"), None);
90/// ```
91pub fn sniff_inline_mime(bytes: &[u8]) -> Option<&'static str> {
92    if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
93        Some("image/png")
94    } else if bytes.starts_with(b"\xFF\xD8\xFF") {
95        Some("image/jpeg")
96    } else if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") {
97        Some("image/gif")
98    } else if bytes.len() >= 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WEBP" {
99        Some("image/webp")
100    } else if bytes.starts_with(b"%PDF-") {
101        Some("application/pdf")
102    } else {
103        None
104    }
105}
106
107#[async_trait]
108impl Tool for ReadFileTool {
109    fn name(&self) -> &str {
110        "read_file"
111    }
112
113    /// Reads a workspace file on disk.
114    fn egress(&self, _args: &serde_json::Value) -> adk_core::egress::ToolEgress {
115        adk_core::egress::ToolEgress::None
116    }
117
118    fn description(&self) -> &str {
119        "Read a file from the workspace. Text comes back with line numbers, with optional \
120         `offset` (1-based start line) and `limit` (number of lines). A PNG, JPEG, GIF, WebP \
121         or PDF comes back as an attached image or document you can look at, with its type \
122         and size."
123    }
124
125    fn is_read_only(&self) -> bool {
126        true
127    }
128
129    fn is_concurrency_safe(&self) -> bool {
130        true
131    }
132
133    fn parameters_schema(&self) -> Option<Value> {
134        Some(json!({
135            "type": "object",
136            "properties": {
137                "path": { "type": "string", "description": "Path relative to the workspace root." },
138                "offset": { "type": "integer", "description": "1-based first line to return (optional, text only)." },
139                "limit": { "type": "integer", "description": "Maximum number of lines to return (optional, text only)." }
140            },
141            "required": ["path"]
142        }))
143    }
144
145    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
146        let path = require_str(&args, "path")?;
147        let (resolved, target) = self.workspace.resolve_target(&path)?;
148        // A link inside the workspace can lead to an excluded file under another name.
149        if self.workspace.is_excluded(&resolved) || self.workspace.is_excluded(&target) {
150            return Err(DevToolError::Excluded(self.workspace.display(&resolved)).into());
151        }
152
153        let bytes = self.workspace.read_contained_bytes(&target).await?;
154        self.workspace
155            .record_digest(ctx.as_ref(), &resolved, &crate::read_ledger::sha256_hex(&bytes))
156            .await;
157        let display = self.workspace.display(&resolved);
158
159        if let Some(mime_type) = sniff_inline_mime(&bytes) {
160            let size = bytes.len();
161            let attached = self.inline_data && size <= self.max_inline_bytes;
162            let kind = if mime_type == "application/pdf" { "PDF document" } else { "image" };
163            let content = if attached {
164                format!("[{kind} {mime_type}, {size} bytes, attached as inline data]")
165            } else if self.inline_data {
166                format!(
167                    "[{kind} {mime_type}, {size} bytes; over the {} byte inline cap, so the \
168                     bytes are not attached]",
169                    self.max_inline_bytes
170                )
171            } else {
172                format!("[{kind} {mime_type}, {size} bytes; this model receives no binary data]")
173            };
174            let response = json!({
175                "path": display,
176                "mime_type": mime_type,
177                "bytes": size,
178                "content": content,
179                "inline": attached,
180            });
181            return Ok(if attached {
182                json!({
183                    "response": response,
184                    "inline_data": [{ "mime_type": mime_type, "data": bytes }],
185                })
186            } else {
187                response
188            });
189        }
190
191        let contents = String::from_utf8(bytes).map_err(|_| {
192            DevToolError::Other(format!(
193                "'{display}' is neither UTF-8 text nor a PNG, JPEG, GIF, WebP or PDF; read_file \
194                 returns text and those image and document types only"
195            ))
196        })?;
197
198        let offset = args.get("offset").and_then(Value::as_u64).unwrap_or(1).max(1) as usize;
199        let limit = args.get("limit").and_then(Value::as_u64).map(|v| v as usize);
200
201        let mut lines = String::new();
202        let mut total = 0usize;
203        let mut shown = 0usize;
204        for (idx, line) in contents.lines().enumerate() {
205            total += 1;
206            let line_no = idx + 1;
207            if line_no < offset {
208                continue;
209            }
210            if let Some(limit) = limit
211                && shown >= limit
212            {
213                break;
214            }
215            lines.push_str(&format!("{line_no:>6}\t{line}\n"));
216            shown += 1;
217        }
218
219        Ok(json!({
220            "path": display,
221            "content": lines,
222            "total_lines": total,
223            "returned_lines": shown,
224        }))
225    }
226}
227
228pub(crate) fn require_str(args: &Value, key: &str) -> Result<String> {
229    args.get(key).and_then(Value::as_str).map(str::to_string).ok_or_else(|| {
230        adk_core::AdkError::tool(format!("missing required string argument '{key}'"))
231    })
232}
233
234#[cfg(test)]
235mod tests {
236    use super::*;
237
238    #[test]
239    fn sniffing_reads_magic_bytes_only() {
240        assert_eq!(sniff_inline_mime(b"\xFF\xD8\xFF\xE0JFIF"), Some("image/jpeg"));
241        assert_eq!(sniff_inline_mime(b"GIF89a\x01\x00"), Some("image/gif"));
242        assert_eq!(sniff_inline_mime(b"RIFF\x00\x00\x00\x00WEBPVP8 "), Some("image/webp"));
243        assert_eq!(sniff_inline_mime(b"RIFF\x00\x00\x00\x00WAVEfmt "), None);
244        assert_eq!(sniff_inline_mime(b"%PDF-1.4"), Some("application/pdf"));
245        assert_eq!(sniff_inline_mime(b"PNG but not really"), None);
246        assert_eq!(sniff_inline_mime(b""), None);
247    }
248}