1use std::sync::Arc;
6
7use async_trait::async_trait;
8use serde_json::{Value, json};
9
10use aidaemon_core::{AccessManifest, ToolAnnotations};
11
12use super::{FilePolicy, SharedBackend, ToolText, path_arg, workspace_parts};
13use crate::backend::WriteMode;
14use crate::outcome::{OutcomeTool, core_tool};
15use crate::semantics::{
16 ToolCallContext, ToolCallOutcome, ToolCallSemantics, ToolCapabilities, ToolMutationEffects,
17 ToolRole, ToolTargetHintKind,
18};
19use crate::workspace::Workspace;
20
21pub struct EditFile {
22 backend: SharedBackend,
23 policy: Arc<dyn FilePolicy>,
24 text: ToolText,
25}
26
27impl EditFile {
28 pub fn new(workspace: Workspace) -> Self {
30 let (backend, policy) = workspace_parts(workspace);
31 Self::on_backend(backend, policy)
32 }
33
34 pub fn on_backend(backend: SharedBackend, policy: Arc<dyn FilePolicy>) -> Self {
36 Self {
37 backend,
38 policy,
39 text: ToolText {
40 short: "Find and replace text in a file".into(),
41 schema: "Find and replace text in a file. Fails without changing anything when the text is not found or is ambiguous; read the file again and retry. For several changes to one file, pass `edits`: applied in order, all or nothing.".into(),
42 },
43 }
44 }
45
46 pub fn with_text(mut self, text: ToolText) -> Self {
48 self.text = text;
49 self
50 }
51}
52
53const OLD_KEYS: [&str; 4] = ["old_text", "old_string", "search", "find"];
56const NEW_KEYS: [&str; 4] = ["new_text", "new_string", "replace", "replacement"];
57
58fn text_arg<'a>(value: &'a Value, keys: [&str; 4]) -> Option<&'a str> {
59 keys.iter()
60 .find_map(|key| value.get(*key).and_then(Value::as_str))
61}
62
63struct EditArg {
65 old_text: String,
66 new_text: String,
67 replace_all: bool,
68}
69
70struct EditRequest {
73 edits: Vec<EditArg>,
74 batch: bool,
75}
76
77impl EditRequest {
78 fn parse(args: &Value) -> Result<Self, String> {
80 let replace_all = |value: &Value| {
81 value
82 .get("replace_all")
83 .and_then(Value::as_bool)
84 .unwrap_or(false)
85 };
86 let Some(list) = args.get("edits").filter(|value| !value.is_null()) else {
87 let old_text = text_arg(args, OLD_KEYS)
88 .ok_or("Missing required parameter: old_text (or `edits`)")?;
89 let new_text =
90 text_arg(args, NEW_KEYS).ok_or("Missing required parameter: new_text")?;
91 return Ok(Self {
92 edits: vec![EditArg {
93 old_text: old_text.to_string(),
94 new_text: new_text.to_string(),
95 replace_all: replace_all(args),
96 }],
97 batch: false,
98 });
99 };
100 if text_arg(args, OLD_KEYS).is_some() || text_arg(args, NEW_KEYS).is_some() {
101 return Err("Give either `edits` or `old_text`/`new_text`, not both".into());
102 }
103 let list = list
104 .as_array()
105 .ok_or("`edits` must be a list of {old_text, new_text, replace_all?}")?;
106 if list.is_empty() {
107 return Err("`edits` is empty; nothing to change".into());
108 }
109 let edits = list
110 .iter()
111 .enumerate()
112 .map(|(index, edit)| {
113 let n = index + 1;
114 let old_text = text_arg(edit, OLD_KEYS)
115 .ok_or_else(|| format!("Edit {n} is missing `old_text`"))?;
116 let new_text = text_arg(edit, NEW_KEYS)
117 .ok_or_else(|| format!("Edit {n} is missing `new_text`"))?;
118 Ok(EditArg {
119 old_text: old_text.to_string(),
120 new_text: new_text.to_string(),
121 replace_all: replace_all(edit),
122 })
123 })
124 .collect::<Result<Vec<_>, String>>()?;
125 Ok(Self { edits, batch: true })
126 }
127
128 fn prefix(&self, index: usize) -> String {
130 if self.batch {
131 format!("Edit {} of {}: ", index + 1, self.edits.len())
132 } else {
133 String::new()
134 }
135 }
136}
137
138struct AppliedEdit {
140 new_content: String,
141 count: usize,
143 effective_new_text: String,
144 used_newline_recovery: bool,
145}
146
147struct AppliedEdits {
149 new_content: String,
150 replaced: usize,
152 new_texts: Vec<String>,
154 used_newline_recovery: bool,
155}
156
157fn apply_edits(
162 bytes: &[u8],
163 path_str: &str,
164 request: &EditRequest,
165) -> anyhow::Result<AppliedEdits> {
166 if bytes.iter().take(8192).any(|byte| *byte == 0) {
167 anyhow::bail!("Cannot edit binary file: {}", path_str);
168 }
169 let mut content = std::str::from_utf8(bytes)
170 .map_err(|_| anyhow::anyhow!("Cannot edit non-UTF-8 file: {}", path_str))?
171 .to_string();
172 let mut applied_all = AppliedEdits {
173 new_content: String::new(),
174 replaced: 0,
175 new_texts: Vec::with_capacity(request.edits.len()),
176 used_newline_recovery: false,
177 };
178 for (index, edit) in request.edits.iter().enumerate() {
179 let applied = apply_edit(&content, path_str, edit).map_err(|why| {
180 if request.batch {
181 anyhow::anyhow!(
182 "{}failed, so no edit was written. {}",
183 request.prefix(index),
184 why
185 )
186 } else {
187 why
188 }
189 })?;
190 applied_all.replaced += if edit.replace_all { applied.count } else { 1 };
191 applied_all.used_newline_recovery |= applied.used_newline_recovery;
192 applied_all.new_texts.push(applied.effective_new_text);
193 content = applied.new_content;
194 }
195 applied_all.new_content = content;
196 Ok(applied_all)
197}
198
199fn apply_edit(content: &str, path_str: &str, edit: &EditArg) -> anyhow::Result<AppliedEdit> {
201 let (old_text, new_text, replace_all) = (
202 edit.old_text.as_str(),
203 edit.new_text.as_str(),
204 edit.replace_all,
205 );
206
207 let mut effective_old_text = old_text.to_string();
209 let mut effective_new_text = new_text.to_string();
210 let mut count = content.matches(&effective_old_text).count();
211
212 if count == 0 {
215 let file_newline = detect_newline_style(content);
216 let normalized_old = normalize_newlines_for_style(old_text, file_newline);
217 if normalized_old != old_text {
218 let normalized_count = content.matches(&normalized_old).count();
219 if normalized_count > 0 {
220 effective_old_text = normalized_old;
221 effective_new_text = normalize_newlines_for_style(new_text, file_newline);
222 count = normalized_count;
223 }
224 }
225 }
226
227 if count == 0 {
228 anyhow::bail!("{}", build_not_found_message(path_str, content, old_text));
229 }
230
231 if count > 1 && !replace_all {
232 anyhow::bail!(
233 "Found {} occurrences of the text in {}. Set replace_all=true to replace all, or provide more context to make old_text unique.",
234 count,
235 path_str
236 );
237 }
238
239 let new_content = if replace_all {
240 content.replace(&effective_old_text, &effective_new_text)
241 } else {
242 content.replacen(&effective_old_text, &effective_new_text, 1)
243 };
244 Ok(AppliedEdit {
245 new_content,
246 count,
247 used_newline_recovery: effective_old_text != old_text,
248 effective_new_text,
249 })
250}
251
252#[async_trait]
253impl OutcomeTool for EditFile {
254 fn name(&self) -> &str {
255 "edit_file"
256 }
257
258 fn description(&self) -> &str {
259 &self.text.short
260 }
261
262 fn schema(&self) -> Value {
263 json!({
264 "name": "edit_file",
265 "description": self.text.schema,
266 "parameters": {
267 "type": "object",
268 "properties": {
269 "path": {
270 "type": "string",
271 "description": "Path to the file (supports ~ expansion)"
272 },
273 "old_text": {
274 "type": "string",
275 "description": "Exact text to find and replace"
276 },
277 "new_text": {
278 "type": "string",
279 "description": "Text to replace with"
280 },
281 "replace_all": {
282 "type": "boolean",
283 "description": "Replace all occurrences (default: false, errors if multiple found)"
284 },
285 "edits": {
286 "type": "array",
287 "description": "Several edits, in place of old_text/new_text; each applies to the result of the one before",
288 "items": {
289 "type": "object",
290 "properties": {
291 "old_text": {
292 "type": "string",
293 "description": "Exact text to find"
294 },
295 "new_text": {
296 "type": "string",
297 "description": "Text to replace with"
298 },
299 "replace_all": {
300 "type": "boolean",
301 "description": "Replace all occurrences (default: false)"
302 }
303 },
304 "required": ["old_text", "new_text"],
305 "additionalProperties": false
306 }
307 }
308 },
309 "required": ["path"],
310 "additionalProperties": false
311 }
312 })
313 }
314
315 async fn execute(
316 &self,
317 arguments: &str,
318 facts: &ToolCallContext,
319 ) -> anyhow::Result<ToolCallOutcome> {
320 let args: Value = serde_json::from_str(arguments)?;
321
322 let path_str = super::path_arg(&args)
323 .ok_or_else(|| anyhow::anyhow!("Missing required parameter: path"))?;
324 let request = EditRequest::parse(&args).map_err(|why| anyhow::anyhow!(why))?;
325
326 let backend = self.backend.clone();
327 let path = backend.resolve_path(path_str).await?;
328
329 if backend.metadata(&path).await.is_err() {
330 return Err(crate::TargetNotFound(format!("File not found: {path_str}")).into());
331 }
332
333 let write_guard = match crate::semantics::file_fence(facts) {
335 Some(fence) => Some(
336 fence
337 .begin_write(path_str)
338 .await
339 .map_err(|why| anyhow::anyhow!(why))?,
340 ),
341 None => None,
342 };
343
344 let bytes = backend.read(&path).await?;
345 let AppliedEdits {
346 new_content,
347 replaced,
348 new_texts,
349 used_newline_recovery,
350 } = apply_edits(&bytes, path_str, &request)?;
351
352 self.policy.backup_before_overwrite(&backend, &path).await;
354 backend
355 .write(&path, new_content.as_bytes(), WriteMode::Overwrite, false)
356 .await?;
357 if let Some(write_guard) = write_guard {
358 write_guard.committed().await;
359 }
360
361 const SHOWN_EDITS: usize = 5;
363 let mut context = new_texts
364 .iter()
365 .take(SHOWN_EDITS)
366 .map(|new_text| get_change_context(&new_content, new_text))
367 .collect::<Vec<_>>()
368 .join("\n ...\n");
369 if new_texts.len() > SHOWN_EDITS {
370 context.push_str(&format!(
371 "\n(and {} more edits)",
372 new_texts.len() - SHOWN_EDITS
373 ));
374 }
375 let edits = if request.batch {
376 format!("applied {} edits, ", request.edits.len())
377 } else {
378 String::new()
379 };
380 let diagnostics = self
381 .policy
382 .post_write_diagnostics(&*backend, std::path::Path::new(path.as_str()))
383 .await;
384
385 Ok(ToolCallOutcome::from_output(format!(
386 "Edited {}: {}replaced {} occurrence{}{}\n\n{}{}",
387 path_str,
388 edits,
389 replaced,
390 if replaced > 1 { "s" } else { "" },
391 if used_newline_recovery {
392 " (newline-normalized match)"
393 } else {
394 ""
395 },
396 context,
397 diagnostics
398 )))
399 }
400
401 fn validate_call(&self, arguments: &Value) -> Result<(), String> {
402 let request = EditRequest::parse(arguments)?;
403 for (index, edit) in request.edits.iter().enumerate() {
404 let prefix = request.prefix(index);
405 if edit.old_text.is_empty() {
406 return Err(format!(
407 "{prefix}`old_text` must not be empty; use write_file to create a file"
408 ));
409 }
410 if edit.old_text == edit.new_text {
411 return Err(format!(
412 "{prefix}`old_text` and `new_text` are identical; nothing to change"
413 ));
414 }
415 }
416 Ok(())
417 }
418}
419
420core_tool!(
421 EditFile,
422 annotations: ToolAnnotations::WRITE,
423 access: |this, arguments| {
424 let paths: Vec<String> = path_arg(arguments)
425 .map(|path| vec![this.policy.declare_path(path)])
426 .unwrap_or_default();
427 AccessManifest {
428 reads: paths.clone(),
429 writes: paths,
430 ..Default::default()
431 }
432 }
433);
434
435#[async_trait]
436impl crate::semantics::ToolSemantics for EditFile {
437 fn dispatch_facts(&self) -> crate::semantics::ToolDispatchFacts {
438 crate::semantics::ToolDispatchFacts {
439 offering: crate::semantics::Offering::Core,
440 checkpoints_writes: true,
441 file_guard: crate::semantics::FileGuard::Writes,
442 recap: crate::semantics::RecapKind::FileWrite,
443 activity: crate::semantics::ToolActivity::Fixed(
444 aidaemon_core::card::ActivityKind::Write,
445 ),
446 opens_project_instructions: true,
447 semantic_scope: Some(crate::semantics::ToolSemanticScope::LocalWorkspace),
448 low_signal_result: true,
449 status_label: Some("editing a file"),
450 evidence: crate::semantics::EvidenceSource::FileWrite,
451 ..Default::default()
452 }
453 }
454
455 fn tool_role(&self) -> ToolRole {
456 ToolRole::Action
457 }
458
459 fn capabilities(&self) -> ToolCapabilities {
460 ToolCapabilities {
461 read_only: false,
462 external_side_effect: false,
463 needs_approval: false,
464 idempotent: false,
465 high_impact_write: false,
469 }
470 }
471
472 fn call_semantics(&self, arguments: &str) -> ToolCallSemantics {
473 let path = serde_json::from_str::<Value>(arguments)
474 .ok()
475 .and_then(|args| {
476 for key in ["path", "file_path", "file", "filename"] {
477 if let Some(path) = args.get(key).and_then(|value| value.as_str()) {
478 return Some(path.to_string());
479 }
480 }
481 None
482 })
483 .unwrap_or_default();
484
485 ToolCallSemantics::observation_and_mutation_with(ToolMutationEffects::LOCAL_SOURCE_WRITE)
489 .with_target_hint(ToolTargetHintKind::Path, path)
490 }
491
492 fn call_file_write(&self, arguments: &str) -> Option<crate::semantics::FileWrite> {
493 let args: Value = serde_json::from_str(arguments).ok()?;
494 let request = EditRequest::parse(&args).ok()?;
495 let kind = if request.batch {
496 crate::semantics::FileWriteKind::Edits(
497 request
498 .edits
499 .into_iter()
500 .map(|edit| crate::semantics::TextEdit {
501 old_text: edit.old_text,
502 replace_all: edit.replace_all,
503 })
504 .collect(),
505 )
506 } else {
507 let edit = request.edits.into_iter().next()?;
508 crate::semantics::FileWriteKind::Edit {
509 old_text: edit.old_text,
510 replace_all: edit.replace_all,
511 }
512 };
513 Some(crate::semantics::FileWrite {
514 path: path_arg(&args)?.to_string(),
515 kind,
516 })
517 }
518
519 fn file_write_result(
520 &self,
521 arguments: &str,
522 current: Option<&[u8]>,
523 ) -> Option<Result<Vec<u8>, String>> {
524 let args: Value = serde_json::from_str(arguments).ok()?;
525 let path = path_arg(&args)?;
526 let request = EditRequest::parse(&args).ok()?;
527 let Some(current) = current else {
528 return Some(Err(format!("File not found: {path}")));
529 };
530 Some(
531 apply_edits(current, path, &request)
532 .map(|applied| applied.new_content.into_bytes())
533 .map_err(|why| why.to_string()),
534 )
535 }
536
537 fn call_effects(&self, arguments: &str) -> aidaemon_core::CallEffects {
540 self.policy.write_effects(&*self.backend, arguments)
541 }
542
543 async fn owner_approval_request(
546 &self,
547 call: &crate::semantics::ApprovalCall<'_>,
548 facts: &ToolCallContext,
549 ) -> crate::semantics::OwnerApprovalNeed {
550 super::persistence_write_approval(
551 &self.backend,
552 &*self.policy,
553 "edit_file",
554 call.arguments,
555 self.call_effects(&call.arguments.to_string()),
556 facts,
557 )
558 .await
559 }
560
561 fn call_annotations_in(
562 &self,
563 arguments: &str,
564 _roots: &crate::semantics::TrustRoots<'_>,
565 ) -> aidaemon_core::ToolAnnotations {
566 let semantics = self.call_semantics(arguments);
567 super::write_call_annotations(self.capabilities(), &semantics, &*self.policy)
568 }
569}
570
571fn detect_newline_style(content: &str) -> &'static str {
572 let crlf_count = content.matches("\r\n").count();
573 let lf_total = content.matches('\n').count();
574 let lf_only_count = lf_total.saturating_sub(crlf_count);
575 if crlf_count > lf_only_count {
576 "\r\n"
577 } else {
578 "\n"
579 }
580}
581
582fn normalize_newlines_for_style(input: &str, newline: &str) -> String {
583 let normalized = input.replace("\r\n", "\n").replace('\r', "\n");
584 if newline == "\r\n" {
585 normalized.replace('\n', "\r\n")
586 } else {
587 normalized
588 }
589}
590
591fn truncate_with_ellipsis(input: &str, max_chars: usize) -> String {
592 if input.chars().count() <= max_chars {
593 return input.to_string();
594 }
595 let mut out: String = input.chars().take(max_chars).collect();
596 out.push_str("...");
597 out
598}
599
600fn build_file_preview(content: &str, max_lines: usize, max_chars: usize) -> String {
601 if content.is_empty() {
602 return "(file is empty)".to_string();
603 }
604
605 let mut preview_lines = Vec::new();
606 for (idx, line) in content.lines().take(max_lines).enumerate() {
607 preview_lines.push(format!("{:>4} | {}", idx + 1, line));
608 }
609
610 let total_lines = content.lines().count();
611 if total_lines > max_lines {
612 preview_lines.push(format!("... ({} more lines)", total_lines - max_lines));
613 }
614
615 let joined = preview_lines.join("\n");
616 truncate_with_ellipsis(&joined, max_chars)
617}
618
619fn build_not_found_message(path: &str, content: &str, old_text: &str) -> String {
620 let first_non_empty_old = old_text
621 .lines()
622 .find(|line| !line.trim().is_empty())
623 .unwrap_or(old_text)
624 .trim();
625 let old_hint = if first_non_empty_old.is_empty() {
626 "old_text appears empty or whitespace-only.".to_string()
627 } else {
628 format!(
629 "old_text first non-empty line: `{}`",
630 truncate_with_ellipsis(first_non_empty_old, 120)
631 )
632 };
633
634 let preview = build_file_preview(content, 40, 3500);
635 format!(
636 "Text not found in {}. The old_text must match exactly (including whitespace and indentation).\n\
637{}\n\n\
638Self-recovery steps:\n\
6391. Call read_file on the same path.\n\
6402. Copy the exact block from the file output into old_text and retry edit_file.\n\
6413. If the goal is replacing the whole file, use write_file instead of edit_file.\n\n\
642File preview:\n{}",
643 path, old_hint, preview
644 )
645}
646
647fn get_change_context(content: &str, new_text: &str) -> String {
649 let lines: Vec<&str> = content.lines().collect();
650 let new_text_first_line = new_text.lines().next().unwrap_or(new_text);
651
652 if let Some(idx) = lines.iter().position(|l| l.contains(new_text_first_line)) {
654 let start = idx.saturating_sub(2);
655 let end = (idx + new_text.lines().count() + 2).min(lines.len());
656 let context_lines: Vec<String> = lines[start..end]
657 .iter()
658 .enumerate()
659 .map(|(i, line)| format!("{:>4} | {}", start + i + 1, line))
660 .collect();
661 context_lines.join("\n")
662 } else {
663 String::from("(change context not available)")
664 }
665}