| 1 | import { findSearchMatch } from "core/edit/searchAndReplace/findSearchMatch"; |
| 2 | import { parseAllSearchReplaceBlocks } from "core/edit/searchAndReplace/parseSearchReplaceBlock"; |
| 3 | import { resolveRelativePathInDir } from "core/util/ideUtils"; |
| 4 | import { ClientToolImpl } from "./callClientTool"; |
| 5 | |
| 6 | export const searchReplaceToolImpl: ClientToolImpl = async ( |
| 7 | args, |
| 8 | toolCallId, |
| 9 | extras, |
| 10 | ) => { |
| 11 | const { filepath, diff } = args; |
| 12 | |
| 13 | // Check if we have a streamId from a pre-existing apply state |
| 14 | if (!extras.streamId) { |
| 15 | throw new Error("Invalid apply state - no streamId available"); |
| 16 | } |
| 17 | |
| 18 | // Resolve the file path |
| 19 | const resolvedFilepath = await resolveRelativePathInDir( |
| 20 | filepath, |
| 21 | extras.ideMessenger.ide, |
| 22 | ); |
| 23 | if (!resolvedFilepath) { |
| 24 | throw new Error(`File ${filepath} does not exist`); |
| 25 | } |
| 26 | |
| 27 | // Parse all search/replace blocks from the diff content |
| 28 | const blocks = parseAllSearchReplaceBlocks(diff); |
| 29 | |
| 30 | if (blocks.length === 0) { |
| 31 | throw new Error("No complete search/replace blocks found"); |
| 32 | } |
| 33 | |
| 34 | try { |
| 35 | // Read the current file content |
| 36 | const originalContent = |
| 37 | await extras.ideMessenger.ide.readFile(resolvedFilepath); |
| 38 | let currentContent = originalContent; |
| 39 | |
| 40 | // Apply all replacements sequentially to build the final content |
| 41 | for (let i = 0; i < blocks.length; i++) { |
| 42 | const block = blocks[i]; |
| 43 | const { searchContent, replaceContent } = block; |
| 44 | |
| 45 | // Find the search content in the current state of the file |
| 46 | const match = findSearchMatch(currentContent, searchContent || ""); |
| 47 | if (!match) { |
| 48 | throw new Error( |
| 49 | `Search content not found in block ${i + 1}:\n${searchContent}`, |
| 50 | ); |
| 51 | } |
| 52 | |
| 53 | // Apply the replacement |
| 54 | currentContent = |
| 55 | currentContent.substring(0, match.startIndex) + |
| 56 | (replaceContent || "") + |
| 57 | currentContent.substring(match.endIndex); |
| 58 | } |
| 59 | |
| 60 | // Single applyToFile call with all accumulated changes |
| 61 | await extras.ideMessenger.request("applyToFile", { |
| 62 | text: currentContent, |
| 63 | streamId: extras.streamId, |
| 64 | filepath: resolvedFilepath, |
| 65 | toolCallId, |
| 66 | }); |
| 67 | |
| 68 | // Return success - applyToFile will handle the completion state |
| 69 | return { |
| 70 | respondImmediately: false, // Let apply state handle completion |
| 71 | output: undefined, |
| 72 | }; |
| 73 | } catch (error) { |
| 74 | throw new Error( |
| 75 | `Failed to apply search and replace: ${error instanceof Error ? error.message : String(error)}`, |
| 76 | ); |
| 77 | } |
| 78 | }; |