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