Elffuss BraidHub

kikocis/continue public

8aab215acf3c · 9.6 KiBRawPermalink
1import * as fs from "fs";
2import * as path from "path";
3
4import { throwIfFileIsSecurityConcern } from "core/indexing/ignore.js";
5
6import { telemetryService } from "../telemetry/telemetryService.js";
7import {
8 calculateLinesOfCodeDiff,
9 getLanguageFromFilePath,
10} from "../telemetry/utils.js";
11
12import { markFileAsRead, readFilesSet } from "./edit.js";
13import { Tool } from "./types.js";
14import { generateDiff } from "./writeFile.js";
15
16export { markFileAsRead };
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
29// Function to check if file has been read (shared with edit tool)
30function hasFileBeenRead(filePath: string): boolean {
31 return readFilesSet.has(filePath);
32}
33
34// Helper functions for multiEdit validation
35function validateMultiEditArgs(args: any): {
36 original_path: string;
37 file_path: string;
38 edits: EditOperation[];
39} {
40 const { file_path, edits } = args as MultiEditArgs;
41
42 if (!file_path) {
43 throw new Error("file_path is required");
44 }
45 if (!edits || !Array.isArray(edits) || edits.length === 0) {
46 throw new Error(
47 "edits array is required and must contain at least one edit",
48 );
49 }
50
51 // Convert relative paths to absolute paths
52 const absolutePath = path.isAbsolute(file_path)
53 ? file_path
54 : path.resolve(process.cwd(), file_path);
55
56 return { original_path: file_path, file_path: absolutePath, edits };
57}
58
59function validateEdits(edits: EditOperation[]): void {
60 for (let i = 0; i < edits.length; i++) {
61 const edit = edits[i];
62 if (!edit.old_string && edit.old_string !== "") {
63 throw new Error(`Edit ${i + 1}: old_string is required`);
64 }
65 if (edit.new_string === undefined) {
66 throw new Error(`Edit ${i + 1}: new_string is required`);
67 }
68 if (edit.old_string === edit.new_string) {
69 throw new Error(
70 `Edit ${i + 1}: old_string and new_string must be different`,
71 );
72 }
73 }
74}
75
76function validateFileAccess(
77 original_path: string,
78 file_path: string,
79 isCreatingNewFile: boolean,
80): void {
81 if (isCreatingNewFile) {
82 // For new file creation, check if parent directory exists
83 const parentDir = path.dirname(file_path);
84 if (parentDir && !fs.existsSync(parentDir)) {
85 throw new Error(`Parent directory does not exist: ${parentDir}`);
86 }
87 } else {
88 // For existing files, check if file has been read
89 // Check with the original path first, then with absolute path
90 if (!hasFileBeenRead(original_path) && !hasFileBeenRead(file_path)) {
91 throw new Error(
92 `You must use the Read tool to read ${original_path} before editing it.`,
93 );
94 }
95 if (!fs.existsSync(file_path)) {
96 throw new Error(`File ${file_path} does not exist`);
97 }
98 }
99}
100
101function applyEdit(
102 content: string,
103 edit: EditOperation,
104 editIndex: number,
105 isFirstEditOfNewFile: boolean,
106): string {
107 const { old_string, new_string, replace_all = false } = edit;
108
109 // For new file creation, the first edit can have empty old_string
110 if (isFirstEditOfNewFile && old_string === "") {
111 return new_string;
112 }
113
114 // Check if old_string exists in current content
115 if (!content.includes(old_string)) {
116 throw new Error(
117 `Edit ${editIndex + 1}: String not found in file: "${old_string}"`,
118 );
119 }
120
121 if (replace_all) {
122 // Replace all occurrences
123 return content.split(old_string).join(new_string);
124 } else {
125 // Replace only the first occurrence, but check for uniqueness
126 const occurrences = content.split(old_string).length - 1;
127 if (occurrences > 1) {
128 throw new Error(
129 `Edit ${editIndex + 1}: String "${old_string}" appears ${occurrences} times in the file. Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.`,
130 );
131 }
132 return content.replace(old_string, new_string);
133 }
134}
135
136export const multiEditTool: Tool = {
137 name: "MultiEdit",
138 displayName: "MultiEdit",
139 readonly: false,
140 isBuiltIn: true,
141 description: `This is a tool for making multiple edits to a single file in one operation. It
142is built on top of the Edit tool and allows you to perform multiple
143find-and-replace operations efficiently. Prefer this tool over the Edit tool
144when you need to make multiple edits to the same file.
145
146
147Before using this tool:
148
149
1501. Use the Read tool to understand the file's contents and context
151
1522. Verify the directory path is correct
153
154
155To make multiple file edits, provide the following:
156
1571. file_path: The absolute path to the file to modify (must be absolute, not
158relative)
159
1602. edits: An array of edit operations to perform, where each edit contains:
161 - old_string: The text to replace (must match the file contents exactly, including all whitespace and indentation)
162 - new_string: The edited text to replace the old_string
163 - replace_all: Replace all occurences of old_string. This parameter is optional and defaults to false.
164
165IMPORTANT:
166
167- All edits are applied in sequence, in the order they are provided
168
169- Each edit operates on the result of the previous edit
170
171- All edits must be valid for the operation to succeed - if any edit fails,
172none will be applied
173
174- This tool is ideal when you need to make several changes to different parts
175of the same file
176
177- For Jupyter notebooks (.ipynb files), use the NotebookEdit instead
178
179
180CRITICAL REQUIREMENTS:
181
1821. All edits follow the same requirements as the single Edit tool
183
1842. The edits are atomic - either all succeed or none are applied
185
1863. Plan your edits carefully to avoid conflicts between sequential operations
187
188
189WARNING:
190
191- The tool will fail if edits.old_string doesn't match the file contents
192exactly (including whitespace)
193
194- The tool will fail if edits.old_string and edits.new_string are the same
195
196- Since edits are applied in sequence, ensure that earlier edits don't affect
197the text that later edits are trying to find
198
199
200When making edits:
201
202- Ensure all edits result in idiomatic, correct code
203
204- Do not leave the code in a broken state
205
206- Always use absolute file paths (starting with /)
207
208- Only use emojis if the user explicitly requests it. Avoid adding emojis to
209files unless asked.
210
211- Use replace_all for replacing and renaming strings across the file. This
212parameter is useful if you want to rename a variable for instance.
213
214
215If you want to create a new file, use:
216
217- A new file path, including dir name if needed
218
219- First edit: empty old_string and the new file's contents as new_string
220
221- Subsequent edits: normal edit operations on the created content`,
222 parameters: {
223 file_path: {
224 type: "string",
225 description: "The absolute path to the file to modify",
226 required: true,
227 },
228 edits: {
229 type: "array",
230 description:
231 "Array of edit operations to perform sequentially on the file",
232 required: true,
233 items: {
234 type: "object",
235 },
236 },
237 },
238 preprocess: async (args) => {
239 // Validate and extract arguments
240 const { original_path, file_path, edits } = validateMultiEditArgs(args);
241
242 throwIfFileIsSecurityConcern(file_path);
243
244 // Validate each edit operation
245 validateEdits(edits);
246
247 // Check if this is creating a new file (first edit has empty old_string)
248 const isCreatingNewFile = edits[0].old_string === "";
249
250 // Validate file access
251 validateFileAccess(original_path, file_path, isCreatingNewFile);
252
253 // Read current file content (or start with empty for new files)
254 let currentContent = "";
255 if (!isCreatingNewFile) {
256 currentContent = fs.readFileSync(file_path, "utf-8");
257 }
258
259 const originalContent = currentContent;
260 let newContent = currentContent;
261
262 // Apply all edits sequentially
263 for (let i = 0; i < edits.length; i++) {
264 const isFirstEditOfNewFile = i === 0 && isCreatingNewFile;
265 newContent = applyEdit(newContent, edits[i], i, isFirstEditOfNewFile);
266 }
267
268 // Generate diff for preview
269 const diff = generateDiff(originalContent, newContent, file_path);
270
271 return {
272 args: {
273 file_path,
274 newContent,
275 originalContent,
276 isCreatingNewFile,
277 editCount: edits.length,
278 },
279 preview: [
280 {
281 type: "text",
282 content: `Will apply ${edits.length} edit${edits.length === 1 ? "" : "s"} to ${isCreatingNewFile ? "create" : "modify"} ${file_path}:`,
283 },
284 {
285 type: "diff",
286 content: diff,
287 },
288 ],
289 };
290 },
291 run: async (args: {
292 file_path: string;
293 newContent: string;
294 originalContent: string;
295 isCreatingNewFile: boolean;
296 editCount: number;
297 }) => {
298 try {
299 fs.writeFileSync(args.file_path, args.newContent, "utf-8");
300
301 // Get lines for telemetry
302 const { added, removed } = calculateLinesOfCodeDiff(
303 args.originalContent,
304 args.newContent,
305 );
306 const language = getLanguageFromFilePath(args.file_path);
307
308 if (added > 0) {
309 telemetryService.recordLinesOfCodeModified("added", added, language);
310 }
311 if (removed > 0) {
312 telemetryService.recordLinesOfCodeModified(
313 "removed",
314 removed,
315 language,
316 );
317 }
318
319 // Generate diff for result display
320 const diff = generateDiff(
321 args.originalContent,
322 args.newContent,
323 args.file_path,
324 );
325
326 const action = args.isCreatingNewFile ? "created" : "edited";
327 return `Successfully ${action} ${args.file_path} with ${args.editCount} edit${args.editCount === 1 ? "" : "s"}\nDiff:\n${diff}`;
328 } catch (error) {
329 throw new Error(
330 `Error: failed to edit ${args.file_path}: ${
331 error instanceof Error ? error.message : String(error)
332 }`,
333 );
334 }
335 },
336};