Skip to main content

aidaemon_tools/fs/
edit.rs

1//! `edit_file`: exact find and replace that changes nothing when the text is
2//! missing or ambiguous. A batch of `edits` applies in order, all or none, in
3//! one write of the file.
4
5use 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    /// A tool confined to `workspace`.
29    pub fn new(workspace: Workspace) -> Self {
30        let (backend, policy) = workspace_parts(workspace);
31        Self::on_backend(backend, policy)
32    }
33
34    /// A tool working through `backend` under an application's `policy`.
35    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    /// Replace the model-facing descriptions.
47    pub fn with_text(mut self, text: ToolText) -> Self {
48        self.text = text;
49        self
50    }
51}
52
53/// The argument names a model may use for the text to find and its
54/// replacement.
55const 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
63/// One find-and-replace a call asks for.
64struct EditArg {
65    old_text: String,
66    new_text: String,
67    replace_all: bool,
68}
69
70/// The edits one call asks for: its `edits` list (`batch`), or the single
71/// `old_text`/`new_text` pair.
72struct EditRequest {
73    edits: Vec<EditArg>,
74    batch: bool,
75}
76
77impl EditRequest {
78    /// Read the edits from a call's arguments, or say what is malformed.
79    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    /// Name edit `index` in a refusal: a batch numbers its edits.
129    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
138/// One edit applied to a file's text.
139struct AppliedEdit {
140    new_content: String,
141    /// Occurrences of the text that were found.
142    count: usize,
143    effective_new_text: String,
144    used_newline_recovery: bool,
145}
146
147/// Every edit of a call applied, in order, to a file's bytes.
148struct AppliedEdits {
149    new_content: String,
150    /// Occurrences replaced, over all the edits.
151    replaced: usize,
152    /// Each edit's replacement as written, for showing where it landed.
153    new_texts: Vec<String>,
154    used_newline_recovery: bool,
155}
156
157/// Apply every edit of `request` to `bytes`, each to the result of the one
158/// before, or say which edit cannot be applied and why. The tool and its
159/// `file_write_result` share this, so a predicted result is the one the call
160/// writes.
161fn 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
199/// Apply one edit to `content`, or say why it cannot be applied.
200fn 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    // Count occurrences using exact match first.
208    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    // Self-recovery path: tolerate newline-style mismatch (LF vs CRLF) while
213    // preserving strict exact matching otherwise.
214    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        // Parameter aliasing: models often use slightly different names
323        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        // Held from before the read until the write has landed.
339        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        // Backup + atomic write
358        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        // Show context around each change (the first few of a batch).
367        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
440#[async_trait]
441impl crate::semantics::ToolSemantics for EditFile {
442    fn dispatch_facts(&self) -> crate::semantics::ToolDispatchFacts {
443        crate::semantics::ToolDispatchFacts {
444            offering: crate::semantics::Offering::Core,
445            checkpoints_writes: true,
446            file_guard: crate::semantics::FileGuard::Writes,
447            recap: crate::semantics::RecapKind::FileWrite,
448            activity: crate::semantics::ToolActivity::Fixed(
449                aidaemon_core::card::ActivityKind::Write,
450            ),
451            opens_project_instructions: true,
452            semantic_scope: Some(crate::semantics::ToolSemanticScope::LocalWorkspace),
453            low_signal_result: true,
454            status_label: Some("editing a file"),
455            evidence: crate::semantics::EvidenceSource::FileWrite,
456            ..Default::default()
457        }
458    }
459
460    fn tool_role(&self) -> ToolRole {
461        ToolRole::Action
462    }
463
464    fn capabilities(&self) -> ToolCapabilities {
465        ToolCapabilities {
466            read_only: false,
467            external_side_effect: false,
468            needs_approval: false,
469            idempotent: false,
470            // Not high-impact: find-and-replace with safe failure on ambiguity.
471            // Dedicated file tools are intentionally available without terminal
472            // approval. Sensitive paths are blocked before editing.
473            high_impact_write: false,
474        }
475    }
476
477    fn call_semantics(&self, arguments: &str) -> ToolCallSemantics {
478        let path = serde_json::from_str::<Value>(arguments)
479            .ok()
480            .and_then(|args| {
481                for key in ["path", "file_path", "file", "filename"] {
482                    if let Some(path) = args.get(key).and_then(|value| value.as_str()) {
483                        return Some(path.to_string());
484                    }
485                }
486                None
487            })
488            .unwrap_or_default();
489
490        // It reads the file under its write fence and returns what the file
491        // now holds around each change: a write and an observation of the
492        // result, so a successful edit proves the file's current state.
493        ToolCallSemantics::observation_and_mutation_with(ToolMutationEffects::LOCAL_SOURCE_WRITE)
494            .with_target_hint(ToolTargetHintKind::Path, path)
495    }
496
497    fn call_file_write(&self, arguments: &str) -> Option<crate::semantics::FileWrite> {
498        let args: Value = serde_json::from_str(arguments).ok()?;
499        let request = EditRequest::parse(&args).ok()?;
500        let kind = if request.batch {
501            crate::semantics::FileWriteKind::Edits(
502                request
503                    .edits
504                    .into_iter()
505                    .map(|edit| crate::semantics::TextEdit {
506                        old_text: edit.old_text,
507                        replace_all: edit.replace_all,
508                    })
509                    .collect(),
510            )
511        } else {
512            let edit = request.edits.into_iter().next()?;
513            crate::semantics::FileWriteKind::Edit {
514                old_text: edit.old_text,
515                replace_all: edit.replace_all,
516            }
517        };
518        Some(crate::semantics::FileWrite {
519            path: path_arg(&args)?.to_string(),
520            kind,
521        })
522    }
523
524    fn file_write_result(
525        &self,
526        arguments: &str,
527        current: Option<&[u8]>,
528    ) -> Option<Result<Vec<u8>, String>> {
529        let args: Value = serde_json::from_str(arguments).ok()?;
530        let path = path_arg(&args)?;
531        let request = EditRequest::parse(&args).ok()?;
532        let Some(current) = current else {
533            return Some(Err(format!("File not found: {path}")));
534        };
535        Some(
536            apply_edits(current, path, &request)
537                .map(|applied| applied.new_content.into_bytes())
538                .map_err(|why| why.to_string()),
539        )
540    }
541
542    /// A write of the target path (absolute; a relative path resolves where
543    /// the execution backend puts it, which is not known here).
544    fn call_effects(&self, arguments: &str) -> aidaemon_core::CallEffects {
545        self.policy.write_effects(&*self.backend, arguments)
546    }
547
548    /// A write that plants persistence (a shell start-up file, a launch
549    /// agent, a git hook, the agent's own instructions) always asks.
550    async fn owner_approval_request(
551        &self,
552        call: &crate::semantics::ApprovalCall<'_>,
553        facts: &ToolCallContext,
554    ) -> crate::semantics::OwnerApprovalNeed {
555        super::persistence_write_approval(
556            &self.backend,
557            &*self.policy,
558            "edit_file",
559            call.arguments,
560            self.call_effects(&call.arguments.to_string()),
561            facts,
562        )
563        .await
564    }
565
566    fn call_annotations_in(
567        &self,
568        arguments: &str,
569        _roots: &crate::semantics::TrustRoots<'_>,
570    ) -> aidaemon_core::ToolAnnotations {
571        let semantics = self.call_semantics(arguments);
572        let mut annotations =
573            crate::semantics::default_call_annotations(self.capabilities(), &semantics);
574        // A write that can plant git configuration changes what later
575        // "read-only" git commands execute: treat it as a configuration change.
576        let plants_git_config = semantics
577            .target_hints
578            .iter()
579            .any(|hint| self.policy.plants_configuration(&hint.value));
580        annotations.egress |= plants_git_config;
581        annotations
582    }
583}
584
585fn detect_newline_style(content: &str) -> &'static str {
586    let crlf_count = content.matches("\r\n").count();
587    let lf_total = content.matches('\n').count();
588    let lf_only_count = lf_total.saturating_sub(crlf_count);
589    if crlf_count > lf_only_count {
590        "\r\n"
591    } else {
592        "\n"
593    }
594}
595
596fn normalize_newlines_for_style(input: &str, newline: &str) -> String {
597    let normalized = input.replace("\r\n", "\n").replace('\r', "\n");
598    if newline == "\r\n" {
599        normalized.replace('\n', "\r\n")
600    } else {
601        normalized
602    }
603}
604
605fn truncate_with_ellipsis(input: &str, max_chars: usize) -> String {
606    if input.chars().count() <= max_chars {
607        return input.to_string();
608    }
609    let mut out: String = input.chars().take(max_chars).collect();
610    out.push_str("...");
611    out
612}
613
614fn build_file_preview(content: &str, max_lines: usize, max_chars: usize) -> String {
615    if content.is_empty() {
616        return "(file is empty)".to_string();
617    }
618
619    let mut preview_lines = Vec::new();
620    for (idx, line) in content.lines().take(max_lines).enumerate() {
621        preview_lines.push(format!("{:>4} | {}", idx + 1, line));
622    }
623
624    let total_lines = content.lines().count();
625    if total_lines > max_lines {
626        preview_lines.push(format!("... ({} more lines)", total_lines - max_lines));
627    }
628
629    let joined = preview_lines.join("\n");
630    truncate_with_ellipsis(&joined, max_chars)
631}
632
633fn build_not_found_message(path: &str, content: &str, old_text: &str) -> String {
634    let first_non_empty_old = old_text
635        .lines()
636        .find(|line| !line.trim().is_empty())
637        .unwrap_or(old_text)
638        .trim();
639    let old_hint = if first_non_empty_old.is_empty() {
640        "old_text appears empty or whitespace-only.".to_string()
641    } else {
642        format!(
643            "old_text first non-empty line: `{}`",
644            truncate_with_ellipsis(first_non_empty_old, 120)
645        )
646    };
647
648    let preview = build_file_preview(content, 40, 3500);
649    format!(
650        "Text not found in {}. The old_text must match exactly (including whitespace and indentation).\n\
651{}\n\n\
652Self-recovery steps:\n\
6531. Call read_file on the same path.\n\
6542. Copy the exact block from the file output into old_text and retry edit_file.\n\
6553. If the goal is replacing the whole file, use write_file instead of edit_file.\n\n\
656File preview:\n{}",
657        path, old_hint, preview
658    )
659}
660
661/// Get a few lines of context around where the replacement was made.
662fn get_change_context(content: &str, new_text: &str) -> String {
663    let lines: Vec<&str> = content.lines().collect();
664    let new_text_first_line = new_text.lines().next().unwrap_or(new_text);
665
666    // Find the first line containing the new text
667    if let Some(idx) = lines.iter().position(|l| l.contains(new_text_first_line)) {
668        let start = idx.saturating_sub(2);
669        let end = (idx + new_text.lines().count() + 2).min(lines.len());
670        let context_lines: Vec<String> = lines[start..end]
671            .iter()
672            .enumerate()
673            .map(|(i, line)| format!("{:>4} | {}", start + i + 1, line))
674            .collect();
675        context_lines.join("\n")
676    } else {
677        String::from("(change context not available)")
678    }
679}