adk_devtools/tools/
read.rs1use 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
13pub const DEFAULT_MAX_INLINE_BYTES: usize = 4 * 1024 * 1024;
23
24pub struct ReadFileTool {
51 workspace: Workspace,
52 max_inline_bytes: usize,
53 inline_data: bool,
54}
55
56impl ReadFileTool {
57 pub fn new(workspace: Workspace) -> Self {
59 Self { workspace, max_inline_bytes: DEFAULT_MAX_INLINE_BYTES, inline_data: true }
60 }
61
62 #[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 #[must_use]
73 pub fn text_only(mut self) -> Self {
74 self.inline_data = false;
75 self
76 }
77}
78
79pub 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 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 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}