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 = args["path"]
324 .as_str()
325 .or_else(|| args["file_path"].as_str())
326 .or_else(|| args["file"].as_str())
327 .or_else(|| args["filename"].as_str())
328 .ok_or_else(|| anyhow::anyhow!("Missing required parameter: path"))?;
329 let request = EditRequest::parse(&args).map_err(|why| anyhow::anyhow!(why))?;
330
331 let backend = self.backend.clone();
332 let path = backend.resolve_path(path_str).await?;
333
334 if backend.metadata(&path).await.is_err() {
335 return Err(crate::TargetNotFound(format!("File not found: {path_str}")).into());
336 }
337
338 let write_guard = match crate::semantics::file_fence(facts) {
340 Some(fence) => Some(
341 fence
342 .begin_write(path_str)
343 .await
344 .map_err(|why| anyhow::anyhow!(why))?,
345 ),
346 None => None,
347 };
348
349 let bytes = backend.read(&path).await?;
350 let AppliedEdits {
351 new_content,
352 replaced,
353 new_texts,
354 used_newline_recovery,
355 } = apply_edits(&bytes, path_str, &request)?;
356
357 self.policy.backup_before_overwrite(&backend, &path).await;
359 backend
360 .write(&path, new_content.as_bytes(), WriteMode::Overwrite, false)
361 .await?;
362 if let Some(write_guard) = write_guard {
363 write_guard.committed().await;
364 }
365
366 const SHOWN_EDITS: usize = 5;
368 let mut context = new_texts
369 .iter()
370 .take(SHOWN_EDITS)
371 .map(|new_text| get_change_context(&new_content, new_text))
372 .collect::<Vec<_>>()
373 .join("\n ...\n");
374 if new_texts.len() > SHOWN_EDITS {
375 context.push_str(&format!(
376 "\n(and {} more edits)",
377 new_texts.len() - SHOWN_EDITS
378 ));
379 }
380 let edits = if request.batch {
381 format!("applied {} edits, ", request.edits.len())
382 } else {
383 String::new()
384 };
385 let diagnostics = self
386 .policy
387 .post_write_diagnostics(&*backend, std::path::Path::new(path.as_str()))
388 .await;
389
390 Ok(ToolCallOutcome::from_output(format!(
391 "Edited {}: {}replaced {} occurrence{}{}\n\n{}{}",
392 path_str,
393 edits,
394 replaced,
395 if replaced > 1 { "s" } else { "" },
396 if used_newline_recovery {
397 " (newline-normalized match)"
398 } else {
399 ""
400 },
401 context,
402 diagnostics
403 )))
404 }
405
406 fn validate_call(&self, arguments: &Value) -> Result<(), String> {
407 let request = EditRequest::parse(arguments)?;
408 for (index, edit) in request.edits.iter().enumerate() {
409 let prefix = request.prefix(index);
410 if edit.old_text.is_empty() {
411 return Err(format!(
412 "{prefix}`old_text` must not be empty; use write_file to create a file"
413 ));
414 }
415 if edit.old_text == edit.new_text {
416 return Err(format!(
417 "{prefix}`old_text` and `new_text` are identical; nothing to change"
418 ));
419 }
420 }
421 Ok(())
422 }
423}
424
425core_tool!(
426 EditFile,
427 annotations: ToolAnnotations::WRITE,
428 access: |this, arguments| {
429 let paths: Vec<String> = path_arg(arguments)
430 .map(|path| vec![this.policy.declare_path(path)])
431 .unwrap_or_default();
432 AccessManifest {
433 reads: paths.clone(),
434 writes: paths,
435 ..Default::default()
436 }
437 }
438);
439
440impl crate::semantics::ToolSemantics for EditFile {
441 fn dispatch_facts(&self) -> crate::semantics::ToolDispatchFacts {
442 crate::semantics::ToolDispatchFacts {
443 offering: crate::semantics::Offering::Core,
444 checkpoints_writes: true,
445 file_guard: crate::semantics::FileGuard::Writes,
446 recap: crate::semantics::RecapKind::FileWrite,
447 activity: crate::semantics::ToolActivity::Fixed(
448 aidaemon_core::card::ActivityKind::Write,
449 ),
450 opens_project_instructions: true,
451 semantic_scope: Some(crate::semantics::ToolSemanticScope::LocalWorkspace),
452 low_signal_result: true,
453 status_label: Some("editing a file"),
454 evidence: crate::semantics::EvidenceSource::FileWrite,
455 ..Default::default()
456 }
457 }
458
459 fn tool_role(&self) -> ToolRole {
460 ToolRole::Action
461 }
462
463 fn capabilities(&self) -> ToolCapabilities {
464 ToolCapabilities {
465 read_only: false,
466 external_side_effect: false,
467 needs_approval: false,
468 idempotent: false,
469 high_impact_write: false,
473 }
474 }
475
476 fn call_semantics(&self, arguments: &str) -> ToolCallSemantics {
477 let path = serde_json::from_str::<Value>(arguments)
478 .ok()
479 .and_then(|args| {
480 for key in ["path", "file_path", "file", "filename"] {
481 if let Some(path) = args.get(key).and_then(|value| value.as_str()) {
482 return Some(path.to_string());
483 }
484 }
485 None
486 })
487 .unwrap_or_default();
488
489 ToolCallSemantics::observation_and_mutation_with(ToolMutationEffects::LOCAL_SOURCE_WRITE)
493 .with_target_hint(ToolTargetHintKind::Path, path)
494 }
495
496 fn call_file_write(&self, arguments: &str) -> Option<crate::semantics::FileWrite> {
497 let args: Value = serde_json::from_str(arguments).ok()?;
498 let request = EditRequest::parse(&args).ok()?;
499 let kind = if request.batch {
500 crate::semantics::FileWriteKind::Edits(
501 request
502 .edits
503 .into_iter()
504 .map(|edit| crate::semantics::TextEdit {
505 old_text: edit.old_text,
506 replace_all: edit.replace_all,
507 })
508 .collect(),
509 )
510 } else {
511 let edit = request.edits.into_iter().next()?;
512 crate::semantics::FileWriteKind::Edit {
513 old_text: edit.old_text,
514 replace_all: edit.replace_all,
515 }
516 };
517 Some(crate::semantics::FileWrite {
518 path: path_arg(&args)?.to_string(),
519 kind,
520 })
521 }
522
523 fn file_write_result(
524 &self,
525 arguments: &str,
526 current: Option<&[u8]>,
527 ) -> Option<Result<Vec<u8>, String>> {
528 let args: Value = serde_json::from_str(arguments).ok()?;
529 let path = path_arg(&args)?;
530 let request = EditRequest::parse(&args).ok()?;
531 let Some(current) = current else {
532 return Some(Err(format!("File not found: {path}")));
533 };
534 Some(
535 apply_edits(current, path, &request)
536 .map(|applied| applied.new_content.into_bytes())
537 .map_err(|why| why.to_string()),
538 )
539 }
540
541 fn call_effects(&self, arguments: &str) -> aidaemon_core::CallEffects {
544 self.policy.write_effects(&*self.backend, arguments)
545 }
546
547 fn call_annotations_in(
548 &self,
549 arguments: &str,
550 _roots: &crate::semantics::TrustRoots<'_>,
551 ) -> aidaemon_core::ToolAnnotations {
552 let semantics = self.call_semantics(arguments);
553 let mut annotations =
554 crate::semantics::default_call_annotations(self.capabilities(), &semantics);
555 let plants_git_config = semantics
558 .target_hints
559 .iter()
560 .any(|hint| self.policy.plants_configuration(&hint.value));
561 annotations.egress |= plants_git_config;
562 annotations
563 }
564}
565
566fn detect_newline_style(content: &str) -> &'static str {
567 let crlf_count = content.matches("\r\n").count();
568 let lf_total = content.matches('\n').count();
569 let lf_only_count = lf_total.saturating_sub(crlf_count);
570 if crlf_count > lf_only_count {
571 "\r\n"
572 } else {
573 "\n"
574 }
575}
576
577fn normalize_newlines_for_style(input: &str, newline: &str) -> String {
578 let normalized = input.replace("\r\n", "\n").replace('\r', "\n");
579 if newline == "\r\n" {
580 normalized.replace('\n', "\r\n")
581 } else {
582 normalized
583 }
584}
585
586fn truncate_with_ellipsis(input: &str, max_chars: usize) -> String {
587 if input.chars().count() <= max_chars {
588 return input.to_string();
589 }
590 let mut out: String = input.chars().take(max_chars).collect();
591 out.push_str("...");
592 out
593}
594
595fn build_file_preview(content: &str, max_lines: usize, max_chars: usize) -> String {
596 if content.is_empty() {
597 return "(file is empty)".to_string();
598 }
599
600 let mut preview_lines = Vec::new();
601 for (idx, line) in content.lines().take(max_lines).enumerate() {
602 preview_lines.push(format!("{:>4} | {}", idx + 1, line));
603 }
604
605 let total_lines = content.lines().count();
606 if total_lines > max_lines {
607 preview_lines.push(format!("... ({} more lines)", total_lines - max_lines));
608 }
609
610 let joined = preview_lines.join("\n");
611 truncate_with_ellipsis(&joined, max_chars)
612}
613
614fn build_not_found_message(path: &str, content: &str, old_text: &str) -> String {
615 let first_non_empty_old = old_text
616 .lines()
617 .find(|line| !line.trim().is_empty())
618 .unwrap_or(old_text)
619 .trim();
620 let old_hint = if first_non_empty_old.is_empty() {
621 "old_text appears empty or whitespace-only.".to_string()
622 } else {
623 format!(
624 "old_text first non-empty line: `{}`",
625 truncate_with_ellipsis(first_non_empty_old, 120)
626 )
627 };
628
629 let preview = build_file_preview(content, 40, 3500);
630 format!(
631 "Text not found in {}. The old_text must match exactly (including whitespace and indentation).\n\
632{}\n\n\
633Self-recovery steps:\n\
6341. Call read_file on the same path.\n\
6352. Copy the exact block from the file output into old_text and retry edit_file.\n\
6363. If the goal is replacing the whole file, use write_file instead of edit_file.\n\n\
637File preview:\n{}",
638 path, old_hint, preview
639 )
640}
641
642fn get_change_context(content: &str, new_text: &str) -> String {
644 let lines: Vec<&str> = content.lines().collect();
645 let new_text_first_line = new_text.lines().next().unwrap_or(new_text);
646
647 if let Some(idx) = lines.iter().position(|l| l.contains(new_text_first_line)) {
649 let start = idx.saturating_sub(2);
650 let end = (idx + new_text.lines().count() + 2).min(lines.len());
651 let context_lines: Vec<String> = lines[start..end]
652 .iter()
653 .enumerate()
654 .map(|(i, line)| format!("{:>4} | {}", start + i + 1, line))
655 .collect();
656 context_lines.join("\n")
657 } else {
658 String::from("(change context not available)")
659 }
660}