1use std::sync::Arc;
4
5use adk_core::{Result, Tool, ToolContext};
6use async_trait::async_trait;
7use serde_json::{Value, json};
8
9use crate::error::DevToolError;
10use crate::read_ledger::sha256_hex;
11use crate::tools::read::require_str;
12use crate::workspace::{Precondition, Workspace};
13
14pub struct EditFileTool {
38 workspace: Workspace,
39}
40
41impl EditFileTool {
42 pub fn new(workspace: Workspace) -> Self {
44 Self { workspace }
45 }
46}
47
48struct Replacement {
50 old_string: String,
51 new_string: String,
52 replace_all: bool,
53}
54
55fn replacements(args: &Value) -> Result<Vec<Replacement>> {
57 let invalid = |message: String| -> adk_core::AdkError { DevToolError::Other(message).into() };
58 let Some(edits) = args.get("edits").filter(|edits| !edits.is_null()) else {
59 return Ok(vec![Replacement {
60 old_string: require_str(args, "old_string")?,
61 new_string: require_str(args, "new_string")?,
62 replace_all: args.get("replace_all").and_then(Value::as_bool).unwrap_or(false),
63 }]);
64 };
65 if args.get("old_string").is_some() || args.get("new_string").is_some() {
66 return Err(invalid(
67 "pass either old_string and new_string, or edits, not both".to_string(),
68 ));
69 }
70 let Some(edits) = edits.as_array().filter(|edits| !edits.is_empty()) else {
71 return Err(invalid("edits must be a non-empty array".to_string()));
72 };
73 edits
74 .iter()
75 .enumerate()
76 .map(|(index, edit)| {
77 let field = |key: &str| {
78 edit.get(key)
79 .and_then(Value::as_str)
80 .map(str::to_string)
81 .ok_or_else(|| invalid(format!("edits[{index}] needs a string '{key}'")))
82 };
83 Ok(Replacement {
84 old_string: field("old_string")?,
85 new_string: field("new_string")?,
86 replace_all: edit.get("replace_all").and_then(Value::as_bool).unwrap_or(false),
87 })
88 })
89 .collect()
90}
91
92pub(crate) fn apply_replacements(
95 original: &str,
96 replacements: &[(&str, &str, bool)],
97 display: &str,
98) -> std::result::Result<(String, usize), DevToolError> {
99 let mut updated = original.to_string();
100 let mut total = 0;
101 let several = replacements.len() > 1;
102 for (index, (old_string, new_string, replace_all)) in replacements.iter().enumerate() {
103 let label =
104 if several { format!("{display} (edits[{index}])") } else { display.to_string() };
105 if old_string.is_empty() {
106 return Err(DevToolError::Other(format!(
107 "the target string of {label} is empty; give the exact text to replace"
108 )));
109 }
110 let count = updated.matches(old_string).count();
111 if count == 0 {
112 return Err(DevToolError::NoMatch(label));
113 }
114 if count > 1 && !replace_all {
115 return Err(DevToolError::Ambiguous { path: label, count });
116 }
117 updated = if *replace_all {
118 updated.replace(old_string, new_string)
119 } else {
120 updated.replacen(old_string, new_string, 1)
121 };
122 total += if *replace_all { count } else { 1 };
123 }
124 Ok((updated, total))
125}
126
127pub fn preview(original: &str, args: &Value, display: &str) -> Result<String> {
147 let replacements = replacements(args)?;
148 let pairs: Vec<(&str, &str, bool)> = replacements
149 .iter()
150 .map(|r| (r.old_string.as_str(), r.new_string.as_str(), r.replace_all))
151 .collect();
152 Ok(apply_replacements(original, &pairs, display)?.0)
153}
154
155#[async_trait]
156impl Tool for EditFileTool {
157 fn name(&self) -> &str {
158 "edit_file"
159 }
160
161 fn egress(&self, _args: &serde_json::Value) -> adk_core::egress::ToolEgress {
163 adk_core::egress::ToolEgress::None
164 }
165
166 fn description(&self) -> &str {
167 "Replace exact strings in a file. The file must have been read with read_file first \
168 and be unchanged since; if it changed, read it again. Give old_string and \
169 new_string for one replacement, or edits for several in one file, applied in order \
170 and all or none. Each target string must occur exactly once unless replace_all is \
171 true."
172 }
173
174 fn parameters_schema(&self) -> Option<Value> {
175 Some(json!({
176 "type": "object",
177 "properties": {
178 "path": { "type": "string", "description": "Path relative to the workspace root." },
179 "old_string": { "type": "string", "description": "The exact text to replace (with new_string; omit when using edits)." },
180 "new_string": { "type": "string", "description": "The replacement text." },
181 "replace_all": { "type": "boolean", "description": "Replace all occurrences (default false)." },
182 "edits": {
183 "type": "array",
184 "description": "Several replacements in this file, applied in order; all apply or none do.",
185 "items": {
186 "type": "object",
187 "properties": {
188 "old_string": { "type": "string" },
189 "new_string": { "type": "string" },
190 "replace_all": { "type": "boolean" }
191 },
192 "required": ["old_string", "new_string"]
193 }
194 },
195 "expect_sha256": { "type": "string", "description": "Optional: the sha256 the file must have; the edit is refused if it differs." }
196 },
197 "required": ["path"]
198 }))
199 }
200
201 async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
202 if !self.workspace.is_writable() {
203 return Err(DevToolError::ReadOnly("edit_file").into());
204 }
205 let path = require_str(&args, "path")?;
206 let replacements = replacements(&args)?;
207 let expect = match args.get("expect_sha256").and_then(Value::as_str) {
208 Some(expect) => Some(Precondition::from_expect(expect)?),
209 None => None,
210 };
211
212 let (resolved, target) = self.workspace.resolve_target(&path)?;
213 let display = self.workspace.display(&resolved);
214 let expected = match expect {
216 Some(Precondition::Sha256(digest)) => digest,
217 Some(Precondition::Absent | Precondition::Any) => {
218 return Err(DevToolError::Other(format!(
219 "edit_file changes an existing file; '{display}' cannot be expected absent"
220 ))
221 .into());
222 }
223 None => match self.workspace.read_digest(ctx.as_ref(), &resolved).await? {
224 Some(digest) => digest,
225 None => return Err(DevToolError::NotRead(display).into()),
226 },
227 };
228
229 let original = self.workspace.read_contained(&target).await?;
230 let found = sha256_hex(original.as_bytes());
231 if found != expected {
232 return Err(DevToolError::Stale {
233 path: display,
234 detail: crate::workspace::StaleFile::Changed { expected, found }.to_string(),
235 }
236 .into());
237 }
238 let pairs: Vec<(&str, &str, bool)> = replacements
239 .iter()
240 .map(|r| (r.old_string.as_str(), r.new_string.as_str(), r.replace_all))
241 .collect();
242 let (updated, count) = apply_replacements(&original, &pairs, &display)?;
243 self.workspace
244 .write_contained(&target, updated.as_bytes(), Precondition::Sha256(found))
245 .await?;
246 self.workspace
247 .record_digest(ctx.as_ref(), &resolved, &sha256_hex(updated.as_bytes()))
248 .await;
249
250 Ok(json!({
251 "path": display,
252 "replacements": count,
253 "message": format!("Replaced {count} occurrence(s) in {display}"),
254 }))
255 }
256}
257
258#[cfg(test)]
259mod tests {
260 use super::*;
261
262 #[test]
263 fn replacements_apply_in_order_and_name_the_one_that_failed() {
264 let (out, count) =
265 apply_replacements("a b c", &[("a", "x", false), ("x b", "y", false)], "f").unwrap();
266 assert_eq!((out.as_str(), count), ("y c", 2));
267 let error =
268 apply_replacements("a b", &[("a", "x", false), ("zzz", "y", false)], "f").unwrap_err();
269 assert!(matches!(&error, DevToolError::NoMatch(label) if label == "f (edits[1])"));
270 let error = apply_replacements("a a", &[("a", "b", false)], "f").unwrap_err();
271 assert!(matches!(error, DevToolError::Ambiguous { count: 2, .. }));
272 let (out, count) = apply_replacements("a a", &[("a", "b", true)], "f").unwrap();
273 assert_eq!((out.as_str(), count), ("b b", 2));
274 }
275
276 #[test]
277 fn edits_and_a_single_pair_are_exclusive() {
278 let both = json!({ "path": "f", "old_string": "a", "new_string": "b",
279 "edits": [{ "old_string": "a", "new_string": "b" }] });
280 assert!(replacements(&both).is_err());
281 assert!(replacements(&json!({ "path": "f", "edits": [] })).is_err());
282 let several = json!({ "path": "f", "edits": [
283 { "old_string": "a", "new_string": "b" },
284 { "old_string": "c", "new_string": "d", "replace_all": true }
285 ] });
286 let parsed = replacements(&several).unwrap();
287 assert_eq!(parsed.len(), 2);
288 assert!(parsed[1].replace_all);
289 }
290}