| 1 | import * as fs from "fs"; |
| 2 | |
| 3 | import { throwIfFileIsSecurityConcern } from "core/indexing/ignore.js"; |
| 4 | |
| 5 | import { telemetryService } from "../telemetry/telemetryService.js"; |
| 6 | import { |
| 7 | calculateLinesOfCodeDiff, |
| 8 | getLanguageFromFilePath, |
| 9 | } from "../telemetry/utils.js"; |
| 10 | |
| 11 | import { readFilesSet, readFileTool } from "./readFile.js"; |
| 12 | import { Tool } from "./types.js"; |
| 13 | import { generateDiff } from "./writeFile.js"; |
| 14 | |
| 15 | export interface EditArgs { |
| 16 | file_path: string; |
| 17 | old_string: string; |
| 18 | new_string: string; |
| 19 | replace_all?: boolean; |
| 20 | } |
| 21 | |
| 22 | export const editTool: Tool = { |
| 23 | name: "Edit", |
| 24 | displayName: "Edit", |
| 25 | readonly: false, |
| 26 | isBuiltIn: true, |
| 27 | description: `Performs exact string replacements in a file. |
| 28 | |
| 29 | USAGE: |
| 30 | - ALWAYS use the \`${readFileTool.name}\` tool just before making edits, to understand the file's up-to-date contents and context. |
| 31 | - When editing text from ${readFileTool.name} tool output, ensure you preserve exact whitespace/indentation. |
| 32 | - Always prefer editing existing files in the codebase. NEVER write new files unless explicitly required. |
| 33 | - Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked. |
| 34 | - Use \`replace_all\` for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable, for instance. |
| 35 | |
| 36 | WARNINGS: |
| 37 | - When not using \`replace_all\`, the edit will FAIL if \`old_string\` is not unique in the file. Either provide a larger string with more surrounding context to make it unique or use \`replace_all\` to change every instance of \`old_string\`. |
| 38 | - The edit will FAIL if you have not recently used the \`${readFileTool.name}\` tool to view up-to-date file contents.`, |
| 39 | parameters: { |
| 40 | file_path: { |
| 41 | type: "string", |
| 42 | description: "The absolute path to the file to modify", |
| 43 | required: true, |
| 44 | }, |
| 45 | old_string: { |
| 46 | type: "string", |
| 47 | description: |
| 48 | "The text to replace - must be exact including whitespace/indentation", |
| 49 | required: true, |
| 50 | }, |
| 51 | new_string: { |
| 52 | type: "string", |
| 53 | description: |
| 54 | "The text to replace it with (MUST be different from old_string)", |
| 55 | required: true, |
| 56 | }, |
| 57 | replace_all: { |
| 58 | type: "boolean", |
| 59 | description: "Replace all occurences of old_string (default false)", |
| 60 | required: false, |
| 61 | }, |
| 62 | }, |
| 63 | preprocess: async (args) => { |
| 64 | const { |
| 65 | file_path, |
| 66 | old_string, |
| 67 | new_string, |
| 68 | replace_all = false, |
| 69 | } = args as EditArgs; |
| 70 | |
| 71 | // Validate arguments |
| 72 | if (!file_path) { |
| 73 | throw new Error("file_path is required"); |
| 74 | } |
| 75 | |
| 76 | if (!old_string) { |
| 77 | throw new Error("old_string is required"); |
| 78 | } |
| 79 | if (new_string === undefined) { |
| 80 | throw new Error("new_string is required"); |
| 81 | } |
| 82 | if (old_string === new_string) { |
| 83 | throw new Error("old_string and new_string must be different"); |
| 84 | } |
| 85 | |
| 86 | const resolvedPath = fs.realpathSync(file_path); |
| 87 | |
| 88 | // Check if file has been read |
| 89 | if (!readFilesSet.has(resolvedPath)) { |
| 90 | throw new Error( |
| 91 | `You must use the ${readFileTool.name} tool to read ${file_path} before editing it.`, |
| 92 | ); |
| 93 | } |
| 94 | |
| 95 | throwIfFileIsSecurityConcern(resolvedPath); |
| 96 | |
| 97 | // Check if file exists |
| 98 | if (!fs.existsSync(resolvedPath)) { |
| 99 | throw new Error(`File ${file_path} does not exist`); |
| 100 | } |
| 101 | |
| 102 | // Read current file content |
| 103 | const oldContent = fs.readFileSync(resolvedPath, "utf-8"); |
| 104 | |
| 105 | // Check if old_string exists in the file |
| 106 | if (!oldContent.includes(old_string)) { |
| 107 | throw new Error(`String not found in file: ${old_string}`); |
| 108 | } |
| 109 | |
| 110 | let newContent: string; |
| 111 | |
| 112 | if (replace_all) { |
| 113 | // Replace all occurrences |
| 114 | newContent = oldContent.split(old_string).join(new_string); |
| 115 | } else { |
| 116 | // Replace only the first occurrence |
| 117 | const occurrences = oldContent.split(old_string).length - 1; |
| 118 | if (occurrences > 1) { |
| 119 | throw new Error( |
| 120 | `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.`, |
| 121 | ); |
| 122 | } |
| 123 | newContent = oldContent.replace(old_string, new_string); |
| 124 | } |
| 125 | |
| 126 | // Generate diff for preview |
| 127 | const diff = generateDiff(oldContent, newContent, resolvedPath); |
| 128 | |
| 129 | return { |
| 130 | args: { |
| 131 | resolvedPath, |
| 132 | newContent, |
| 133 | oldContent, |
| 134 | }, |
| 135 | preview: [ |
| 136 | { |
| 137 | type: "text", |
| 138 | content: "Will make the following changes:", |
| 139 | }, |
| 140 | { |
| 141 | type: "diff", |
| 142 | content: diff, |
| 143 | }, |
| 144 | ], |
| 145 | }; |
| 146 | }, |
| 147 | run: async (args: { |
| 148 | resolvedPath: string; |
| 149 | newContent: string; |
| 150 | oldContent: string; |
| 151 | }) => { |
| 152 | try { |
| 153 | fs.writeFileSync(args.resolvedPath, args.newContent, "utf-8"); |
| 154 | |
| 155 | // Get lines for telemetry |
| 156 | const { added, removed } = calculateLinesOfCodeDiff( |
| 157 | args.oldContent, |
| 158 | args.newContent, |
| 159 | ); |
| 160 | const language = getLanguageFromFilePath(args.resolvedPath); |
| 161 | |
| 162 | if (added > 0) { |
| 163 | telemetryService.recordLinesOfCodeModified("added", added, language); |
| 164 | } |
| 165 | if (removed > 0) { |
| 166 | telemetryService.recordLinesOfCodeModified( |
| 167 | "removed", |
| 168 | removed, |
| 169 | language, |
| 170 | ); |
| 171 | } |
| 172 | |
| 173 | // Generate diff for result display |
| 174 | const diff = generateDiff( |
| 175 | args.oldContent, |
| 176 | args.newContent, |
| 177 | args.resolvedPath, |
| 178 | ); |
| 179 | |
| 180 | return `Successfully edited ${args.resolvedPath}\nDiff:\n${diff}`; |
| 181 | } catch (error) { |
| 182 | throw new Error( |
| 183 | `Error: failed to edit ${args.resolvedPath}: ${ |
| 184 | error instanceof Error ? error.message : String(error) |
| 185 | }`, |
| 186 | ); |
| 187 | } |
| 188 | }, |
| 189 | }; |