1use std::sync::Arc;
4
5use serde_json::json;
6
7use super::input::InputReader;
8use super::paths::validate_absolute_path;
9use super::resolve_sandbox;
10use crate::sandbox::Sandbox;
11use crate::tools::{FunctionTool, ToolError};
12use crate::types::{JsonSchema, JsonValue};
13
14pub const DEFAULT_EDIT_DESCRIPTION: &str = "Replace an exact string in a text file. `old_str` must appear in the file exactly once. Files must use absolute paths.";
16
17#[derive(Clone, Default, bon::Builder)]
19#[builder(on(String, into))]
20pub struct MakeEditOptions {
21 pub sandbox: Option<Arc<dyn Sandbox>>,
24 pub name: Option<String>,
26 pub description: Option<String>,
28}
29
30impl std::fmt::Debug for MakeEditOptions {
31 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32 f.debug_struct("MakeEditOptions")
33 .field("sandbox", &self.sandbox.is_some())
34 .field("name", &self.name)
35 .field("description", &self.description)
36 .finish()
37 }
38}
39
40fn input_schema() -> JsonSchema {
41 json!({
42 "type": "object",
43 "properties": {
44 "path": {"type": "string", "description": "Absolute path to the file."},
45 "old_str": {"type": "string", "description": "Exact text to find. Must be unique within the file."},
46 "new_str": {"type": "string", "description": "Replacement text."}
47 },
48 "required": ["path", "old_str", "new_str"],
49 "additionalProperties": false
50 })
51}
52
53#[must_use]
55pub fn edit() -> FunctionTool {
56 make_edit(MakeEditOptions::default())
57}
58
59#[must_use]
72pub fn make_edit(options: MakeEditOptions) -> FunctionTool {
73 let name = options.name.unwrap_or_else(|| "edit".to_owned());
74 let description = options
75 .description
76 .unwrap_or_else(|| DEFAULT_EDIT_DESCRIPTION.to_owned());
77 let bound = options.sandbox;
78 FunctionTool::builder(name, description)
79 .input_schema(input_schema())
80 .callback(move |input, context| {
81 let sandbox = resolve_sandbox(bound.as_ref(), &context);
82 async move { run(sandbox.as_ref(), &input).await }
83 })
84}
85
86async fn run(sandbox: &dyn Sandbox, input: &JsonValue) -> Result<JsonValue, ToolError> {
87 let mut reader = InputReader::new(input);
88 let path = reader.string("path");
89 let old_str = reader.string("old_str");
90 let new_str = reader.string("new_str");
91 reader.finish()?;
92 let (path, old_str, new_str) = (
93 path.unwrap_or_default(),
94 old_str.unwrap_or_default(),
95 new_str.unwrap_or_default(),
96 );
97 validate_absolute_path(path)?;
98 if old_str.is_empty() {
99 return Err(ToolError::msg("old_str must not be empty."));
100 }
101 let content = sandbox.read_text(path).await?;
102 let occurrences = content.matches(old_str).count();
103 if occurrences == 0 {
104 return Err(ToolError::msg(format!("old_str did not appear verbatim in {path}.")));
105 }
106 if occurrences > 1 {
107 return Err(ToolError::msg(format!(
108 "old_str appears {occurrences} times in {path}; make it unique."
109 )));
110 }
111 sandbox.write_text(path, &content.replacen(old_str, new_str, 1)).await?;
112 Ok(format!("Edited {path}.").into())
113}
114
115#[cfg(test)]
116mod tests {
117 use super::*;
118 use crate::tools::Tool;
119 use crate::vended_tools::test_support::{agent, error_text};
120
121 #[tokio::test]
122 async fn rejects_a_relative_path() {
123 let input = json!({"path": "relative.txt", "old_str": "a", "new_str": "b"});
124 assert!(error_text(&edit(), input, &agent()).await.contains("not absolute"));
125 }
126
127 #[test]
128 fn defaults_to_the_edit_name_and_description() {
129 assert_eq!(edit().name(), "edit");
130 assert_eq!(edit().description(), DEFAULT_EDIT_DESCRIPTION);
131 }
132
133 #[test]
134 fn applies_name_and_description_overrides_without_a_sandbox() {
135 let custom = make_edit(
136 MakeEditOptions::builder()
137 .name("my_edit")
138 .description("Custom edit.")
139 .build(),
140 );
141 assert_eq!(custom.name(), "my_edit");
142 assert_eq!(custom.description(), "Custom edit.");
143 }
144
145 #[test]
146 fn applies_overrides_when_a_sandbox_is_bound() {
147 let custom = make_edit(MakeEditOptions {
148 sandbox: Some(Arc::new(crate::sandbox::NotASandboxLocalEnvironment::new())),
149 name: Some("sandbox_edit".to_owned()),
150 ..MakeEditOptions::default()
151 });
152 assert_eq!(custom.name(), "sandbox_edit");
153 assert_eq!(custom.description(), DEFAULT_EDIT_DESCRIPTION);
154 }
155
156 #[cfg(unix)]
157 mod host {
158 use super::*;
159 use crate::sandbox::NotASandboxLocalEnvironment;
160 use crate::vended_tools::test_support::{RecordingSandbox, agent_with_sandbox, ok_text};
161
162 fn edit_tool() -> FunctionTool {
163 make_edit(MakeEditOptions {
164 sandbox: Some(Arc::new(NotASandboxLocalEnvironment::new())),
165 ..MakeEditOptions::default()
166 })
167 }
168
169 fn file(dir: &tempfile::TempDir, content: &str) -> String {
170 let path = dir.path().join("f.txt");
171 std::fs::write(&path, content).unwrap();
172 path.to_string_lossy().into_owned()
173 }
174
175 fn contents(path: &str) -> String {
176 std::fs::read_to_string(path).unwrap()
177 }
178
179 fn input(path: &str, old_str: &str, new_str: &str) -> JsonValue {
180 json!({"path": path, "old_str": old_str, "new_str": new_str})
181 }
182
183 #[tokio::test]
184 async fn replaces_a_unique_match() {
185 let dir = tempfile::tempdir().unwrap();
186 let path = file(&dir, "alpha\nbeta\ngamma");
187 let message = ok_text(&edit_tool(), input(&path, "beta", "BETA"), &agent()).await;
188 assert_eq!(message, format!("Edited {path}."));
189 assert_eq!(contents(&path), "alpha\nBETA\ngamma");
190 }
191
192 #[tokio::test]
193 async fn rejects_an_empty_old_str() {
194 let dir = tempfile::tempdir().unwrap();
195 let path = file(&dir, "alpha");
196 let message = error_text(&edit_tool(), input(&path, "", "x"), &agent()).await;
197 assert!(message.contains("old_str must not be empty"));
198 }
199
200 #[tokio::test]
201 async fn rejects_a_missing_match() {
202 let dir = tempfile::tempdir().unwrap();
203 let path = file(&dir, "alpha\nbeta");
204 let message = error_text(&edit_tool(), input(&path, "zeta", "x"), &agent()).await;
205 assert!(message.contains("did not appear verbatim"));
206 }
207
208 #[tokio::test]
209 async fn rejects_an_ambiguous_match_and_leaves_the_file_untouched() {
210 let dir = tempfile::tempdir().unwrap();
211 let path = file(&dir, "foo\nfoo\nfoo");
212 let message = error_text(&edit_tool(), input(&path, "foo", "bar"), &agent()).await;
213 assert!(message.contains("appears 3 times"));
214 assert_eq!(contents(&path), "foo\nfoo\nfoo");
215 }
216
217 #[tokio::test]
218 async fn deletes_the_match_when_new_str_is_empty() {
219 let dir = tempfile::tempdir().unwrap();
220 let path = file(&dir, "keep\nremove-me\nkeep");
221 ok_text(&edit_tool(), input(&path, "remove-me\n", ""), &agent()).await;
222 assert_eq!(contents(&path), "keep\nkeep");
223 }
224
225 #[tokio::test]
226 async fn replaces_a_multiline_old_str() {
227 let dir = tempfile::tempdir().unwrap();
228 let path = file(&dir, "a\nb\nc\nd");
229 ok_text(&edit_tool(), input(&path, "b\nc", "B\nC\nC2"), &agent()).await;
230 assert_eq!(contents(&path), "a\nB\nC\nC2\nd");
231 }
232
233 #[tokio::test]
234 async fn inserts_replacement_patterns_in_new_str_literally() {
235 let dir = tempfile::tempdir().unwrap();
236 let path = file(&dir, "x = 1");
237 ok_text(&edit_tool(), input(&path, "1", "$& $1 $$"), &agent()).await;
238 assert_eq!(contents(&path), "x = $& $1 $$");
239 }
240
241 #[tokio::test]
242 async fn uses_the_bound_sandbox_over_the_agent_sandbox() {
243 let dir = tempfile::tempdir().unwrap();
244 let path = file(&dir, "x");
245 let exploding = agent_with_sandbox(Arc::new(RecordingSandbox::default()));
246 ok_text(&edit_tool(), input(&path, "x", "y"), &exploding).await;
247 assert_eq!(contents(&path), "y");
248 }
249
250 #[tokio::test]
251 async fn default_edit_reads_the_agent_sandbox() {
252 let dir = tempfile::tempdir().unwrap();
253 let path = file(&dir, "hello");
254 ok_text(&edit(), input(&path, "hello", "world"), &agent()).await;
255 assert_eq!(contents(&path), "world");
256 }
257 }
258}