1use std::path::PathBuf;
4
5use async_trait::async_trait;
6use serde_json::{json, Value};
7use tokio_util::sync::CancellationToken;
8
9use crate::agent::tool::{AgentTool, ToolResult};
10use crate::tools::edit_diff::{
11 apply_edits, detect_line_ending, generate_diff, normalize_to_lf, restore_line_endings,
12 strip_bom, Edit,
13};
14use crate::tools::file_mutex::with_file_lock;
15use crate::tools::util::{display_path, resolve_to_cwd};
16
17pub struct EditTool {
18 pub cwd: PathBuf,
19}
20
21fn prepare_arguments(args: Value) -> Value {
26 let Some(obj) = args.as_object().cloned() else {
27 return args;
28 };
29 let mut obj = obj;
30
31 if let Some(Value::String(s)) = obj.get("edits").cloned() {
33 if let Ok(Value::Array(a)) = serde_json::from_str::<Value>(&s) {
34 obj.insert("edits".into(), Value::Array(a));
35 }
36 }
37
38 let has_legacy = obj.get("oldText").is_some() && obj.get("newText").is_some();
40 if has_legacy {
41 let old = obj.remove("oldText").unwrap_or(Value::Null);
42 let nw = obj.remove("newText").unwrap_or(Value::Null);
43 let mut edits = match obj.get("edits").cloned() {
44 Some(Value::Array(a)) => a,
45 _ => Vec::new(),
46 };
47 let mut entry = serde_json::Map::new();
48 entry.insert("oldText".into(), old);
49 entry.insert("newText".into(), nw);
50 edits.push(Value::Object(entry));
51 obj.insert("edits".into(), Value::Array(edits));
52 }
53 Value::Object(obj)
54}
55
56#[async_trait]
57impl AgentTool for EditTool {
58 fn name(&self) -> &str {
59 "edit"
60 }
61 fn description(&self) -> &str {
62 "Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into one edit. Do not include large unchanged regions just to connect distant changes."
63 }
64 fn input_schema(&self) -> Value {
65 json!({
66 "type": "object",
67 "properties": {
68 "path": { "type": "string", "description": "Path to the file to edit (relative or absolute)" },
69 "edits": {
70 "type": "array",
71 "description": "One or more targeted replacements, each matched against the original file (not incrementally). Non-overlapping.",
72 "items": {
73 "type": "object",
74 "properties": {
75 "oldText": { "type": "string", "description": "Exact text to replace; must be unique in the file" },
76 "newText": { "type": "string", "description": "Replacement text" }
77 },
78 "required": ["oldText", "newText"],
79 "additionalProperties": false
80 }
81 }
82 },
83 "required": ["path", "edits"]
84 })
85 }
86
87 fn prepare_arguments(&self, args: Value) -> Value {
88 prepare_arguments(args)
89 }
90
91 async fn execute(&self, args: Value, _cancel: CancellationToken) -> anyhow::Result<ToolResult> {
92 let path_str = args
93 .get("path")
94 .and_then(|v| v.as_str())
95 .or_else(|| args.get("file_path").and_then(|v| v.as_str()))
96 .ok_or_else(|| anyhow::anyhow!("edit requires a 'path' parameter"))?
97 .to_string();
98 let edits_raw = args
99 .get("edits")
100 .cloned()
101 .ok_or_else(|| anyhow::anyhow!("edit requires an 'edits' array with at least one replacement"))?;
102 let edits: Vec<Edit> = serde_json::from_value(edits_raw)
103 .map_err(|e| anyhow::anyhow!("edits must be an array of {{oldText,newText}}: {e}"))?;
104 if edits.is_empty() {
105 anyhow::bail!("edits must contain at least one replacement");
106 }
107
108 let abs = resolve_to_cwd(&path_str, &self.cwd);
109 let display = display_path(&path_str, &self.cwd);
110
111 let result = with_file_lock(&abs, async {
112 if !abs.exists() {
113 anyhow::bail!("Could not edit file: {display}. File does not exist.");
114 }
115 let raw = tokio::fs::read_to_string(&abs).await?;
116 let (bom, text) = strip_bom(&raw);
117 let ending = detect_line_ending(&text);
118 let normalized = normalize_to_lf(&text);
119 let (base, new_normalized) = apply_edits(&normalized, &edits, &display)?;
120 let final_content = format!("{bom}{}", restore_line_endings(&new_normalized, ending));
121 tokio::fs::write(&abs, final_content.as_bytes()).await?;
122 let (diff, first_changed_line) = generate_diff(&base, &new_normalized, &display);
123 Ok::<_, anyhow::Error>((edits.len(), diff, first_changed_line))
124 })
125 .await;
126
127 let (count, diff, first_changed_line) = result?;
128 let details = json!({
129 "diff": diff,
130 "firstChangedLine": first_changed_line,
131 });
132 let mut result = ToolResult::text(format!(
133 "Successfully replaced {count} block(s) in {display}.\n\n{diff}"
134 ));
135 result.details = details;
136 Ok(result)
137 }
138}