Elffuss BraidHub

kikocis/continue public

3ff29c567dd0 · 6.4 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. 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- 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 type: "object",
69 required: ["file_path", "edits"],
70 properties: {
71 file_path: {
72 type: "string",
73 description:
74 "Absolute or relative path to the file to modify. Absolute preferred",
75 },
76 edits: {
77 type: "array",
78 description:
79 "Array of edit operations to perform sequentially on the file",
80 items: {
81 type: "object",
82 required: ["old_string", "new_string"],
83 properties: {
84 old_string: {
85 type: "string",
86 description:
87 "The text to replace (exact match including whitespace/indentation)",
88 },
89 new_string: {
90 type: "string",
91 description:
92 "The text to replace it with. MUST be different than old_string.",
93 },
94 replace_all: {
95 type: "boolean",
96 description:
97 "Replace all occurrences of old_string (default false) in the file",
98 },
99 },
100 },
101 },
102 },
103 },
104 preprocess: async (args) => {
105 const { resolvedPath } = validateAndResolveFilePath(args);
106
107 const { edits } = validateMultiEdit(args);
108
109 const currentContent = fs.readFileSync(resolvedPath, "utf-8");
110 const newContent = executeMultiFindAndReplace(currentContent, edits);
111
112 // Generate diff for preview
113 const diff = generateDiff(currentContent, newContent, resolvedPath);
114
115 return {
116 args: {
117 file_path: resolvedPath,
118 newContent,
119 originalContent: currentContent,
120 editCount: edits.length,
121 },
122 preview: [
123 {
124 type: "text",
125 content: `Will apply ${edits.length} edit${edits.length === 1 ? "" : "s"} to ${resolvedPath}:`,
126 },
127 {
128 type: "diff",
129 content: diff,
130 },
131 ],
132 };
133 },
134 run: async (args: {
135 file_path: string;
136 newContent: string;
137 originalContent: string;
138 editCount: number;
139 }) => {
140 try {
141 fs.writeFileSync(args.file_path, args.newContent, "utf-8");
142
143 // Get lines for telemetry
144 const { added, removed } = calculateLinesOfCodeDiff(
145 args.originalContent,
146 args.newContent,
147 );
148 const language = getLanguageFromFilePath(args.file_path);
149
150 if (added > 0) {
151 telemetryService.recordLinesOfCodeModified("added", added, language);
152 }
153 if (removed > 0) {
154 telemetryService.recordLinesOfCodeModified(
155 "removed",
156 removed,
157 language,
158 );
159 }
160
161 // Generate diff for result display
162 const diff = generateDiff(
163 args.originalContent,
164 args.newContent,
165 args.file_path,
166 );
167
168 return `Successfully edited ${args.file_path} with ${args.editCount} edit${args.editCount === 1 ? "" : "s"}\nDiff:\n${diff}`;
169 } catch (error) {
170 if (error instanceof ContinueError) {
171 throw error;
172 }
173 throw new ContinueError(
174 ContinueErrorReason.FileWriteError,
175 `Error: failed to edit ${args.file_path}: ${
176 error instanceof Error ? error.message : String(error)
177 }`,
178 );
179 }
180 },
181};