Elffuss BraidHub

kikocis/continue public

4e263ad457a7 · 3.8 KiBRawPermalink
1import { findSearchMatch } from "core/edit/searchAndReplace/findSearchMatch";
2import { parseAllSearchReplaceBlocks } from "core/edit/searchAndReplace/parseSearchReplaceBlock";
3import { resolveRelativePathInDir } from "core/util/ideUtils";
4import posthog from "posthog-js";
5import { v4 as uuid } from "uuid";
6import { updateApplyState } from "../../redux/slices/sessionSlice";
7import { handleEditToolApplyError } from "../../redux/thunks/handleApplyStateUpdate";
8import { ClientToolImpl } from "./callClientTool";
9
10export const searchReplaceToolImpl: ClientToolImpl = async (
11 args,
12 toolCallId,
13 extras,
14) => {
15 const { filepath, diffs } = args;
16
17 const state = extras.getState();
18 const allowAnonymousTelemetry = state.config.config.allowAnonymousTelemetry;
19
20 const streamId = uuid();
21
22 // Resolve the file path
23 const resolvedFilepath = await resolveRelativePathInDir(
24 filepath,
25 extras.ideMessenger.ide,
26 );
27 if (!resolvedFilepath) {
28 throw new Error(`File ${filepath} does not exist`);
29 }
30
31 // Parse all search/replace blocks from all diff strings
32 const allBlocks = [];
33 for (let diffIndex = 0; diffIndex < diffs.length; diffIndex++) {
34 const blocks = parseAllSearchReplaceBlocks(diffs[diffIndex]);
35 if (blocks.length === 0) {
36 throw new Error(
37 `No complete search/replace blocks found in diff ${diffIndex + 1}`,
38 );
39 }
40 allBlocks.push(...blocks);
41 }
42
43 if (allBlocks.length === 0) {
44 throw new Error("No complete search/replace blocks found in any diffs");
45 }
46
47 try {
48 // Read the current file content
49 const originalContent =
50 await extras.ideMessenger.ide.readFile(resolvedFilepath);
51 let currentContent = originalContent;
52
53 // Apply all replacements sequentially to build the final content
54 for (let i = 0; i < allBlocks.length; i++) {
55 const block = allBlocks[i];
56 const { searchContent, replaceContent } = block;
57
58 // Find the search content in the current state of the file
59 const match = findSearchMatch(currentContent, searchContent || "");
60
61 // Because we don't have access to use hooks, we check `allowAnonymousTelemetry`
62 // directly rather than using `CustomPostHogProvider`
63 if (allowAnonymousTelemetry) {
64 // Capture telemetry for tool calls
65 posthog.capture("find_replace_match_result", {
66 matchStrategy: match?.strategyName ?? "noMatch",
67 });
68 }
69
70 if (!match) {
71 throw new Error(
72 `Search content not found in block ${i + 1}:\n${searchContent}`,
73 );
74 }
75
76 // Apply the replacement
77 currentContent =
78 currentContent.substring(0, match.startIndex) +
79 (replaceContent || "") +
80 currentContent.substring(match.endIndex);
81 }
82
83 // Single applyToFile call with all accumulated changes
84 // This works becaues of our logic in `applyCodeBlock` that determines
85 // that the full file rewrite here can be applied instantly, so the diff
86 // lines are generated with meyers diff and streamed instantaneously
87 extras.dispatch(
88 updateApplyState({
89 streamId,
90 toolCallId,
91 status: "not-started",
92 }),
93 );
94 void extras.ideMessenger
95 .request("applyToFile", {
96 streamId,
97 toolCallId,
98 text: currentContent,
99 filepath: resolvedFilepath,
100 isSearchAndReplace: true,
101 })
102 .then((res) => {
103 if (res.status === "error") {
104 void extras.dispatch(
105 handleEditToolApplyError({
106 toolCallId,
107 }),
108 );
109 }
110 });
111
112 // Return success - applyToFile will handle the completion state
113 return {
114 respondImmediately: false, // Let apply state handle completion
115 output: undefined,
116 };
117 } catch (error) {
118 throw new Error(
119 `Failed to apply search and replace: ${error instanceof Error ? error.message : String(error)}`,
120 );
121 }
122};