Elffuss BraidHub

kikocis/continue public

c4ec337463d8 · 5.7 KiBRawPermalink
1import * as fs from "fs";
2
3import { throwIfFileIsSecurityConcern } from "core/indexing/ignore.js";
4
5import { telemetryService } from "../telemetry/telemetryService.js";
6import {
7 calculateLinesOfCodeDiff,
8 getLanguageFromFilePath,
9} from "../telemetry/utils.js";
10
11import { Tool } from "./types.js";
12import { generateDiff } from "./writeFile.js";
13
14export interface EditArgs {
15 file_path: string;
16 old_string: string;
17 new_string: string;
18 replace_all?: boolean;
19}
20
21// Track files that have been read in the current session
22export const readFilesSet = new Set<string>();
23
24export const editTool: Tool = {
25 name: "Edit",
26 displayName: "Edit",
27 readonly: false,
28 isBuiltIn: true,
29 description: `Performs exact string replacements in files.
30
31
32Usage:
33
34- You must use your \`Read\` tool at least once in the conversation before
35editing. This tool will error if you attempt an edit without reading the file.
36
37- When editing text from Read tool output, ensure you preserve the exact
38indentation (tabs/spaces) as it appears AFTER the line number prefix. The line
39number prefix format is: spaces + line number + tab. Everything after that tab
40is the actual file content to match. Never include any part of the line number
41prefix in the old_string or new_string.
42
43- ALWAYS prefer editing existing files in the codebase. NEVER write new files
44unless explicitly required.
45
46- Only use emojis if the user explicitly requests it. Avoid adding emojis to
47files unless asked.
48
49- The edit will FAIL if \`old_string\` is not unique in the file. Either provide
50a larger string with more surrounding context to make it unique or use
51\`replace_all\` to change every instance of \`old_string\`.
52
53- Use \`replace_all\` for replacing and renaming strings across the file. This
54parameter is useful if you want to rename a variable for instance.`,
55 parameters: {
56 file_path: {
57 type: "string",
58 description: "The absolute path to the file to modify",
59 required: true,
60 },
61 old_string: {
62 type: "string",
63 description: "The text to replace",
64 required: true,
65 },
66 new_string: {
67 type: "string",
68 description:
69 "The text to replace it with (must be different from old_string)",
70 required: true,
71 },
72 replace_all: {
73 type: "boolean",
74 description: "Replace all occurences of old_string (default false)",
75 required: false,
76 },
77 },
78 preprocess: async (args) => {
79 const {
80 file_path,
81 old_string,
82 new_string,
83 replace_all = false,
84 } = args as EditArgs;
85 throwIfFileIsSecurityConcern(file_path);
86 // Check if file has been read
87 if (!readFilesSet.has(file_path)) {
88 throw new Error(
89 `You must use the Read tool to read ${file_path} before editing it.`,
90 );
91 }
92
93 // Validate arguments
94 if (!file_path) {
95 throw new Error("file_path is required");
96 }
97 if (!old_string) {
98 throw new Error("old_string is required");
99 }
100 if (new_string === undefined) {
101 throw new Error("new_string is required");
102 }
103 if (old_string === new_string) {
104 throw new Error("old_string and new_string must be different");
105 }
106
107 // Check if file exists
108 if (!fs.existsSync(file_path)) {
109 throw new Error(`File ${file_path} does not exist`);
110 }
111
112 // Read current file content
113 const oldContent = fs.readFileSync(file_path, "utf-8");
114
115 // Check if old_string exists in the file
116 if (!oldContent.includes(old_string)) {
117 throw new Error(`String not found in file: ${old_string}`);
118 }
119
120 let newContent: string;
121
122 if (replace_all) {
123 // Replace all occurrences
124 newContent = oldContent.split(old_string).join(new_string);
125 } else {
126 // Replace only the first occurrence
127 const occurrences = oldContent.split(old_string).length - 1;
128 if (occurrences > 1) {
129 throw new Error(
130 `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.`,
131 );
132 }
133 newContent = oldContent.replace(old_string, new_string);
134 }
135
136 // Generate diff for preview
137 const diff = generateDiff(oldContent, newContent, file_path);
138
139 return {
140 args: {
141 file_path,
142 newContent,
143 oldContent,
144 },
145 preview: [
146 {
147 type: "text",
148 content: "Will make the following changes:",
149 },
150 {
151 type: "diff",
152 content: diff,
153 },
154 ],
155 };
156 },
157 run: async (args: {
158 file_path: string;
159 newContent: string;
160 oldContent: string;
161 }) => {
162 try {
163 fs.writeFileSync(args.file_path, args.newContent, "utf-8");
164
165 // Get lines for telemetry
166 const { added, removed } = calculateLinesOfCodeDiff(
167 args.oldContent,
168 args.newContent,
169 );
170 const language = getLanguageFromFilePath(args.file_path);
171
172 if (added > 0) {
173 telemetryService.recordLinesOfCodeModified("added", added, language);
174 }
175 if (removed > 0) {
176 telemetryService.recordLinesOfCodeModified(
177 "removed",
178 removed,
179 language,
180 );
181 }
182
183 // Generate diff for result display
184 const diff = generateDiff(
185 args.oldContent,
186 args.newContent,
187 args.file_path,
188 );
189
190 return `Successfully edited ${args.file_path}\nDiff:\n${diff}`;
191 } catch (error) {
192 throw new Error(
193 `Error: failed to edit ${args.file_path}: ${
194 error instanceof Error ? error.message : String(error)
195 }`,
196 );
197 }
198 },
199};
200
201// Function to mark a file as read (to be called from the read tool)
202export function markFileAsRead(filePath: string) {
203 readFilesSet.add(filePath);
204}