1use anyhow::{Context, Result};
6use async_trait::async_trait;
7use serde::{Deserialize, Serialize};
8use serde_json::{Value, json};
9use similar::{ChangeTag, TextDiff};
10use std::collections::HashMap;
11use std::path::PathBuf;
12use tokio::fs;
13
14use super::{Tool, ToolResult};
15
16#[derive(Debug, Clone, Serialize, Deserialize)]
17pub struct ConfirmMultiEditInput {
18 pub edits: Vec<EditOperation>,
19 pub confirm: Option<bool>,
20}
21
22#[derive(Debug, Clone, Serialize, Deserialize)]
23pub struct EditOperation {
24 pub file: String,
25 pub old_string: String,
26 pub new_string: String,
27}
28
29#[derive(Debug, Clone, Serialize, Deserialize)]
30pub struct EditPreview {
31 pub file: String,
32 pub diff: String,
33 pub added: usize,
34 pub removed: usize,
35}
36
37pub struct ConfirmMultiEditTool;
38
39impl ConfirmMultiEditTool {
40 pub fn new() -> Self {
41 Self
42 }
43}
44
45#[async_trait]
46impl Tool for ConfirmMultiEditTool {
47 fn id(&self) -> &str {
48 "confirm_multiedit"
49 }
50
51 fn name(&self) -> &str {
52 "Confirm Multi Edit"
53 }
54
55 fn description(&self) -> &str {
56 "Edit multiple files with confirmation. Shows diffs for all changes and requires user confirmation before applying."
57 }
58
59 fn parameters(&self) -> Value {
60 json!({
61 "type": "object",
62 "properties": {
63 "edits": {
64 "type": "array",
65 "description": "Array of edit operations to preview",
66 "items": {
67 "type": "object",
68 "properties": {
69 "file": {
70 "type": "string",
71 "description": "Path to the file to edit"
72 },
73 "old_string": {
74 "type": "string",
75 "description": "The exact string to find and replace"
76 },
77 "new_string": {
78 "type": "string",
79 "description": "The string to replace it with"
80 }
81 },
82 "required": ["file", "old_string", "new_string"]
83 }
84 },
85 "confirm": {
86 "type": "boolean",
87 "description": "Set to true to confirm and apply all changes, false to reject all",
88 "default": null
89 }
90 },
91 "required": ["edits"]
92 })
93 }
94
95 async fn execute(&self, input: Value) -> Result<ToolResult> {
96 let params: ConfirmMultiEditInput = serde_json::from_value(input)?;
97
98 if params.edits.is_empty() {
99 return Ok(ToolResult::error("No edits provided"));
100 }
101
102 let mut file_contents: Vec<(PathBuf, String, String, String)> = Vec::new();
104 let mut previews: Vec<EditPreview> = Vec::new();
105
106 for edit in ¶ms.edits {
107 let path = PathBuf::from(&edit.file);
108
109 if !path.exists() {
110 return Ok(ToolResult::error(format!(
111 "File does not exist: {}",
112 edit.file
113 )));
114 }
115
116 let content = fs::read_to_string(&path)
117 .await
118 .with_context(|| format!("Failed to read file: {}", edit.file))?;
119
120 let matches: Vec<_> = content.match_indices(&edit.old_string).collect();
122
123 if matches.is_empty() {
124 return Ok(ToolResult::error(format!(
125 "String not found in {}: {}",
126 edit.file,
127 if edit.old_string.len() > 50 {
128 format!("{}...", &edit.old_string[..50])
129 } else {
130 edit.old_string.clone()
131 }
132 )));
133 }
134
135 if matches.len() > 1 {
136 return Ok(ToolResult::error(format!(
137 "String found {} times in {} (must be unique). Use more context to disambiguate.",
138 matches.len(),
139 edit.file
140 )));
141 }
142
143 file_contents.push((
144 path,
145 content,
146 edit.old_string.clone(),
147 edit.new_string.clone(),
148 ));
149 }
150
151 let mut total_added = 0;
153 let mut total_removed = 0;
154
155 for (path, content, old_string, new_string) in &file_contents {
156 let new_content = content.replacen(old_string, new_string, 1);
157 let diff = TextDiff::from_lines(content, &new_content);
158
159 let mut diff_output = String::new();
160 let mut added = 0;
161 let mut removed = 0;
162
163 for change in diff.iter_all_changes() {
164 let (sign, style) = match change.tag() {
165 ChangeTag::Delete => {
166 removed += 1;
167 ("-", "red")
168 }
169 ChangeTag::Insert => {
170 added += 1;
171 ("+", "green")
172 }
173 ChangeTag::Equal => (" ", "default"),
174 };
175
176 let line = format!("{}{}", sign, change);
177 if style == "red" {
178 diff_output.push_str(&format!("\x1b[31m{}\x1b[0m", line.trim_end()));
179 } else if style == "green" {
180 diff_output.push_str(&format!("\x1b[32m{}\x1b[0m", line.trim_end()));
181 } else {
182 diff_output.push_str(&line.trim_end());
183 }
184 diff_output.push('\n');
185 }
186
187 previews.push(EditPreview {
188 file: path.display().to_string(),
189 diff: diff_output.trim().to_string(),
190 added,
191 removed,
192 });
193
194 total_added += added;
195 total_removed += removed;
196 }
197
198 if params.confirm.is_none() {
200 let mut all_diffs = String::new();
201 for preview in &previews {
202 all_diffs.push_str(&format!("\n=== {} ===\n{}", preview.file, preview.diff));
203 }
204
205 let mut metadata = HashMap::new();
206 metadata.insert("requires_confirmation".to_string(), json!(true));
207 metadata.insert("total_files".to_string(), json!(previews.len()));
208 metadata.insert("total_added".to_string(), json!(total_added));
209 metadata.insert("total_removed".to_string(), json!(total_removed));
210 metadata.insert("previews".to_string(), json!(previews));
211
212 return Ok(ToolResult {
213 output: format!(
214 "Multi-file changes require confirmation:{}\n\nTotal: {} files, +{} lines, -{} lines",
215 all_diffs,
216 previews.len(),
217 total_added,
218 total_removed
219 ),
220 success: true,
221 metadata,
222 });
223 }
224
225 if params.confirm == Some(true) {
227 for (path, content, old_string, new_string) in file_contents {
229 let new_content = content.replacen(&old_string, &new_string, 1);
230 fs::write(&path, &new_content).await?;
231 }
232
233 Ok(ToolResult::success(format!(
234 "✓ Applied {} file changes",
235 previews.len()
236 )))
237 } else {
238 Ok(ToolResult::success("✗ All changes rejected by user"))
239 }
240 }
241}