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