1use std::sync::Arc;
8
9use serde_json::json;
10
11use super::input::InputReader;
12use super::paths::validate_absolute_path;
13use super::resolve_sandbox;
14use crate::sandbox::Sandbox;
15use crate::tools::{FunctionTool, ToolError};
16use crate::types::{
17 DocumentBlock, DocumentFormat, DocumentSource, ImageBlock, ImageFormat, ImageSource, JsonSchema, JsonValue,
18 ToolResultContent,
19};
20
21const READ_DEFAULT_LIMIT: u64 = 2000;
22const READ_MAX_BYTES: usize = 1_048_576;
23const READ_MAX_MEDIA_BYTES: usize = 10_485_760;
24
25const IMAGE_EXTENSIONS: [&str; 5] = ["png", "jpg", "jpeg", "gif", "webp"];
26
27const PNG: &[u8] = &[0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
28const JPEG: &[u8] = &[0xff, 0xd8, 0xff];
29const GIF87A: &[u8] = b"GIF87a";
30const GIF89A: &[u8] = b"GIF89a";
31const OLE2: &[u8] = &[0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1];
32const ZIP: &[u8] = &[0x50, 0x4b, 0x03, 0x04];
33const PDF: &[u8] = b"%PDF-";
34
35pub const DEFAULT_READ_DESCRIPTION: &str = "Read a file. Text returns `cat -n` style numbered lines so you can cite `path:line`. Files must use absolute paths.";
37
38const MEDIA_DESCRIPTION_SUFFIX: &str =
39 " Images (png/jpg/jpeg/gif/webp) and binary documents (pdf/doc/docx/xls/xlsx) return media you can view directly.";
40
41#[derive(Clone, Default, bon::Builder)]
43#[builder(on(String, into))]
44pub struct MakeReadOptions {
45 pub sandbox: Option<Arc<dyn Sandbox>>,
48 pub media: Option<bool>,
51 pub name: Option<String>,
53 pub description: Option<String>,
56 pub max_bytes: Option<usize>,
58 pub max_media_bytes: Option<usize>,
60}
61
62impl std::fmt::Debug for MakeReadOptions {
63 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64 f.debug_struct("MakeReadOptions")
65 .field("sandbox", &self.sandbox.is_some())
66 .field("media", &self.media)
67 .field("name", &self.name)
68 .field("max_bytes", &self.max_bytes)
69 .field("max_media_bytes", &self.max_media_bytes)
70 .finish_non_exhaustive()
71 }
72}
73
74#[derive(Clone, Copy)]
75struct Limits {
76 media: bool,
77 max_bytes: usize,
78 max_media_bytes: usize,
79}
80
81fn input_schema() -> JsonSchema {
82 json!({
83 "type": "object",
84 "properties": {
85 "path": {"type": "string", "description": "Absolute path to the file."},
86 "offset": {
87 "description": "1-indexed line to start from. Defaults to the first line. Text files only.",
88 "type": "integer",
89 "minimum": 1,
90 "maximum": 9_007_199_254_740_991_u64
91 },
92 "limit": {
93 "description": "Maximum number of lines to return. Defaults to 2000. Text files only.",
94 "type": "integer",
95 "minimum": 1,
96 "maximum": 9_007_199_254_740_991_u64
97 }
98 },
99 "required": ["path"],
100 "additionalProperties": false
101 })
102}
103
104#[must_use]
106pub fn read() -> FunctionTool {
107 make_read(MakeReadOptions::default())
108}
109
110#[must_use]
123pub fn make_read(options: MakeReadOptions) -> FunctionTool {
124 let limits = Limits {
125 media: options.media.unwrap_or(true),
126 max_bytes: options.max_bytes.unwrap_or(READ_MAX_BYTES),
127 max_media_bytes: options.max_media_bytes.unwrap_or(READ_MAX_MEDIA_BYTES),
128 };
129 let description = options.description.unwrap_or_else(|| {
130 let suffix = if limits.media { MEDIA_DESCRIPTION_SUFFIX } else { "" };
131 format!("{DEFAULT_READ_DESCRIPTION}{suffix}")
132 });
133 let name = options.name.unwrap_or_else(|| "read".to_owned());
134 let bound = options.sandbox;
135 FunctionTool::builder(name, description)
136 .input_schema(input_schema())
137 .callback(move |input, context| {
138 let sandbox = resolve_sandbox(bound.as_ref(), &context);
139 async move { run(sandbox.as_ref(), &input, limits).await }
140 })
141}
142
143async fn run(sandbox: &dyn Sandbox, input: &JsonValue, limits: Limits) -> Result<JsonValue, ToolError> {
144 let mut reader = InputReader::new(input);
145 let path = reader.string("path");
146 let offset = reader.optional_positive_integer("offset", "offset must be a positive 1-indexed line number");
147 let limit = reader.optional_positive_integer("limit", "limit must be a positive line count");
148 reader.finish()?;
149 let path = path.unwrap_or_default();
150 validate_absolute_path(path)?;
151 let ext = extension(path);
152
153 if IMAGE_EXTENSIONS.contains(&ext.as_str()) {
154 let bytes = sandbox.read_file(path).await?;
155 let Some(format) = sniff_image_format(&bytes) else {
156 return Err(ToolError::msg(format!(
157 "{path} has a .{ext} extension but its {} bytes are not a png, jpeg, gif, or webp image. If a shell tool is available, use it to identify or extract text.",
158 bytes.len()
159 )));
160 };
161 if !limits.media {
162 return Ok(media_placeholder(path, "Image", image_format_name(format), bytes.len()).into());
163 }
164 check_media_size(path, "image", bytes.len(), limits.max_media_bytes)?;
165 let block = ImageBlock::new(format, ImageSource::Bytes(bytes));
166 return Ok(serde_json::to_value(ToolResultContent::Image(block))?);
167 }
168
169 if let Some((format, signatures)) = document_format(&ext) {
170 let bytes = sandbox.read_file(path).await?;
171 if !signatures.iter().any(|signature| bytes.starts_with(signature)) {
172 return Err(ToolError::msg(format!(
173 "{path} has a .{ext} extension but its {} bytes are not a valid {ext} document. If a shell tool is available, use it to identify or extract text.",
174 bytes.len()
175 )));
176 }
177 if !limits.media {
178 return Ok(media_placeholder(path, "Document", &ext, bytes.len()).into());
179 }
180 check_media_size(path, "document", bytes.len(), limits.max_media_bytes)?;
181 let block = DocumentBlock::new(document_name(path), format, DocumentSource::Bytes(bytes));
182 return Ok(serde_json::to_value(ToolResultContent::Document(block))?);
183 }
184
185 let bytes = sandbox.read_file(path).await?;
186 let Ok(content) = String::from_utf8(bytes) else {
187 return Err(ToolError::msg(format!(
188 "{path} is not UTF-8 text. If a shell tool is available, inspect it there."
189 )));
190 };
191 Ok(numbered_window(path, &content, offset, limit, limits.max_bytes)?.into())
192}
193
194fn numbered_window(
195 path: &str,
196 content: &str,
197 offset: Option<u64>,
198 limit: Option<u64>,
199 max_bytes: usize,
200) -> Result<String, ToolError> {
201 let lines: Vec<&str> = content.split('\n').collect();
202 let start = offset.map_or(0, |offset| usize::try_from(offset - 1).unwrap_or(usize::MAX));
203 let count = usize::try_from(limit.unwrap_or(READ_DEFAULT_LIMIT)).unwrap_or(usize::MAX);
204 let end = start.saturating_add(count).min(lines.len());
205 let window = lines.get(start..end).unwrap_or_default();
206 if window.is_empty() {
207 return Ok(format!(
208 "[File has {} lines; offset {} is past the end.]",
209 lines.len(),
210 offset.unwrap_or_default()
211 ));
212 }
213 let window_bytes = window.iter().map(|line| line.len()).sum::<usize>() + window.len() - 1;
214 if window_bytes > max_bytes {
215 return Err(ToolError::msg(format!(
216 "Read window from {path} is {window_bytes} bytes ({} lines), exceeding the {max_bytes}-byte limit. Reduce `limit` or shift `offset` to read a smaller slice.",
217 window.len()
218 )));
219 }
220 let mut numbered = window
221 .iter()
222 .enumerate()
223 .map(|(index, line)| format!("{:>6}\t{line}", index + start + 1))
224 .collect::<Vec<_>>()
225 .join("\n");
226 if start > 0 || start.saturating_add(count) < lines.len() {
227 numbered.push_str(&format!(
228 "\n[Showing lines {}-{} of {}. Use offset/limit to read more.]",
229 start + 1,
230 start + window.len(),
231 lines.len()
232 ));
233 }
234 Ok(numbered)
235}
236
237fn file_name(path: &str) -> &str {
238 path.rsplit(['/', '\\']).next().unwrap_or_default()
239}
240
241fn extension(path: &str) -> String {
242 let name = file_name(path);
243 name.rfind('.')
244 .map_or_else(String::new, |dot| name[dot + 1..].to_lowercase())
245}
246
247fn document_name(path: &str) -> String {
250 let replaced: String = file_name(path)
251 .chars()
252 .map(|c| {
253 let allowed = c.is_ascii_alphanumeric() || c.is_whitespace() || "-()[]".contains(c);
254 if allowed { c } else { ' ' }
255 })
256 .collect();
257 let collapsed = replaced.split_whitespace().collect::<Vec<_>>().join(" ");
258 if collapsed.is_empty() {
259 "document".to_owned()
260 } else {
261 collapsed
262 }
263}
264
265fn sniff_image_format(data: &[u8]) -> Option<ImageFormat> {
266 if data.starts_with(b"RIFF") && data.get(8..12) == Some(b"WEBP".as_slice()) {
267 return Some(ImageFormat::Webp);
268 }
269 if data.starts_with(PNG) {
270 return Some(ImageFormat::Png);
271 }
272 if data.starts_with(JPEG) {
273 return Some(ImageFormat::Jpeg);
274 }
275 if data.starts_with(GIF87A) || data.starts_with(GIF89A) {
276 return Some(ImageFormat::Gif);
277 }
278 None
279}
280
281fn image_format_name(format: ImageFormat) -> &'static str {
282 match format {
283 ImageFormat::Png => "png",
284 ImageFormat::Gif => "gif",
285 ImageFormat::Webp => "webp",
286 _ => "jpeg",
287 }
288}
289
290fn document_format(ext: &str) -> Option<(DocumentFormat, &'static [&'static [u8]])> {
291 match ext {
292 "pdf" => Some((DocumentFormat::Pdf, &[PDF])),
293 "doc" => Some((DocumentFormat::Doc, &[OLE2])),
294 "xls" => Some((DocumentFormat::Xls, &[OLE2])),
295 "docx" => Some((DocumentFormat::Docx, &[ZIP])),
296 "xlsx" => Some((DocumentFormat::Xlsx, &[ZIP])),
297 _ => None,
298 }
299}
300
301fn check_media_size(path: &str, kind: &str, size: usize, max_bytes: usize) -> Result<(), ToolError> {
302 if size <= max_bytes {
303 return Ok(());
304 }
305 Err(ToolError::msg(format!(
306 "{path} is {size} bytes, exceeding the {max_bytes}-byte limit for {kind} reads. If a shell tool is available, use it to extract a smaller representation."
307 )))
308}
309
310fn media_placeholder(path: &str, kind: &str, format: &str, size: usize) -> String {
311 format!(
312 "[{kind} file: {path} ({format}, {size} bytes). This model cannot view {} files, so its contents are not shown. If a shell tool is available, use it when the file has a text-extractable form.]",
313 kind.to_lowercase()
314 )
315}
316
317#[cfg(test)]
318mod tests;