Elffuss BraidHub

kikocis/continue public

4af4016b5aa3 · 5.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 { 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: `This is a tool for making multiple edits to a single file in one operation. It allows you to perform multiple find-and-replace operations efficiently.
35This tool is ideal 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 (must be absolute, not relative)
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 occurences of old_string. This parameter is optional and defaults to false.
43
44IMPORTANT:
45- All edits are applied in sequence, in the order they are provided
46- Each edit operates on the result of the previous edit, so plan your edits carefully to avoid conflicts between sequential operations
47- Edits are atomic - all edits must be valid for the operation to succeed - if any edit fails, none will be applied
48- This tool is ideal when you need to make several changes to different parts of the same file
49
50CRITICAL REQUIREMENTS:
511. ALWAYS use the ${readFileTool.name} tool just before making edits, to understand the file's up-to-date contents and context
522. When making edits:
53- Ensure all edits result in idiomatic, correct code
54- Do not leave the code in a broken state
55- Always use absolute file paths (starting with /)
56- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.
57- Use replace_all for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance.
58- Empty old_string can be used to insert content at the beginning of a file
59
60WARNINGS:
61- If earlier edits affect the text that later edits are trying to find, files can become mangled
62- The tool will fail if edits.old_string doesn't match the file contents exactly (including whitespace)
63- The tool will fail if edits.old_string and edits.new_string are the same - they MUST be different
64- The tool will fail if you have not used the ${readFileTool.name} tool to read the file in this session
65- The tool will fail if the file does not exist - it cannot create new files
66- This tool cannot create new files - the file must already exist`,
67 parameters: {
68 file_path: {
69 type: "string",
70 description: "The absolute path to the file to modify",
71 required: true,
72 },
73 edits: {
74 type: "array",
75 description:
76 "Array of edit operations to perform sequentially on the file",
77 required: true,
78 items: {
79 type: "object",
80 },
81 },
82 },
83 preprocess: async (args) => {
84 const { resolvedPath } = validateAndResolveFilePath(args);
85
86 const { edits } = validateMultiEdit(args);
87
88 const currentContent = fs.readFileSync(resolvedPath, "utf-8");
89 const newContent = executeMultiFindAndReplace(currentContent, edits);
90
91 // Generate diff for preview
92 const diff = generateDiff(currentContent, newContent, resolvedPath);
93
94 return {
95 args: {
96 file_path: resolvedPath,
97 newContent,
98 originalContent: currentContent,
99 editCount: edits.length,
100 },
101 preview: [
102 {
103 type: "text",
104 content: `Will apply ${edits.length} edit${edits.length === 1 ? "" : "s"} to ${resolvedPath}:`,
105 },
106 {
107 type: "diff",
108 content: diff,
109 },
110 ],
111 };
112 },
113 run: async (args: {
114 file_path: string;
115 newContent: string;
116 originalContent: string;
117 editCount: number;
118 }) => {
119 try {
120 fs.writeFileSync(args.file_path, args.newContent, "utf-8");
121
122 // Get lines for telemetry
123 const { added, removed } = calculateLinesOfCodeDiff(
124 args.originalContent,
125 args.newContent,
126 );
127 const language = getLanguageFromFilePath(args.file_path);
128
129 if (added > 0) {
130 telemetryService.recordLinesOfCodeModified("added", added, language);
131 }
132 if (removed > 0) {
133 telemetryService.recordLinesOfCodeModified(
134 "removed",
135 removed,
136 language,
137 );
138 }
139
140 // Generate diff for result display
141 const diff = generateDiff(
142 args.originalContent,
143 args.newContent,
144 args.file_path,
145 );
146
147 return `Successfully edited ${args.file_path} with ${args.editCount} edit${args.editCount === 1 ? "" : "s"}\nDiff:\n${diff}`;
148 } catch (error) {
149 if (error instanceof ContinueError) {
150 throw error;
151 }
152 throw new ContinueError(
153 ContinueErrorReason.FileWriteError,
154 `Error: failed to edit ${args.file_path}: ${
155 error instanceof Error ? error.message : String(error)
156 }`,
157 );
158 }
159 },
160};