Elffuss BraidHub

kikocis/continue public

main · 6.7 KiBRawPermalink
1import * as fs from "fs";
2
3import { validateMultiEdit } from "core/edit/searchAndReplace/multiEditValidation.js";
4import { executeMultiFindAndReplace } from "core/edit/searchAndReplace/performReplace.js";
5import { ContinueError, ContinueErrorReason } from "core/util/errors.js";
6
7import { telemetryService } from "../telemetry/telemetryService.js";
8import {
9 calculateLinesOfCodeDiff,
10 getLanguageFromFilePath,
11} from "../telemetry/utils.js";
12
13import { editTool, validateAndResolveFilePath } from "./edit.js";
14import { readFileTool } from "./readFile.js";
15import { Tool } from "./types.js";
16import { generateDiff } from "./writeFile.js";
17
18export interface EditOperation {
19 old_string: string;
20 new_string: string;
21 replace_all?: boolean;
22}
23
24export interface MultiEditArgs {
25 file_path: string;
26 edits: EditOperation[];
27}
28
29export const multiEditTool: Tool = {
30 name: "MultiEdit",
31 displayName: "MultiEdit",
32 readonly: false,
33 isBuiltIn: true,
34 description: `Use this tool to make multiple edits to a single file in one operation. It allows you to perform multiple find-and-replace operations efficiently.
35Prefer this tool over the ${editTool.name} tool when you need to make multiple edits to the same file.
36
37To make multiple edits to a file, provide the following:
381. file_path: The absolute path to the file to modify. Relative paths can also be used (resolved against cwd) but absolute is preferred
392. edits: An array of edit operations to perform, where each edit contains:
40 - old_string: The text to replace (must match the file contents exactly, including all whitespace/indentation)
41 - new_string: The edited text to replace the old_string
42 - replace_all: Replace all occurrences of old_string. This parameter is optional and defaults to false.
43
44IMPORTANT:
45- Files may be modified between tool calls by users, linters, etc, so always make all edits in one tool call where possible. For example, do not only edit imports if there are other changes in the file, as unused imports may be removed by a linter between tool calls.
46- All edits are applied in sequence, in the order they are provided
47- Each edit operates on the result of the previous edit, so plan your edits carefully to avoid conflicts between sequential operations
48- Edits are atomic - all edits must be valid for the operation to succeed - if any edit fails, none will be applied
49- This tool is ideal when you need to make several changes to different parts of the same file
50
51CRITICAL REQUIREMENTS:
521. ALWAYS use the ${readFileTool.name} tool just before making edits, to understand the file's up-to-date contents and context
532. When making edits:
54- Ensure all edits result in idiomatic, correct code
55- Do not leave the code in a broken state
56- Always use absolute file paths (starting with /)
57- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.
58- Use replace_all for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance.
59- Empty old_string can be used to insert content at the beginning of a file
60
61WARNINGS:
62- If earlier edits affect the text that later edits are trying to find, files can become mangled
63- The tool will fail if edits.old_string doesn't match the file contents exactly (including whitespace)
64- The tool will fail if edits.old_string and edits.new_string are the same - they MUST be different
65- The tool will fail if you have not used the ${readFileTool.name} tool to read the file in this session
66- The tool will fail if the file does not exist - it cannot create new files
67- This tool cannot create new files - the file must already exist`,
68 parameters: {
69 type: "object",
70 required: ["file_path", "edits"],
71 properties: {
72 file_path: {
73 type: "string",
74 description:
75 "Absolute or relative path to the file to modify. Absolute preferred",
76 },
77 edits: {
78 type: "array",
79 description:
80 "Array of edit operations to perform sequentially on the file",
81 items: {
82 type: "object",
83 required: ["old_string", "new_string"],
84 properties: {
85 old_string: {
86 type: "string",
87 description:
88 "The text to replace (exact match including whitespace/indentation)",
89 },
90 new_string: {
91 type: "string",
92 description:
93 "The text to replace it with. MUST be different than old_string.",
94 },
95 replace_all: {
96 type: "boolean",
97 description:
98 "Replace all occurrences of old_string (default false) in the file",
99 },
100 },
101 },
102 },
103 },
104 },
105 preprocess: async (args) => {
106 const { resolvedPath } = validateAndResolveFilePath(args);
107
108 const { edits } = validateMultiEdit(args);
109
110 const currentContent = fs.readFileSync(resolvedPath, "utf-8");
111 const newContent = executeMultiFindAndReplace(currentContent, edits);
112
113 // Generate diff for preview
114 const diff = generateDiff(currentContent, newContent, resolvedPath);
115
116 return {
117 args: {
118 file_path: resolvedPath,
119 newContent,
120 originalContent: currentContent,
121 editCount: edits.length,
122 },
123 preview: [
124 {
125 type: "text",
126 content: `Will apply ${edits.length} edit${edits.length === 1 ? "" : "s"} to ${resolvedPath}:`,
127 },
128 {
129 type: "diff",
130 content: diff,
131 },
132 ],
133 };
134 },
135 run: async (args: {
136 file_path: string;
137 newContent: string;
138 originalContent: string;
139 editCount: number;
140 }) => {
141 try {
142 fs.writeFileSync(args.file_path, args.newContent, "utf-8");
143
144 // Get lines for telemetry
145 const { added, removed } = calculateLinesOfCodeDiff(
146 args.originalContent,
147 args.newContent,
148 );
149 const language = getLanguageFromFilePath(args.file_path);
150
151 if (added > 0) {
152 telemetryService.recordLinesOfCodeModified("added", added, language);
153 }
154 if (removed > 0) {
155 telemetryService.recordLinesOfCodeModified(
156 "removed",
157 removed,
158 language,
159 );
160 }
161
162 // Generate diff for result display
163 const diff = generateDiff(
164 args.originalContent,
165 args.newContent,
166 args.file_path,
167 );
168
169 return `Successfully edited ${args.file_path} with ${args.editCount} edit${args.editCount === 1 ? "" : "s"}\nDiff:\n${diff}`;
170 } catch (error) {
171 if (error instanceof ContinueError) {
172 throw error;
173 }
174 throw new ContinueError(
175 ContinueErrorReason.FileWriteError,
176 `Error: failed to edit ${args.file_path}: ${
177 error instanceof Error ? error.message : String(error)
178 }`,
179 );
180 }
181 },
182};