| 1 | import * as fs from "fs"; |
| 2 | import * as path from "path"; |
| 3 | |
| 4 | import { telemetryService } from "../telemetry/telemetryService.js"; |
| 5 | import { |
| 6 | calculateLinesOfCodeDiff, |
| 7 | getLanguageFromFilePath, |
| 8 | } from "../telemetry/utils.js"; |
| 9 | |
| 10 | import { markFileAsRead, readFilesSet } from "./edit.js"; |
| 11 | import { Tool } from "./types.js"; |
| 12 | import { generateDiff } from "./writeFile.js"; |
| 13 | |
| 14 | export { markFileAsRead }; |
| 15 | |
| 16 | export interface EditOperation { |
| 17 | old_string: string; |
| 18 | new_string: string; |
| 19 | replace_all?: boolean; |
| 20 | } |
| 21 | |
| 22 | export interface MultiEditArgs { |
| 23 | file_path: string; |
| 24 | edits: EditOperation[]; |
| 25 | } |
| 26 | |
| 27 | // Function to check if file has been read (shared with edit tool) |
| 28 | function hasFileBeenRead(filePath: string): boolean { |
| 29 | return readFilesSet.has(filePath); |
| 30 | } |
| 31 | |
| 32 | // Helper functions for multiEdit validation |
| 33 | function validateMultiEditArgs(args: any): { |
| 34 | original_path: string; |
| 35 | file_path: string; |
| 36 | edits: EditOperation[]; |
| 37 | } { |
| 38 | const { file_path, edits } = args as MultiEditArgs; |
| 39 | |
| 40 | if (!file_path) { |
| 41 | throw new Error("file_path is required"); |
| 42 | } |
| 43 | if (!edits || !Array.isArray(edits) || edits.length === 0) { |
| 44 | throw new Error( |
| 45 | "edits array is required and must contain at least one edit", |
| 46 | ); |
| 47 | } |
| 48 | |
| 49 | // Convert relative paths to absolute paths |
| 50 | const absolutePath = path.isAbsolute(file_path) |
| 51 | ? file_path |
| 52 | : path.resolve(process.cwd(), file_path); |
| 53 | |
| 54 | return { original_path: file_path, file_path: absolutePath, edits }; |
| 55 | } |
| 56 | |
| 57 | function validateEdits(edits: EditOperation[]): void { |
| 58 | for (let i = 0; i < edits.length; i++) { |
| 59 | const edit = edits[i]; |
| 60 | if (!edit.old_string && edit.old_string !== "") { |
| 61 | throw new Error(`Edit ${i + 1}: old_string is required`); |
| 62 | } |
| 63 | if (edit.new_string === undefined) { |
| 64 | throw new Error(`Edit ${i + 1}: new_string is required`); |
| 65 | } |
| 66 | if (edit.old_string === edit.new_string) { |
| 67 | throw new Error( |
| 68 | `Edit ${i + 1}: old_string and new_string must be different`, |
| 69 | ); |
| 70 | } |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | function validateFileAccess( |
| 75 | original_path: string, |
| 76 | file_path: string, |
| 77 | isCreatingNewFile: boolean, |
| 78 | ): void { |
| 79 | if (isCreatingNewFile) { |
| 80 | // For new file creation, check if parent directory exists |
| 81 | const parentDir = path.dirname(file_path); |
| 82 | if (parentDir && !fs.existsSync(parentDir)) { |
| 83 | throw new Error(`Parent directory does not exist: ${parentDir}`); |
| 84 | } |
| 85 | } else { |
| 86 | // For existing files, check if file has been read |
| 87 | // Check with the original path first, then with absolute path |
| 88 | if (!hasFileBeenRead(original_path) && !hasFileBeenRead(file_path)) { |
| 89 | throw new Error( |
| 90 | `You must use the Read tool to read ${original_path} before editing it.`, |
| 91 | ); |
| 92 | } |
| 93 | if (!fs.existsSync(file_path)) { |
| 94 | throw new Error(`File ${file_path} does not exist`); |
| 95 | } |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | function applyEdit( |
| 100 | content: string, |
| 101 | edit: EditOperation, |
| 102 | editIndex: number, |
| 103 | isFirstEditOfNewFile: boolean, |
| 104 | ): string { |
| 105 | const { old_string, new_string, replace_all = false } = edit; |
| 106 | |
| 107 | // For new file creation, the first edit can have empty old_string |
| 108 | if (isFirstEditOfNewFile && old_string === "") { |
| 109 | return new_string; |
| 110 | } |
| 111 | |
| 112 | // Check if old_string exists in current content |
| 113 | if (!content.includes(old_string)) { |
| 114 | throw new Error( |
| 115 | `Edit ${editIndex + 1}: String not found in file: "${old_string}"`, |
| 116 | ); |
| 117 | } |
| 118 | |
| 119 | if (replace_all) { |
| 120 | // Replace all occurrences |
| 121 | return content.split(old_string).join(new_string); |
| 122 | } else { |
| 123 | // Replace only the first occurrence, but check for uniqueness |
| 124 | const occurrences = content.split(old_string).length - 1; |
| 125 | if (occurrences > 1) { |
| 126 | throw new Error( |
| 127 | `Edit ${editIndex + 1}: String "${old_string}" appears ${occurrences} times in the file. Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.`, |
| 128 | ); |
| 129 | } |
| 130 | return content.replace(old_string, new_string); |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | export const multiEditTool: Tool = { |
| 135 | name: "MultiEdit", |
| 136 | displayName: "MultiEdit", |
| 137 | readonly: false, |
| 138 | isBuiltIn: true, |
| 139 | description: `This is a tool for making multiple edits to a single file in one operation. It |
| 140 | is built on top of the Edit tool and allows you to perform multiple |
| 141 | find-and-replace operations efficiently. Prefer this tool over the Edit tool |
| 142 | when you need to make multiple edits to the same file. |
| 143 | |
| 144 | |
| 145 | Before using this tool: |
| 146 | |
| 147 | |
| 148 | 1. Use the Read tool to understand the file's contents and context |
| 149 | |
| 150 | 2. Verify the directory path is correct |
| 151 | |
| 152 | |
| 153 | To make multiple file edits, provide the following: |
| 154 | |
| 155 | 1. file_path: The absolute path to the file to modify (must be absolute, not |
| 156 | relative) |
| 157 | |
| 158 | 2. edits: An array of edit operations to perform, where each edit contains: |
| 159 | - old_string: The text to replace (must match the file contents exactly, including all whitespace and indentation) |
| 160 | - new_string: The edited text to replace the old_string |
| 161 | - replace_all: Replace all occurences of old_string. This parameter is optional and defaults to false. |
| 162 | |
| 163 | IMPORTANT: |
| 164 | |
| 165 | - All edits are applied in sequence, in the order they are provided |
| 166 | |
| 167 | - Each edit operates on the result of the previous edit |
| 168 | |
| 169 | - All edits must be valid for the operation to succeed - if any edit fails, |
| 170 | none will be applied |
| 171 | |
| 172 | - This tool is ideal when you need to make several changes to different parts |
| 173 | of the same file |
| 174 | |
| 175 | - For Jupyter notebooks (.ipynb files), use the NotebookEdit instead |
| 176 | |
| 177 | |
| 178 | CRITICAL REQUIREMENTS: |
| 179 | |
| 180 | 1. All edits follow the same requirements as the single Edit tool |
| 181 | |
| 182 | 2. The edits are atomic - either all succeed or none are applied |
| 183 | |
| 184 | 3. Plan your edits carefully to avoid conflicts between sequential operations |
| 185 | |
| 186 | |
| 187 | WARNING: |
| 188 | |
| 189 | - The tool will fail if edits.old_string doesn't match the file contents |
| 190 | exactly (including whitespace) |
| 191 | |
| 192 | - The tool will fail if edits.old_string and edits.new_string are the same |
| 193 | |
| 194 | - Since edits are applied in sequence, ensure that earlier edits don't affect |
| 195 | the text that later edits are trying to find |
| 196 | |
| 197 | |
| 198 | When making edits: |
| 199 | |
| 200 | - Ensure all edits result in idiomatic, correct code |
| 201 | |
| 202 | - Do not leave the code in a broken state |
| 203 | |
| 204 | - Always use absolute file paths (starting with /) |
| 205 | |
| 206 | - Only use emojis if the user explicitly requests it. Avoid adding emojis to |
| 207 | files unless asked. |
| 208 | |
| 209 | - Use replace_all for replacing and renaming strings across the file. This |
| 210 | parameter is useful if you want to rename a variable for instance. |
| 211 | |
| 212 | |
| 213 | If you want to create a new file, use: |
| 214 | |
| 215 | - A new file path, including dir name if needed |
| 216 | |
| 217 | - First edit: empty old_string and the new file's contents as new_string |
| 218 | |
| 219 | - Subsequent edits: normal edit operations on the created content`, |
| 220 | parameters: { |
| 221 | file_path: { |
| 222 | type: "string", |
| 223 | description: "The absolute path to the file to modify", |
| 224 | required: true, |
| 225 | }, |
| 226 | edits: { |
| 227 | type: "array", |
| 228 | description: |
| 229 | "Array of edit operations to perform sequentially on the file", |
| 230 | required: true, |
| 231 | items: { |
| 232 | type: "object", |
| 233 | }, |
| 234 | }, |
| 235 | }, |
| 236 | preprocess: async (args) => { |
| 237 | // Validate and extract arguments |
| 238 | const { original_path, file_path, edits } = validateMultiEditArgs(args); |
| 239 | |
| 240 | // Validate each edit operation |
| 241 | validateEdits(edits); |
| 242 | |
| 243 | // Check if this is creating a new file (first edit has empty old_string) |
| 244 | const isCreatingNewFile = edits[0].old_string === ""; |
| 245 | |
| 246 | // Validate file access |
| 247 | validateFileAccess(original_path, file_path, isCreatingNewFile); |
| 248 | |
| 249 | // Read current file content (or start with empty for new files) |
| 250 | let currentContent = ""; |
| 251 | if (!isCreatingNewFile) { |
| 252 | currentContent = fs.readFileSync(file_path, "utf-8"); |
| 253 | } |
| 254 | |
| 255 | const originalContent = currentContent; |
| 256 | let newContent = currentContent; |
| 257 | |
| 258 | // Apply all edits sequentially |
| 259 | for (let i = 0; i < edits.length; i++) { |
| 260 | const isFirstEditOfNewFile = i === 0 && isCreatingNewFile; |
| 261 | newContent = applyEdit(newContent, edits[i], i, isFirstEditOfNewFile); |
| 262 | } |
| 263 | |
| 264 | // Generate diff for preview |
| 265 | const diff = generateDiff(originalContent, newContent, file_path); |
| 266 | |
| 267 | return { |
| 268 | args: { |
| 269 | file_path, |
| 270 | newContent, |
| 271 | originalContent, |
| 272 | isCreatingNewFile, |
| 273 | editCount: edits.length, |
| 274 | }, |
| 275 | preview: [ |
| 276 | { |
| 277 | type: "text", |
| 278 | content: `Will apply ${edits.length} edit${edits.length === 1 ? "" : "s"} to ${isCreatingNewFile ? "create" : "modify"} ${file_path}:`, |
| 279 | }, |
| 280 | { |
| 281 | type: "diff", |
| 282 | content: diff, |
| 283 | }, |
| 284 | ], |
| 285 | }; |
| 286 | }, |
| 287 | run: async (args: { |
| 288 | file_path: string; |
| 289 | newContent: string; |
| 290 | originalContent: string; |
| 291 | isCreatingNewFile: boolean; |
| 292 | editCount: number; |
| 293 | }) => { |
| 294 | try { |
| 295 | fs.writeFileSync(args.file_path, args.newContent, "utf-8"); |
| 296 | |
| 297 | // Get lines for telemetry |
| 298 | const { added, removed } = calculateLinesOfCodeDiff( |
| 299 | args.originalContent, |
| 300 | args.newContent, |
| 301 | ); |
| 302 | const language = getLanguageFromFilePath(args.file_path); |
| 303 | |
| 304 | if (added > 0) { |
| 305 | telemetryService.recordLinesOfCodeModified("added", added, language); |
| 306 | } |
| 307 | if (removed > 0) { |
| 308 | telemetryService.recordLinesOfCodeModified( |
| 309 | "removed", |
| 310 | removed, |
| 311 | language, |
| 312 | ); |
| 313 | } |
| 314 | |
| 315 | // Generate diff for result display |
| 316 | const diff = generateDiff( |
| 317 | args.originalContent, |
| 318 | args.newContent, |
| 319 | args.file_path, |
| 320 | ); |
| 321 | |
| 322 | const action = args.isCreatingNewFile ? "created" : "edited"; |
| 323 | return `Successfully ${action} ${args.file_path} with ${args.editCount} edit${args.editCount === 1 ? "" : "s"}\nDiff:\n${diff}`; |
| 324 | } catch (error) { |
| 325 | throw new Error( |
| 326 | `Error: failed to edit ${args.file_path}: ${ |
| 327 | error instanceof Error ? error.message : String(error) |
| 328 | }`, |
| 329 | ); |
| 330 | } |
| 331 | }, |
| 332 | }; |