| 1 | import * as fs from "fs"; |
| 2 | |
| 3 | import { telemetryService } from "../../telemetry/telemetryService.js"; |
| 4 | import { |
| 5 | calculateLinesOfCodeDiff, |
| 6 | getLanguageFromFilePath, |
| 7 | } from "../../telemetry/utils.js"; |
| 8 | import { Tool } from "../types.js"; |
| 9 | import { generateDiff } from "../writeFile.js"; |
| 10 | |
| 11 | import { findSearchMatch } from "./findSearchMatch.js"; |
| 12 | import { parseSearchAndReplaceArgs } from "./parseArgs.js"; |
| 13 | import { parseAllSearchReplaceBlocks } from "./parseBlock.js"; |
| 14 | |
| 15 | export interface SearchAndReplaceInFileArgs { |
| 16 | filepath: string; |
| 17 | diffs: string[]; |
| 18 | } |
| 19 | |
| 20 | // Currently unsupported and filtered out in `gui/src/redux/slices/sessionSlice.ts` |
| 21 | export const NO_PARALLEL_TOOL_CALLING_INSRUCTION = |
| 22 | "Note this tool CANNOT be called in parallel."; |
| 23 | |
| 24 | /** |
| 25 | * This tool is in an experimental state. |
| 26 | * Our starting point is heavily inspired by Cline's `replace_in_file` tool: https://github.com/cline/cline/blob/2709ccefcddc616e89a70962f017bcbbca1f17bf/src/core/prompts/system.ts#L87-L121 |
| 27 | */ |
| 28 | export const searchAndReplaceInFileTool: Tool = { |
| 29 | name: "Edit", |
| 30 | displayName: "Edit", |
| 31 | readonly: false, |
| 32 | isBuiltIn: true, |
| 33 | description: `Request to replace sections of content in an existing file using multiple SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file. ${NO_PARALLEL_TOOL_CALLING_INSRUCTION}`, |
| 34 | parameters: { |
| 35 | filepath: { |
| 36 | type: "string", |
| 37 | description: "The path to the file to edit", |
| 38 | required: true, |
| 39 | }, |
| 40 | diffs: { |
| 41 | type: "array", |
| 42 | items: { |
| 43 | type: "string", |
| 44 | }, |
| 45 | description: `An array of strings, each containing one or more SEARCH/REPLACE blocks following this exact format: |
| 46 | \`\`\` |
| 47 | ------- SEARCH |
| 48 | [exact content to find] |
| 49 | ======= |
| 50 | [new content to replace with] |
| 51 | +++++++ REPLACE |
| 52 | \`\`\` |
| 53 | |
| 54 | Critical rules: |
| 55 | 1. SEARCH content must match the associated file section to find EXACTLY: |
| 56 | * Match character-for-character including whitespace, indentation, line endings |
| 57 | * Include all comments, docstrings, etc. |
| 58 | 2. SEARCH/REPLACE blocks will ONLY replace the first match occurrence. |
| 59 | * Including multiple unique SEARCH/REPLACE blocks if you need to make multiple changes. |
| 60 | * Include *just* enough lines in each SEARCH section to uniquely match each set of lines that need to change. |
| 61 | * When using multiple SEARCH/REPLACE blocks, list them in the order they appear in the file. |
| 62 | 3. **Order matters**: DIFFs in the array should be ordered from top to bottom of the file to ensure correct application. |
| 63 | 4. Keep SEARCH/REPLACE blocks concise: |
| 64 | * Break large SEARCH/REPLACE blocks into a series of smaller blocks that each change a small portion of the file. |
| 65 | * Include just the changing lines, and a few surrounding lines if needed for uniqueness. |
| 66 | * Do not include long runs of unchanging lines in SEARCH/REPLACE blocks. |
| 67 | * Each line must be complete. Never truncate lines mid-way through as this can cause matching failures. |
| 68 | 5. Splitting up tool calls: |
| 69 | * When making multiple closely related edits to the same file, you should try to use multiple SEARCH/REPLACE blocks in a single tool call, rather than making multiple separate tool calls |
| 70 | * If you need to make follow up edits or group your work into logical segments, it is okay to perform additional tool calls |
| 71 | * DO NOT make back-to-back tool calls. Instead interleave with brief explanation of what each will do. For example, instead of [explanation, tool call, tool call] you should do [explanation, tool call, explanation, tool call] |
| 72 | 6. Special operations: |
| 73 | * To move code: Use two SEARCH/REPLACE blocks (one to delete from original + one to insert at new location) |
| 74 | * To delete code: Use empty REPLACE section |
| 75 | |
| 76 | Usage: |
| 77 | \`\`\` |
| 78 | ------- SEARCH |
| 79 | [exact content to find] |
| 80 | ======= |
| 81 | [new content to replace with] |
| 82 | +++++++ REPLACE |
| 83 | |
| 84 | ------- SEARCH |
| 85 | [exact content to find] |
| 86 | ======= |
| 87 | [new content to replace with] |
| 88 | +++++++ REPLACE |
| 89 | \`\`\` |
| 90 | |
| 91 | Each string in the diffs array can contain multiple SEARCH/REPLACE blocks, and all will be applied sequentially in the order they appear.`, |
| 92 | required: true, |
| 93 | }, |
| 94 | }, |
| 95 | preprocess: async (args) => { |
| 96 | // Get and validate args |
| 97 | const { filepath, diffs } = parseSearchAndReplaceArgs(args); |
| 98 | |
| 99 | // Get current file contents |
| 100 | if (!fs.existsSync(filepath)) { |
| 101 | throw new Error(`file ${filepath} does not exist`); |
| 102 | } |
| 103 | const oldContent = fs.readFileSync(filepath, "utf-8"); |
| 104 | let newContent = oldContent; |
| 105 | |
| 106 | // Parse blocks |
| 107 | const blocks = diffs.map(parseAllSearchReplaceBlocks).flat(); |
| 108 | if (blocks.length === 0) { |
| 109 | throw new Error("No complete search/replace blocks found in any diffs"); |
| 110 | } |
| 111 | |
| 112 | // Apply all replacements sequentially to build the final content |
| 113 | for (let i = 0; i < blocks.length; i++) { |
| 114 | const block = blocks[i]; |
| 115 | const { searchContent, replaceContent } = block; |
| 116 | |
| 117 | if (typeof searchContent === "undefined") { |
| 118 | throw new Error(`No search content defined for block ${i + 1}`); |
| 119 | } |
| 120 | if (typeof replaceContent === "undefined") { |
| 121 | throw new Error(`No replace content defined for block ${i + 1}`); |
| 122 | } |
| 123 | |
| 124 | const match = findSearchMatch(newContent, searchContent); |
| 125 | |
| 126 | if (!match) { |
| 127 | throw new Error( |
| 128 | `Search content not found in block ${i + 1}:\n${searchContent}`, |
| 129 | ); |
| 130 | } |
| 131 | |
| 132 | newContent = |
| 133 | newContent.substring(0, match.startIndex) + |
| 134 | replaceContent + |
| 135 | newContent.substring(match.endIndex); |
| 136 | } |
| 137 | |
| 138 | const diff = generateDiff(oldContent, newContent, filepath); |
| 139 | |
| 140 | return { |
| 141 | args: { |
| 142 | filepath, |
| 143 | newContent, |
| 144 | oldContent, // Just for telemetry later |
| 145 | }, |
| 146 | preview: [ |
| 147 | { |
| 148 | type: "text", |
| 149 | content: "Will make the following changes:", |
| 150 | }, |
| 151 | { |
| 152 | type: "diff", |
| 153 | content: diff, |
| 154 | }, |
| 155 | ], |
| 156 | }; |
| 157 | }, |
| 158 | run: async (args) => { |
| 159 | try { |
| 160 | fs.writeFileSync(args.filepath, args.newContent, "utf-8"); |
| 161 | |
| 162 | // Get lines for telemetry |
| 163 | const { added, removed } = calculateLinesOfCodeDiff( |
| 164 | args.oldContent, |
| 165 | args.newContent, |
| 166 | ); |
| 167 | const language = getLanguageFromFilePath(args.filepath); |
| 168 | |
| 169 | if (added > 0) { |
| 170 | telemetryService.recordLinesOfCodeModified("added", added, language); |
| 171 | } |
| 172 | if (removed > 0) { |
| 173 | telemetryService.recordLinesOfCodeModified( |
| 174 | "removed", |
| 175 | removed, |
| 176 | language, |
| 177 | ); |
| 178 | } |
| 179 | |
| 180 | // Record file operation |
| 181 | return `Successfully edited ${args.filepath}`; |
| 182 | } catch (error) { |
| 183 | throw new Error( |
| 184 | `Error: failed to edit ${args.filepath}:\n ${ |
| 185 | error instanceof Error ? error.message : String(error) |
| 186 | }`, |
| 187 | ); |
| 188 | } |
| 189 | }, |
| 190 | }; |