Skip to main content

strands_harness/tools/
file_tools.rs

1//! Filesystem tools `read`, `write` and `edit`, and the harness `shell`.
2//!
3//! The file tools route file access through the calling agent's
4//! [`sandbox`](strands::ToolAgent::sandbox), so they behave the same against host and container
5//! filesystems. Their texts and limits are the harness's, which differ from the SDK's vended
6//! `read`/`write`/`edit`. `shell` is the SDK's stateless sandbox shell
7//! ([`strands::vended_tools::shell::make_shell`]).
8
9use serde_json::json;
10use strands::tools::{FunctionTool, ToolContext, ToolError};
11use strands::types::{
12    DocumentBlock, DocumentFormat, DocumentSource, ImageBlock, ImageFormat, ImageSource, JsonSchema, JsonValue,
13    ToolResultContent,
14};
15use strands::vended_tools::shell::{MakeShellOptions, make_shell};
16
17const READ_DEFAULT_LIMIT: f64 = 2000.0;
18
19const IMAGE_EXTENSIONS: [&str; 5] = ["png", "jpg", "jpeg", "gif", "webp"];
20
21const PNG: &[u8] = &[0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
22const JPEG: &[u8] = &[0xff, 0xd8, 0xff];
23const GIF87A: &[u8] = b"GIF87a";
24const GIF89A: &[u8] = b"GIF89a";
25
26/// The `read` tool description (`READ_DESCRIPTION`).
27pub const READ_DESCRIPTION: &str = concat!(
28    "Read a file. Text returns `cat -n` style numbered lines so you can cite `path:line`; images ",
29    "(png/jpg/jpeg/gif/webp) and binary documents (pdf/doc/docx/xls/xlsx) return media you can view directly. ",
30    "Text defaults to the first 2000 lines; use offset/limit to page through larger files."
31);
32
33/// The `write` tool description.
34pub const WRITE_DESCRIPTION: &str =
35    "Write a file, creating it or overwriting it. Use `edit` for surgical changes to a large file.";
36
37/// The `edit` tool description.
38pub const EDIT_DESCRIPTION: &str = "Replace an exact string in a file. `old_str` must appear exactly once.";
39
40fn read_schema() -> JsonSchema {
41    json!({
42        "type": "object",
43        "properties": {
44            "path": {"type": "string", "description": "Absolute path to the file."},
45            "offset": {
46                "description": "1-indexed line to start from. Defaults to the first line. Text files only.",
47                "type": "number"
48            },
49            "limit": {
50                "description": "Maximum number of lines to return. Defaults to 2000. Text files only.",
51                "type": "number"
52            }
53        },
54        "required": ["path"],
55        "additionalProperties": false
56    })
57}
58
59fn write_schema() -> JsonSchema {
60    json!({
61        "type": "object",
62        "properties": {
63            "path": {"type": "string", "description": "Absolute path to the file."},
64            "content": {"type": "string", "description": "The full file content to write."}
65        },
66        "required": ["path", "content"],
67        "additionalProperties": false
68    })
69}
70
71fn edit_schema() -> JsonSchema {
72    json!({
73        "type": "object",
74        "properties": {
75            "path": {"type": "string", "description": "Absolute path to the file."},
76            "old_str": {"type": "string", "description": "Exact text to find. Must be unique within the file."},
77            "new_str": {"type": "string", "description": "Replacement text."}
78        },
79        "required": ["path", "old_str", "new_str"],
80        "additionalProperties": false
81    })
82}
83
84/// The harness `read` tool.
85///
86/// `media: false` is for a model that rejects image and document blocks: `read` then describes
87/// those files in text instead. Text files come back as `cat -n` style numbered lines, the first
88/// 2000 by default; images are checked against their signature, so a mislabeled file is an error
89/// rather than an image block that would poison the history.
90///
91/// ```
92/// use strands::Tool;
93/// use strands_harness::tools::file_tools::read_tool;
94///
95/// let read = read_tool(true);
96/// assert_eq!(read.name(), "read");
97/// ```
98#[must_use]
99pub fn read_tool(media: bool) -> FunctionTool {
100    FunctionTool::builder("read", READ_DESCRIPTION)
101        .input_schema(read_schema())
102        .callback(move |input, context| async move { read(&input, &context, media).await })
103}
104
105/// The harness `write` tool (`write`): writes the whole file through the agent's sandbox and
106/// reports the line count.
107#[must_use]
108pub fn write_tool() -> FunctionTool {
109    FunctionTool::builder("write", WRITE_DESCRIPTION)
110        .input_schema(write_schema())
111        .callback(|input, context| async move { write(&input, &context).await })
112}
113
114/// The harness `edit` tool (`edit`): replaces `old_str`, which must appear exactly once, with
115/// `new_str`.
116#[must_use]
117pub fn edit_tool() -> FunctionTool {
118    FunctionTool::builder("edit", EDIT_DESCRIPTION)
119        .input_schema(edit_schema())
120        .callback(|input, context| async move { edit(&input, &context).await })
121}
122
123/// The harness `shell` built-in (`makeShell(builtinTools.shell)`): the SDK's stateless sandbox
124/// shell, whose schema is `command` and `timeout` only. `description` replaces the SDK's default
125/// description (`ShellConfig.description`).
126///
127/// # Errors
128///
129/// None in practice; [`make_shell`] fails only on an invalid default timeout, which this does
130/// not set.
131pub fn shell_tool(description: Option<String>) -> strands::Result<FunctionTool> {
132    make_shell(MakeShellOptions {
133        description,
134        ..MakeShellOptions::default()
135    })
136}
137
138fn string_field<'a>(input: &'a JsonValue, key: &str) -> Result<&'a str, ToolError> {
139    input
140        .get(key)
141        .and_then(JsonValue::as_str)
142        .ok_or_else(|| ToolError::msg(format!("Invalid input: expected string at \"{key}\".")))
143}
144
145fn number_field(input: &JsonValue, key: &str) -> Result<Option<f64>, ToolError> {
146    match input.get(key) {
147        None | Some(JsonValue::Null) => Ok(None),
148        Some(value) => value
149            .as_f64()
150            .map(Some)
151            .ok_or_else(|| ToolError::msg(format!("Invalid input: expected number at \"{key}\"."))),
152    }
153}
154
155/// Accepts either platform's absolute form (POSIX `/`, Windows `\`, a drive letter with a
156/// separator, or a UNC share): the path belongs to the sandbox, not the host.
157fn validate_path(path: &str) -> Result<(), ToolError> {
158    let bytes = path.as_bytes();
159    let drive =
160        bytes.len() >= 3 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' && matches!(bytes[2], b'\\' | b'/');
161    if !(path.starts_with('/') || path.starts_with('\\') || drive) {
162        return Err(ToolError::msg(format!(
163            "The path {path} is not absolute; it should start with '/' (or a drive letter or UNC share on Windows)."
164        )));
165    }
166    if path.split(['/', '\\']).any(|segment| segment == "..") {
167        return Err(ToolError::msg("Invalid path: path traversal is not allowed."));
168    }
169    Ok(())
170}
171
172fn file_name(path: &str) -> &str {
173    path.rsplit(['/', '\\']).next().unwrap_or_default()
174}
175
176fn extension(path: &str) -> String {
177    let name = file_name(path);
178    name.rfind('.')
179        .map_or_else(String::new, |dot| name[dot + 1..].to_lowercase())
180}
181
182/// Bedrock accepts only alphanumerics, whitespace, hyphens, parentheses and square brackets in
183/// document names, with no consecutive whitespace.
184fn document_name(path: &str) -> String {
185    let replaced: String = file_name(path)
186        .chars()
187        .map(|c| {
188            let allowed = c.is_ascii_alphanumeric() || c.is_whitespace() || "-()[]".contains(c);
189            if allowed { c } else { ' ' }
190        })
191        .collect();
192    let collapsed = replaced.split_whitespace().collect::<Vec<_>>().join(" ");
193    if collapsed.is_empty() {
194        "document".to_owned()
195    } else {
196        collapsed
197    }
198}
199
200fn sniff_image_format(data: &[u8]) -> Option<ImageFormat> {
201    if data.starts_with(b"RIFF") && data.get(8..12) == Some(b"WEBP".as_slice()) {
202        return Some(ImageFormat::Webp);
203    }
204    [
205        (PNG, ImageFormat::Png),
206        (JPEG, ImageFormat::Jpeg),
207        (GIF87A, ImageFormat::Gif),
208        (GIF89A, ImageFormat::Gif),
209    ]
210    .into_iter()
211    .find(|(signature, _)| data.starts_with(signature))
212    .map(|(_, format)| format)
213}
214
215fn image_format_name(format: ImageFormat) -> &'static str {
216    match format {
217        ImageFormat::Png => "png",
218        ImageFormat::Gif => "gif",
219        ImageFormat::Webp => "webp",
220        _ => "jpeg",
221    }
222}
223
224fn document_format(ext: &str) -> Option<DocumentFormat> {
225    match ext {
226        "pdf" => Some(DocumentFormat::Pdf),
227        "doc" => Some(DocumentFormat::Doc),
228        "docx" => Some(DocumentFormat::Docx),
229        "xls" => Some(DocumentFormat::Xls),
230        "xlsx" => Some(DocumentFormat::Xlsx),
231        _ => None,
232    }
233}
234
235fn media_placeholder(path: &str, kind: &str, format: &str, size: usize) -> String {
236    format!(
237        "[{kind} file: {path} ({format}, {size} bytes). This model cannot view {} files, so its contents are not shown. Use shell tools if the file has a text-extractable form.]",
238        kind.to_lowercase()
239    )
240}
241
242/// A number as text, whole numbers in the safe integer range without a fraction, or `undefined`.
243fn js_text(value: Option<f64>) -> String {
244    match value {
245        None => "undefined".to_owned(),
246        Some(value) if value.fract() == 0.0 && value.abs() < 9_007_199_254_740_992.0 => format!("{value:.0}"),
247        Some(value) => value.to_string(),
248    }
249}
250
251/// `Array.prototype.slice` index resolution: truncates, counts a negative index from the end,
252/// and clamps to `[0, len]`.
253#[allow(
254    clippy::cast_possible_truncation,
255    clippy::cast_sign_loss,
256    clippy::cast_precision_loss,
257    reason = "clamped to [0, len] before the cast"
258)]
259fn slice_index(index: f64, len: usize) -> usize {
260    let len_f = len as f64;
261    let index = if index.is_nan() { 0.0 } else { index.trunc() };
262    let resolved = if index < 0.0 {
263        (len_f + index).max(0.0)
264    } else {
265        index.min(len_f)
266    };
267    resolved as usize
268}
269
270async fn read(input: &JsonValue, context: &ToolContext, media: bool) -> Result<JsonValue, ToolError> {
271    let path = string_field(input, "path")?;
272    let offset = number_field(input, "offset")?;
273    let limit = number_field(input, "limit")?;
274    validate_path(path)?;
275    let ext = extension(path);
276    let sandbox = context.agent().sandbox();
277
278    if IMAGE_EXTENSIONS.contains(&ext.as_str()) {
279        let bytes = sandbox.read_file(path).await?;
280        let Some(format) = sniff_image_format(&bytes) else {
281            return Err(ToolError::msg(format!(
282                "{path} has a .{ext} extension but its {} bytes are not a png, jpeg, gif, or webp image. Identify it with `file`; if it is text, read it with `cat`.",
283                bytes.len()
284            )));
285        };
286        if !media {
287            return Ok(media_placeholder(path, "Image", image_format_name(format), bytes.len()).into());
288        }
289        let block = ImageBlock::new(format, ImageSource::Bytes(bytes));
290        return Ok(serde_json::to_value(ToolResultContent::Image(block))?);
291    }
292
293    if let Some(format) = document_format(&ext) {
294        let bytes = sandbox.read_file(path).await?;
295        if !media {
296            return Ok(media_placeholder(path, "Document", &ext, bytes.len()).into());
297        }
298        let block = DocumentBlock::new(document_name(path), format, DocumentSource::Bytes(bytes));
299        return Ok(serde_json::to_value(ToolResultContent::Document(block))?);
300    }
301
302    let content = sandbox.read_text(path).await?;
303    Ok(numbered_window(&content, offset, limit).into())
304}
305
306#[allow(clippy::cast_precision_loss, reason = "line counts are far below 2^53")]
307fn numbered_window(content: &str, offset: Option<f64>, limit: Option<f64>) -> String {
308    let lines: Vec<&str> = content.split('\n').collect();
309    let start_f = offset
310        .filter(|offset| *offset != 0.0 && !offset.is_nan())
311        .map_or(0.0, |offset| (offset - 1.0).max(0.0));
312    let count = limit.unwrap_or(READ_DEFAULT_LIMIT);
313    let start = slice_index(start_f, lines.len());
314    let end = slice_index(start_f + count, lines.len());
315    let window = lines.get(start..end.max(start)).unwrap_or_default();
316    if window.is_empty() {
317        return format!(
318            "[File has {} lines; offset {} is past the end.]",
319            lines.len(),
320            js_text(offset)
321        );
322    }
323    let mut numbered = window
324        .iter()
325        .enumerate()
326        .map(|(index, line)| format!("{:>6}\t{line}", index + start + 1))
327        .collect::<Vec<_>>()
328        .join("\n");
329    if start_f > 0.0 || start_f + count < lines.len() as f64 {
330        numbered.push_str(&format!(
331            "\n[Showing lines {}-{} of {}. Use offset/limit to read more.]",
332            js_text(Some(start_f + 1.0)),
333            js_text(Some(start_f + window.len() as f64)),
334            lines.len()
335        ));
336    }
337    numbered
338}
339
340async fn write(input: &JsonValue, context: &ToolContext) -> Result<JsonValue, ToolError> {
341    let path = string_field(input, "path")?;
342    let content = string_field(input, "content")?;
343    validate_path(path)?;
344    context.agent().sandbox().write_text(path, content).await?;
345    let line_count = if content.is_empty() {
346        0
347    } else {
348        content.split('\n').count()
349    };
350    Ok(format!("Wrote {line_count} lines to {path}.").into())
351}
352
353/// How many times `old` occurs in `content`; an empty `old` counts the gaps between UTF-16 code
354/// units (one less than their number).
355#[allow(clippy::cast_possible_wrap, reason = "file sizes are far below i64::MAX")]
356fn occurrences(content: &str, old: &str) -> i64 {
357    if old.is_empty() {
358        return content.encode_utf16().count() as i64 - 1;
359    }
360    content.matches(old).count() as i64
361}
362
363async fn edit(input: &JsonValue, context: &ToolContext) -> Result<JsonValue, ToolError> {
364    let path = string_field(input, "path")?;
365    let old = string_field(input, "old_str")?;
366    let new = string_field(input, "new_str")?;
367    validate_path(path)?;
368    let sandbox = context.agent().sandbox();
369    let content = sandbox.read_text(path).await?;
370    let count = occurrences(&content, old);
371    if count == 0 {
372        return Err(ToolError::msg(format!("old_str did not appear verbatim in {path}.")));
373    }
374    if count > 1 {
375        return Err(ToolError::msg(format!(
376            "old_str appears {count} times in {path}; make it unique."
377        )));
378    }
379    sandbox.write_text(path, &content.replacen(old, new, 1)).await?;
380    Ok(format!("Edited {path}.").into())
381}
382
383#[cfg(test)]
384mod tests;