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