Skip to main content

strands/vended_tools/
write.rs

1//! The sandbox-routed `write` tool: creates or overwrites a text file. Pairs with
2//! [`read`](super::read) and [`edit`](super::edit).
3
4use std::sync::Arc;
5
6use serde_json::json;
7
8use super::input::InputReader;
9use super::paths::validate_absolute_path;
10use super::resolve_sandbox;
11use crate::sandbox::Sandbox;
12use crate::tools::{FunctionTool, ToolError};
13use crate::types::{JsonSchema, JsonValue};
14
15/// The description of the `write` tool shown to the model (`DEFAULT_WRITE_DESCRIPTION`).
16pub const DEFAULT_WRITE_DESCRIPTION: &str =
17    "Create or overwrite a text file with the full provided content. Files must use absolute paths.";
18
19/// Options for [`make_write`] (`MakeWriteOptions`).
20#[derive(Clone, Default, bon::Builder)]
21#[builder(on(String, into))]
22pub struct MakeWriteOptions {
23    /// The sandbox to write to. `None` uses the calling agent's
24    /// [`sandbox`](crate::ToolAgent::sandbox).
25    pub sandbox: Option<Arc<dyn Sandbox>>,
26    /// The tool name; `write` when absent.
27    pub name: Option<String>,
28    /// The tool description; [`DEFAULT_WRITE_DESCRIPTION`] when absent.
29    pub description: Option<String>,
30}
31
32impl std::fmt::Debug for MakeWriteOptions {
33    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
34        f.debug_struct("MakeWriteOptions")
35            .field("sandbox", &self.sandbox.is_some())
36            .field("name", &self.name)
37            .field("description", &self.description)
38            .finish()
39    }
40}
41
42fn input_schema() -> JsonSchema {
43    json!({
44        "type": "object",
45        "properties": {
46            "path": {"type": "string", "description": "Absolute path to the file."},
47            "content": {"type": "string", "description": "The full file content to write."}
48        },
49        "required": ["path", "content"],
50        "additionalProperties": false
51    })
52}
53
54/// The default `write` tool, writing through the calling agent's sandbox (`write`).
55#[must_use]
56pub fn write() -> FunctionTool {
57    make_write(MakeWriteOptions::default())
58}
59
60/// Creates a sandbox-routed write tool. Missing parent directories are created;
61/// the call fails when `path` is not absolute or has a `..` segment.
62///
63/// ```
64/// use strands::vended_tools::write::{MakeWriteOptions, make_write};
65///
66/// let tool = make_write(MakeWriteOptions::builder().name("save").build());
67/// assert_eq!(strands::Tool::name(&tool), "save");
68/// ```
69#[must_use]
70pub fn make_write(options: MakeWriteOptions) -> FunctionTool {
71    let name = options.name.unwrap_or_else(|| "write".to_owned());
72    let description = options
73        .description
74        .unwrap_or_else(|| DEFAULT_WRITE_DESCRIPTION.to_owned());
75    let bound = options.sandbox;
76    FunctionTool::builder(name, description)
77        .input_schema(input_schema())
78        .callback(move |input, context| {
79            let sandbox = resolve_sandbox(bound.as_ref(), &context);
80            async move { run(sandbox.as_ref(), &input).await }
81        })
82}
83
84async fn run(sandbox: &dyn Sandbox, input: &JsonValue) -> Result<JsonValue, ToolError> {
85    let mut reader = InputReader::new(input);
86    let path = reader.string("path");
87    let content = reader.string("content");
88    reader.finish()?;
89    let (path, content) = (path.unwrap_or_default(), content.unwrap_or_default());
90    validate_absolute_path(path)?;
91    sandbox.write_text(path, content).await?;
92    let line_count = if content.is_empty() {
93        0
94    } else {
95        content.matches('\n').count() + 1
96    };
97    let noun = if line_count == 1 { "line" } else { "lines" };
98    Ok(format!("Wrote {line_count} {noun} to {path}.").into())
99}
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104    use crate::vended_tools::test_support::{RecordingSandbox, agent, agent_with_sandbox, error_text};
105
106    #[tokio::test]
107    async fn rejects_relative_path() {
108        let message = error_text(&write(), json!({"path": "relative.txt", "content": "x"}), &agent()).await;
109        assert!(message.contains("not absolute"));
110    }
111
112    #[tokio::test]
113    async fn rejects_parent_traversal_posix() {
114        let message = error_text(
115            &write(),
116            json!({"path": "/tmp/../etc/passwd", "content": "x"}),
117            &agent(),
118        )
119        .await;
120        assert!(message.contains("path traversal is not allowed"));
121    }
122
123    #[tokio::test]
124    async fn rejects_parent_traversal_windows() {
125        let input = json!({"path": "C:\\project\\..\\etc\\hosts", "content": "x"});
126        let message = error_text(&write(), input, &agent()).await;
127        assert!(message.contains("path traversal is not allowed"));
128    }
129
130    #[tokio::test]
131    async fn default_write_reads_agent_sandbox() {
132        let sandbox = Arc::new(RecordingSandbox::default());
133        let agent = agent_with_sandbox(sandbox.clone());
134        let message = crate::vended_tools::test_support::ok_text(
135            &write(),
136            json!({"path": "/tmp/f.txt", "content": "from-agent"}),
137            &agent,
138        )
139        .await;
140        assert_eq!(message, "Wrote 1 line to /tmp/f.txt.");
141        assert_eq!(
142            *sandbox.writes.lock().unwrap(),
143            [("/tmp/f.txt".to_owned(), b"from-agent".to_vec())]
144        );
145    }
146
147    #[cfg(unix)]
148    mod host {
149        use super::*;
150        use crate::sandbox::NotASandboxLocalEnvironment;
151        use crate::vended_tools::test_support::ok_text;
152
153        fn write_tool() -> FunctionTool {
154            make_write(MakeWriteOptions {
155                sandbox: Some(Arc::new(NotASandboxLocalEnvironment::new())),
156                ..MakeWriteOptions::default()
157            })
158        }
159
160        async fn write_file(path: &std::path::Path, content: &str) -> String {
161            let input = json!({"path": path.to_string_lossy(), "content": content});
162            ok_text(&write_tool(), input, &agent()).await
163        }
164
165        #[tokio::test]
166        async fn creates_file() {
167            let dir = tempfile::tempdir().unwrap();
168            let path = dir.path().join("new.txt");
169            let message = write_file(&path, "hello\nworld").await;
170            assert_eq!(message, format!("Wrote 2 lines to {}.", path.display()));
171            assert_eq!(std::fs::read_to_string(&path).unwrap(), "hello\nworld");
172        }
173
174        #[tokio::test]
175        async fn overwrites_existing_file() {
176            let dir = tempfile::tempdir().unwrap();
177            let path = dir.path().join("f.txt");
178            std::fs::write(&path, "old content").unwrap();
179            let message = write_file(&path, "new").await;
180            assert_eq!(message, format!("Wrote 1 line to {}.", path.display()));
181            assert_eq!(std::fs::read_to_string(&path).unwrap(), "new");
182        }
183
184        #[tokio::test]
185        async fn empty_content_reports_zero_lines() {
186            let dir = tempfile::tempdir().unwrap();
187            let path = dir.path().join("empty.txt");
188            let message = write_file(&path, "").await;
189            assert_eq!(message, format!("Wrote 0 lines to {}.", path.display()));
190            assert_eq!(std::fs::read_to_string(&path).unwrap(), "");
191        }
192
193        #[tokio::test]
194        async fn single_line_without_trailing_newline() {
195            let dir = tempfile::tempdir().unwrap();
196            let path = dir.path().join("one.txt");
197            let message = write_file(&path, "just one line").await;
198            assert_eq!(message, format!("Wrote 1 line to {}.", path.display()));
199        }
200
201        #[tokio::test]
202        async fn trailing_newline_counts_the_empty_tail() {
203            let dir = tempfile::tempdir().unwrap();
204            let path = dir.path().join("tail.txt");
205            let message = write_file(&path, "a\nb\n").await;
206            assert_eq!(message, format!("Wrote 3 lines to {}.", path.display()));
207        }
208
209        #[tokio::test]
210        async fn creates_parent_directories() {
211            let dir = tempfile::tempdir().unwrap();
212            let path = dir.path().join("a").join("b").join("c.txt");
213            write_file(&path, "deep").await;
214            assert_eq!(std::fs::read_to_string(&path).unwrap(), "deep");
215        }
216
217        #[tokio::test]
218        async fn bound_sandbox_overrides_agent_sandbox() {
219            let dir = tempfile::tempdir().unwrap();
220            let path = dir.path().join("f.txt");
221            let agent_sandbox = Arc::new(RecordingSandbox::default());
222            let input = json!({"path": path.to_string_lossy(), "content": "from-bound"});
223            ok_text(&write_tool(), input, &agent_with_sandbox(agent_sandbox.clone())).await;
224            assert_eq!(std::fs::read_to_string(&path).unwrap(), "from-bound");
225            assert!(agent_sandbox.writes.lock().unwrap().is_empty());
226        }
227    }
228}