@vybestack/llxprt-code-core 0.7.0-nightly.251220.86336527d → 0.7.0-nightly.251221.9d28e80b6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/src/auth/anthropic-device-flow.d.ts +1 -0
- package/dist/src/auth/anthropic-device-flow.js +1 -0
- package/dist/src/auth/anthropic-device-flow.js.map +1 -1
- package/dist/src/config/config.d.ts +0 -3
- package/dist/src/config/config.js +1 -12
- package/dist/src/config/config.js.map +1 -1
- package/dist/src/core/client.js +9 -4
- package/dist/src/core/client.js.map +1 -1
- package/dist/src/core/geminiChat.d.ts +5 -0
- package/dist/src/core/geminiChat.js +31 -13
- package/dist/src/core/geminiChat.js.map +1 -1
- package/dist/src/policy/config.js +0 -1
- package/dist/src/policy/config.js.map +1 -1
- package/dist/src/policy/policies/write.toml +0 -5
- package/dist/src/providers/openai-responses/CODEX_MODELS.js +6 -0
- package/dist/src/providers/openai-responses/CODEX_MODELS.js.map +1 -1
- package/dist/src/services/history/ContentConverters.js +33 -5
- package/dist/src/services/history/ContentConverters.js.map +1 -1
- package/dist/src/services/history/HistoryService.d.ts +30 -1
- package/dist/src/services/history/HistoryService.js +335 -10
- package/dist/src/services/history/HistoryService.js.map +1 -1
- package/dist/src/tools/tool-names.d.ts +1 -2
- package/dist/src/tools/tool-names.js +0 -1
- package/dist/src/tools/tool-names.js.map +1 -1
- package/package.json +1 -1
- package/dist/src/tools/smart-edit.d.ts +0 -93
- package/dist/src/tools/smart-edit.js +0 -742
- package/dist/src/tools/smart-edit.js.map +0 -1
|
@@ -1,742 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @license
|
|
3
|
-
* Copyright 2025 Google LLC
|
|
4
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
5
|
-
*/
|
|
6
|
-
import * as fs from 'node:fs';
|
|
7
|
-
import * as path from 'node:path';
|
|
8
|
-
import * as crypto from 'node:crypto';
|
|
9
|
-
import * as Diff from 'diff';
|
|
10
|
-
import { BaseDeclarativeTool, BaseToolInvocation, Kind, ToolConfirmationOutcome, } from './tools.js';
|
|
11
|
-
import { ToolErrorType } from './tool-error.js';
|
|
12
|
-
import { makeRelative, shortenPath } from '../utils/paths.js';
|
|
13
|
-
import { isNodeError } from '../utils/errors.js';
|
|
14
|
-
import { ApprovalMode } from '../config/config.js';
|
|
15
|
-
import { DEFAULT_DIFF_OPTIONS, getDiffStat } from './diffOptions.js';
|
|
16
|
-
import { ReadFileTool } from './read-file.js';
|
|
17
|
-
import { IDEConnectionStatus } from '../ide/ide-client.js';
|
|
18
|
-
import { FixLLMEditWithInstruction } from '../utils/llm-edit-fixer.js';
|
|
19
|
-
export function applyReplacement(currentContent, oldString, newString, isNewFile) {
|
|
20
|
-
if (isNewFile) {
|
|
21
|
-
return newString;
|
|
22
|
-
}
|
|
23
|
-
if (currentContent === null) {
|
|
24
|
-
// Should not happen if not a new file, but defensively return empty or newString if oldString is also empty
|
|
25
|
-
return oldString === '' ? newString : '';
|
|
26
|
-
}
|
|
27
|
-
// If oldString is empty and it's not a new file, do not modify the content.
|
|
28
|
-
if (oldString === '' && !isNewFile) {
|
|
29
|
-
return currentContent;
|
|
30
|
-
}
|
|
31
|
-
return currentContent.replaceAll(oldString, newString);
|
|
32
|
-
}
|
|
33
|
-
/**
|
|
34
|
-
* Creates a SHA256 hash of the given content.
|
|
35
|
-
* @param content The string content to hash.
|
|
36
|
-
* @returns A hex-encoded hash string.
|
|
37
|
-
*/
|
|
38
|
-
function hashContent(content) {
|
|
39
|
-
return crypto.createHash('sha256').update(content).digest('hex');
|
|
40
|
-
}
|
|
41
|
-
function restoreTrailingNewline(originalContent, modifiedContent) {
|
|
42
|
-
const hadTrailingNewline = originalContent.endsWith('\n');
|
|
43
|
-
if (hadTrailingNewline && !modifiedContent.endsWith('\n')) {
|
|
44
|
-
return modifiedContent + '\n';
|
|
45
|
-
}
|
|
46
|
-
else if (!hadTrailingNewline && modifiedContent.endsWith('\n')) {
|
|
47
|
-
return modifiedContent.replace(/\n$/, '');
|
|
48
|
-
}
|
|
49
|
-
return modifiedContent;
|
|
50
|
-
}
|
|
51
|
-
/**
|
|
52
|
-
* Escapes characters with special meaning in regular expressions.
|
|
53
|
-
* @param str The string to escape.
|
|
54
|
-
* @returns The escaped string.
|
|
55
|
-
*/
|
|
56
|
-
function escapeRegex(str) {
|
|
57
|
-
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
|
|
58
|
-
}
|
|
59
|
-
async function calculateExactReplacement(context) {
|
|
60
|
-
const { currentContent, params } = context;
|
|
61
|
-
const { old_string, new_string } = params;
|
|
62
|
-
const normalizedCode = currentContent;
|
|
63
|
-
const normalizedSearch = old_string.replace(/\r\n/g, '\n');
|
|
64
|
-
const normalizedReplace = new_string.replace(/\r\n/g, '\n');
|
|
65
|
-
const exactOccurrences = normalizedCode.split(normalizedSearch).length - 1;
|
|
66
|
-
if (exactOccurrences > 0) {
|
|
67
|
-
let modifiedCode = normalizedCode.replaceAll(normalizedSearch, normalizedReplace);
|
|
68
|
-
modifiedCode = restoreTrailingNewline(currentContent, modifiedCode);
|
|
69
|
-
return {
|
|
70
|
-
newContent: modifiedCode,
|
|
71
|
-
occurrences: exactOccurrences,
|
|
72
|
-
finalOldString: normalizedSearch,
|
|
73
|
-
finalNewString: normalizedReplace,
|
|
74
|
-
};
|
|
75
|
-
}
|
|
76
|
-
return null;
|
|
77
|
-
}
|
|
78
|
-
async function calculateFlexibleReplacement(context) {
|
|
79
|
-
const { currentContent, params } = context;
|
|
80
|
-
const { old_string, new_string } = params;
|
|
81
|
-
const normalizedCode = currentContent;
|
|
82
|
-
const normalizedSearch = old_string.replace(/\r\n/g, '\n');
|
|
83
|
-
const normalizedReplace = new_string.replace(/\r\n/g, '\n');
|
|
84
|
-
const sourceLines = normalizedCode.match(/.*(?:\n|$)/g)?.slice(0, -1) ?? [];
|
|
85
|
-
const searchLinesStripped = normalizedSearch
|
|
86
|
-
.split('\n')
|
|
87
|
-
.map((line) => line.trim());
|
|
88
|
-
const replaceLines = normalizedReplace.split('\n');
|
|
89
|
-
let flexibleOccurrences = 0;
|
|
90
|
-
let i = 0;
|
|
91
|
-
while (i <= sourceLines.length - searchLinesStripped.length) {
|
|
92
|
-
const window = sourceLines.slice(i, i + searchLinesStripped.length);
|
|
93
|
-
const windowStripped = window.map((line) => line.trim());
|
|
94
|
-
const isMatch = windowStripped.every((line, index) => line === searchLinesStripped[index]);
|
|
95
|
-
if (isMatch) {
|
|
96
|
-
flexibleOccurrences++;
|
|
97
|
-
const firstLineInMatch = window[0];
|
|
98
|
-
const indentationMatch = firstLineInMatch.match(/^(\s*)/);
|
|
99
|
-
const indentation = indentationMatch ? indentationMatch[1] : '';
|
|
100
|
-
const newBlockWithIndent = replaceLines.map((line) => `${indentation}${line}`);
|
|
101
|
-
sourceLines.splice(i, searchLinesStripped.length, newBlockWithIndent.join('\n'));
|
|
102
|
-
i += replaceLines.length;
|
|
103
|
-
}
|
|
104
|
-
else {
|
|
105
|
-
i++;
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
if (flexibleOccurrences > 0) {
|
|
109
|
-
let modifiedCode = sourceLines.join('');
|
|
110
|
-
modifiedCode = restoreTrailingNewline(currentContent, modifiedCode);
|
|
111
|
-
return {
|
|
112
|
-
newContent: modifiedCode,
|
|
113
|
-
occurrences: flexibleOccurrences,
|
|
114
|
-
finalOldString: normalizedSearch,
|
|
115
|
-
finalNewString: normalizedReplace,
|
|
116
|
-
};
|
|
117
|
-
}
|
|
118
|
-
return null;
|
|
119
|
-
}
|
|
120
|
-
async function calculateRegexReplacement(context) {
|
|
121
|
-
const { currentContent, params } = context;
|
|
122
|
-
const { old_string, new_string } = params;
|
|
123
|
-
// Normalize line endings for consistent processing.
|
|
124
|
-
const normalizedSearch = old_string.replace(/\r\n/g, '\n');
|
|
125
|
-
const normalizedReplace = new_string.replace(/\r\n/g, '\n');
|
|
126
|
-
// This logic is ported from your Python implementation.
|
|
127
|
-
// It builds a flexible, multi-line regex from a search string.
|
|
128
|
-
const delimiters = ['(', ')', ':', '[', ']', '{', '}', '>', '<', '='];
|
|
129
|
-
let processedString = normalizedSearch;
|
|
130
|
-
for (const delim of delimiters) {
|
|
131
|
-
processedString = processedString.split(delim).join(` ${delim} `);
|
|
132
|
-
}
|
|
133
|
-
// Split by any whitespace and remove empty strings.
|
|
134
|
-
const tokens = processedString.split(/\s+/).filter(Boolean);
|
|
135
|
-
if (tokens.length === 0) {
|
|
136
|
-
return null;
|
|
137
|
-
}
|
|
138
|
-
const escapedTokens = tokens.map(escapeRegex);
|
|
139
|
-
// Join tokens with `\s*` to allow for flexible whitespace between them.
|
|
140
|
-
const pattern = escapedTokens.join('\\s*');
|
|
141
|
-
// The final pattern captures leading whitespace (indentation) and then matches the token pattern.
|
|
142
|
-
// 'm' flag enables multi-line mode, so '^' matches the start of any line.
|
|
143
|
-
const finalPattern = `^(\\s*)${pattern}`;
|
|
144
|
-
const flexibleRegex = new RegExp(finalPattern, 'm');
|
|
145
|
-
const match = flexibleRegex.exec(currentContent);
|
|
146
|
-
if (!match) {
|
|
147
|
-
return null;
|
|
148
|
-
}
|
|
149
|
-
const indentation = match[1] || '';
|
|
150
|
-
const newLines = normalizedReplace.split('\n');
|
|
151
|
-
const newBlockWithIndent = newLines
|
|
152
|
-
.map((line) => `${indentation}${line}`)
|
|
153
|
-
.join('\n');
|
|
154
|
-
// Use replace with the regex to substitute the matched content.
|
|
155
|
-
// Since the regex doesn't have the 'g' flag, it will only replace the first occurrence.
|
|
156
|
-
const modifiedCode = currentContent.replace(flexibleRegex, newBlockWithIndent);
|
|
157
|
-
return {
|
|
158
|
-
newContent: restoreTrailingNewline(currentContent, modifiedCode),
|
|
159
|
-
occurrences: 1, // This method is designed to find and replace only the first occurrence.
|
|
160
|
-
finalOldString: normalizedSearch,
|
|
161
|
-
finalNewString: normalizedReplace,
|
|
162
|
-
};
|
|
163
|
-
}
|
|
164
|
-
/**
|
|
165
|
-
* Detects the line ending style of a string.
|
|
166
|
-
* @param content The string content to analyze.
|
|
167
|
-
* @returns '\r\n' for Windows-style, '\n' for Unix-style.
|
|
168
|
-
*/
|
|
169
|
-
function detectLineEnding(content) {
|
|
170
|
-
// If a Carriage Return is found, assume Windows-style endings.
|
|
171
|
-
// This is a simple but effective heuristic.
|
|
172
|
-
return content.includes('\r\n') ? '\r\n' : '\n';
|
|
173
|
-
}
|
|
174
|
-
export async function calculateReplacement(context) {
|
|
175
|
-
const { currentContent, params } = context;
|
|
176
|
-
const { old_string, new_string } = params;
|
|
177
|
-
const normalizedSearch = old_string.replace(/\r\n/g, '\n');
|
|
178
|
-
const normalizedReplace = new_string.replace(/\r\n/g, '\n');
|
|
179
|
-
if (normalizedSearch === '') {
|
|
180
|
-
return {
|
|
181
|
-
newContent: currentContent,
|
|
182
|
-
occurrences: 0,
|
|
183
|
-
finalOldString: normalizedSearch,
|
|
184
|
-
finalNewString: normalizedReplace,
|
|
185
|
-
};
|
|
186
|
-
}
|
|
187
|
-
const exactResult = await calculateExactReplacement(context);
|
|
188
|
-
if (exactResult) {
|
|
189
|
-
return exactResult;
|
|
190
|
-
}
|
|
191
|
-
const flexibleResult = await calculateFlexibleReplacement(context);
|
|
192
|
-
if (flexibleResult) {
|
|
193
|
-
return flexibleResult;
|
|
194
|
-
}
|
|
195
|
-
const regexResult = await calculateRegexReplacement(context);
|
|
196
|
-
if (regexResult) {
|
|
197
|
-
return regexResult;
|
|
198
|
-
}
|
|
199
|
-
return {
|
|
200
|
-
newContent: currentContent,
|
|
201
|
-
occurrences: 0,
|
|
202
|
-
finalOldString: normalizedSearch,
|
|
203
|
-
finalNewString: normalizedReplace,
|
|
204
|
-
};
|
|
205
|
-
}
|
|
206
|
-
export function getErrorReplaceResult(params, occurrences, expectedReplacements, finalOldString, finalNewString) {
|
|
207
|
-
let error = undefined;
|
|
208
|
-
if (occurrences === 0) {
|
|
209
|
-
error = {
|
|
210
|
-
display: `Failed to edit, could not find the string to replace.`,
|
|
211
|
-
raw: `Failed to edit, 0 occurrences found for old_string (${finalOldString}). Original old_string was (${params.old_string}) in ${params.file_path}. No edits made. The exact text in old_string was not found. Ensure you're not escaping content incorrectly and check whitespace, indentation, and context. Use ${ReadFileTool.Name} tool to verify.`,
|
|
212
|
-
type: ToolErrorType.EDIT_NO_OCCURRENCE_FOUND,
|
|
213
|
-
};
|
|
214
|
-
}
|
|
215
|
-
else if (occurrences !== expectedReplacements) {
|
|
216
|
-
const occurrenceTerm = expectedReplacements === 1 ? 'occurrence' : 'occurrences';
|
|
217
|
-
error = {
|
|
218
|
-
display: `Failed to edit, expected ${expectedReplacements} ${occurrenceTerm} but found ${occurrences}.`,
|
|
219
|
-
raw: `Failed to edit, Expected ${expectedReplacements} ${occurrenceTerm} but found ${occurrences} for old_string in file: ${params.file_path}`,
|
|
220
|
-
type: ToolErrorType.EDIT_EXPECTED_OCCURRENCE_MISMATCH,
|
|
221
|
-
};
|
|
222
|
-
}
|
|
223
|
-
else if (finalOldString === finalNewString) {
|
|
224
|
-
error = {
|
|
225
|
-
display: `No changes to apply. The old_string and new_string are identical.`,
|
|
226
|
-
raw: `No changes to apply. The old_string and new_string are identical in file: ${params.file_path}`,
|
|
227
|
-
type: ToolErrorType.EDIT_NO_CHANGE,
|
|
228
|
-
};
|
|
229
|
-
}
|
|
230
|
-
return error;
|
|
231
|
-
}
|
|
232
|
-
class EditToolInvocation extends BaseToolInvocation {
|
|
233
|
-
config;
|
|
234
|
-
constructor(config, params, messageBus) {
|
|
235
|
-
super(params, messageBus);
|
|
236
|
-
this.config = config;
|
|
237
|
-
}
|
|
238
|
-
getToolName() {
|
|
239
|
-
return SmartEditTool.Name;
|
|
240
|
-
}
|
|
241
|
-
toolLocations() {
|
|
242
|
-
return [{ path: this.params.file_path }];
|
|
243
|
-
}
|
|
244
|
-
async attemptSelfCorrection(params, currentContent, initialError, abortSignal, originalLineEnding) {
|
|
245
|
-
// In order to keep from clobbering edits made outside our system,
|
|
246
|
-
// check if the file has been modified since we first read it.
|
|
247
|
-
let errorForLlmEditFixer = initialError.raw;
|
|
248
|
-
let contentForLlmEditFixer = currentContent;
|
|
249
|
-
const initialContentHash = hashContent(currentContent);
|
|
250
|
-
const onDiskContent = await this.config
|
|
251
|
-
.getFileSystemService()
|
|
252
|
-
.readTextFile(params.file_path);
|
|
253
|
-
const onDiskContentHash = hashContent(onDiskContent.replace(/\r\n/g, '\n'));
|
|
254
|
-
if (initialContentHash !== onDiskContentHash) {
|
|
255
|
-
// The file has changed on disk since we first read it.
|
|
256
|
-
// Use the latest content for the correction attempt.
|
|
257
|
-
contentForLlmEditFixer = onDiskContent.replace(/\r\n/g, '\n');
|
|
258
|
-
errorForLlmEditFixer = `The initial edit attempt failed with the following error: "${initialError.raw}". However, the file has been modified by either the user or an external process since that edit attempt. The file content provided to you is the latest version. Please base your correction on this new content.`;
|
|
259
|
-
}
|
|
260
|
-
const fixedEdit = await FixLLMEditWithInstruction(params.instruction, params.old_string, params.new_string, errorForLlmEditFixer, contentForLlmEditFixer, this.config.getGeminiClient(), abortSignal);
|
|
261
|
-
if (fixedEdit.noChangesRequired) {
|
|
262
|
-
return {
|
|
263
|
-
currentContent,
|
|
264
|
-
newContent: currentContent,
|
|
265
|
-
occurrences: 0,
|
|
266
|
-
isNewFile: false,
|
|
267
|
-
error: {
|
|
268
|
-
display: `No changes required. The file already meets the specified conditions.`,
|
|
269
|
-
raw: `A secondary check by an LLM determined that no changes were necessary to fulfill the instruction. Explanation: ${fixedEdit.explanation}. Original error with the parameters given: ${initialError.raw}`,
|
|
270
|
-
type: ToolErrorType.EDIT_NO_CHANGE_LLM_JUDGEMENT,
|
|
271
|
-
},
|
|
272
|
-
originalLineEnding,
|
|
273
|
-
};
|
|
274
|
-
}
|
|
275
|
-
const secondAttemptResult = await calculateReplacement({
|
|
276
|
-
params: {
|
|
277
|
-
...params,
|
|
278
|
-
old_string: fixedEdit.search,
|
|
279
|
-
new_string: fixedEdit.replace,
|
|
280
|
-
},
|
|
281
|
-
currentContent: contentForLlmEditFixer,
|
|
282
|
-
abortSignal,
|
|
283
|
-
});
|
|
284
|
-
const secondError = getErrorReplaceResult(params, secondAttemptResult.occurrences, 1, // expectedReplacements is always 1 for smart_edit
|
|
285
|
-
secondAttemptResult.finalOldString, secondAttemptResult.finalNewString);
|
|
286
|
-
if (secondError) {
|
|
287
|
-
// The fix failed, return the original error
|
|
288
|
-
return {
|
|
289
|
-
currentContent: contentForLlmEditFixer,
|
|
290
|
-
newContent: currentContent,
|
|
291
|
-
occurrences: 0,
|
|
292
|
-
isNewFile: false,
|
|
293
|
-
error: initialError,
|
|
294
|
-
originalLineEnding,
|
|
295
|
-
};
|
|
296
|
-
}
|
|
297
|
-
return {
|
|
298
|
-
currentContent: contentForLlmEditFixer,
|
|
299
|
-
newContent: secondAttemptResult.newContent,
|
|
300
|
-
occurrences: secondAttemptResult.occurrences,
|
|
301
|
-
isNewFile: false,
|
|
302
|
-
error: undefined,
|
|
303
|
-
originalLineEnding,
|
|
304
|
-
};
|
|
305
|
-
}
|
|
306
|
-
/**
|
|
307
|
-
* Calculates the potential outcome of an edit operation.
|
|
308
|
-
* @param params Parameters for the edit operation
|
|
309
|
-
* @returns An object describing the potential edit outcome
|
|
310
|
-
* @throws File system errors if reading the file fails unexpectedly (e.g., permissions)
|
|
311
|
-
*/
|
|
312
|
-
async calculateEdit(params, abortSignal) {
|
|
313
|
-
const expectedReplacements = 1;
|
|
314
|
-
let currentContent = null;
|
|
315
|
-
let fileExists = false;
|
|
316
|
-
let originalLineEnding = '\n'; // Default for new files
|
|
317
|
-
try {
|
|
318
|
-
currentContent = await this.config
|
|
319
|
-
.getFileSystemService()
|
|
320
|
-
.readTextFile(params.file_path);
|
|
321
|
-
originalLineEnding = detectLineEnding(currentContent);
|
|
322
|
-
currentContent = currentContent.replace(/\r\n/g, '\n');
|
|
323
|
-
fileExists = true;
|
|
324
|
-
}
|
|
325
|
-
catch (err) {
|
|
326
|
-
if (!isNodeError(err) || err.code !== 'ENOENT') {
|
|
327
|
-
throw err;
|
|
328
|
-
}
|
|
329
|
-
fileExists = false;
|
|
330
|
-
}
|
|
331
|
-
const isNewFile = params.old_string === '' && !fileExists;
|
|
332
|
-
if (isNewFile) {
|
|
333
|
-
return {
|
|
334
|
-
currentContent,
|
|
335
|
-
newContent: params.new_string,
|
|
336
|
-
occurrences: 1,
|
|
337
|
-
isNewFile: true,
|
|
338
|
-
error: undefined,
|
|
339
|
-
originalLineEnding,
|
|
340
|
-
};
|
|
341
|
-
}
|
|
342
|
-
// after this point, it's not a new file/edit
|
|
343
|
-
if (!fileExists) {
|
|
344
|
-
return {
|
|
345
|
-
currentContent,
|
|
346
|
-
newContent: '',
|
|
347
|
-
occurrences: 0,
|
|
348
|
-
isNewFile: false,
|
|
349
|
-
error: {
|
|
350
|
-
display: `File not found. Cannot apply edit. Use an empty old_string to create a new file.`,
|
|
351
|
-
raw: `File not found: ${params.file_path}`,
|
|
352
|
-
type: ToolErrorType.FILE_NOT_FOUND,
|
|
353
|
-
},
|
|
354
|
-
originalLineEnding,
|
|
355
|
-
};
|
|
356
|
-
}
|
|
357
|
-
if (currentContent === null) {
|
|
358
|
-
return {
|
|
359
|
-
currentContent,
|
|
360
|
-
newContent: '',
|
|
361
|
-
occurrences: 0,
|
|
362
|
-
isNewFile: false,
|
|
363
|
-
error: {
|
|
364
|
-
display: `Failed to read content of file.`,
|
|
365
|
-
raw: `Failed to read content of existing file: ${params.file_path}`,
|
|
366
|
-
type: ToolErrorType.READ_CONTENT_FAILURE,
|
|
367
|
-
},
|
|
368
|
-
originalLineEnding,
|
|
369
|
-
};
|
|
370
|
-
}
|
|
371
|
-
if (params.old_string === '') {
|
|
372
|
-
return {
|
|
373
|
-
currentContent,
|
|
374
|
-
newContent: currentContent,
|
|
375
|
-
occurrences: 0,
|
|
376
|
-
isNewFile: false,
|
|
377
|
-
error: {
|
|
378
|
-
display: `Failed to edit. Attempted to create a file that already exists.`,
|
|
379
|
-
raw: `File already exists, cannot create: ${params.file_path}`,
|
|
380
|
-
type: ToolErrorType.ATTEMPT_TO_CREATE_EXISTING_FILE,
|
|
381
|
-
},
|
|
382
|
-
originalLineEnding,
|
|
383
|
-
};
|
|
384
|
-
}
|
|
385
|
-
const replacementResult = await calculateReplacement({
|
|
386
|
-
params,
|
|
387
|
-
currentContent,
|
|
388
|
-
abortSignal,
|
|
389
|
-
});
|
|
390
|
-
const initialError = getErrorReplaceResult(params, replacementResult.occurrences, expectedReplacements, replacementResult.finalOldString, replacementResult.finalNewString);
|
|
391
|
-
if (!initialError) {
|
|
392
|
-
return {
|
|
393
|
-
currentContent,
|
|
394
|
-
newContent: replacementResult.newContent,
|
|
395
|
-
occurrences: replacementResult.occurrences,
|
|
396
|
-
isNewFile: false,
|
|
397
|
-
error: undefined,
|
|
398
|
-
originalLineEnding,
|
|
399
|
-
};
|
|
400
|
-
}
|
|
401
|
-
// If there was an error, try to self-correct.
|
|
402
|
-
return this.attemptSelfCorrection(params, currentContent, initialError, abortSignal, originalLineEnding);
|
|
403
|
-
}
|
|
404
|
-
/**
|
|
405
|
-
* Handles the confirmation prompt for the Edit tool in the CLI.
|
|
406
|
-
* It needs to calculate the diff to show the user.
|
|
407
|
-
*/
|
|
408
|
-
async shouldConfirmExecute(abortSignal) {
|
|
409
|
-
if (this.config.getApprovalMode() === ApprovalMode.AUTO_EDIT) {
|
|
410
|
-
return false;
|
|
411
|
-
}
|
|
412
|
-
let editData;
|
|
413
|
-
try {
|
|
414
|
-
editData = await this.calculateEdit(this.params, abortSignal);
|
|
415
|
-
}
|
|
416
|
-
catch (error) {
|
|
417
|
-
if (abortSignal.aborted) {
|
|
418
|
-
throw error;
|
|
419
|
-
}
|
|
420
|
-
const errorMsg = error instanceof Error ? error.message : String(error);
|
|
421
|
-
console.log(`Error preparing edit: ${errorMsg}`);
|
|
422
|
-
return false;
|
|
423
|
-
}
|
|
424
|
-
if (editData.error) {
|
|
425
|
-
console.log(`Error: ${editData.error.display}`);
|
|
426
|
-
return false;
|
|
427
|
-
}
|
|
428
|
-
const fileName = path.basename(this.params.file_path);
|
|
429
|
-
const fileDiff = Diff.createPatch(fileName, editData.currentContent ?? '', editData.newContent, 'Current', 'Proposed', DEFAULT_DIFF_OPTIONS);
|
|
430
|
-
const ideClient = this.config.getIdeClient();
|
|
431
|
-
const ideConfirmation = this.config.getIdeMode() &&
|
|
432
|
-
ideClient?.getConnectionStatus().status === IDEConnectionStatus.Connected
|
|
433
|
-
? ideClient.openDiff(this.params.file_path, editData.newContent)
|
|
434
|
-
: undefined;
|
|
435
|
-
const confirmationDetails = {
|
|
436
|
-
type: 'edit',
|
|
437
|
-
title: `Confirm Edit: ${shortenPath(makeRelative(this.params.file_path, this.config.getTargetDir()))}`,
|
|
438
|
-
fileName,
|
|
439
|
-
filePath: this.params.file_path,
|
|
440
|
-
fileDiff,
|
|
441
|
-
originalContent: editData.currentContent,
|
|
442
|
-
newContent: editData.newContent,
|
|
443
|
-
onConfirm: async (outcome) => {
|
|
444
|
-
if (outcome === ToolConfirmationOutcome.ProceedAlways) {
|
|
445
|
-
this.config.setApprovalMode(ApprovalMode.AUTO_EDIT);
|
|
446
|
-
}
|
|
447
|
-
if (ideConfirmation) {
|
|
448
|
-
const result = await ideConfirmation;
|
|
449
|
-
if (result.status === 'accepted' && result.content) {
|
|
450
|
-
// TODO(chrstn): See https://github.com/google-gemini/gemini-cli/pull/5618#discussion_r2255413084
|
|
451
|
-
// for info on a possible race condition where the file is modified on disk while being edited.
|
|
452
|
-
this.params.old_string = editData.currentContent ?? '';
|
|
453
|
-
this.params.new_string = result.content;
|
|
454
|
-
}
|
|
455
|
-
}
|
|
456
|
-
},
|
|
457
|
-
ideConfirmation,
|
|
458
|
-
};
|
|
459
|
-
return confirmationDetails;
|
|
460
|
-
}
|
|
461
|
-
getDescription() {
|
|
462
|
-
const relativePath = makeRelative(this.params.file_path, this.config.getTargetDir());
|
|
463
|
-
if (this.params.old_string === '') {
|
|
464
|
-
return `Create ${shortenPath(relativePath)}`;
|
|
465
|
-
}
|
|
466
|
-
const oldStringSnippet = this.params.old_string.split('\n')[0].substring(0, 30) +
|
|
467
|
-
(this.params.old_string.length > 30 ? '...' : '');
|
|
468
|
-
const newStringSnippet = this.params.new_string.split('\n')[0].substring(0, 30) +
|
|
469
|
-
(this.params.new_string.length > 30 ? '...' : '');
|
|
470
|
-
if (this.params.old_string === this.params.new_string) {
|
|
471
|
-
return `No file changes to ${shortenPath(relativePath)}`;
|
|
472
|
-
}
|
|
473
|
-
return `${shortenPath(relativePath)}: ${oldStringSnippet} => ${newStringSnippet}`;
|
|
474
|
-
}
|
|
475
|
-
/**
|
|
476
|
-
* Executes the edit operation with the given parameters.
|
|
477
|
-
* @param params Parameters for the edit operation
|
|
478
|
-
* @returns Result of the edit operation
|
|
479
|
-
*/
|
|
480
|
-
async execute(signal) {
|
|
481
|
-
let editData;
|
|
482
|
-
try {
|
|
483
|
-
editData = await this.calculateEdit(this.params, signal);
|
|
484
|
-
}
|
|
485
|
-
catch (error) {
|
|
486
|
-
if (signal.aborted) {
|
|
487
|
-
throw error;
|
|
488
|
-
}
|
|
489
|
-
const errorMsg = error instanceof Error ? error.message : String(error);
|
|
490
|
-
return {
|
|
491
|
-
llmContent: `Error preparing edit: ${errorMsg}`,
|
|
492
|
-
returnDisplay: `Error preparing edit: ${errorMsg}`,
|
|
493
|
-
error: {
|
|
494
|
-
message: errorMsg,
|
|
495
|
-
type: ToolErrorType.EDIT_PREPARATION_FAILURE,
|
|
496
|
-
},
|
|
497
|
-
};
|
|
498
|
-
}
|
|
499
|
-
if (editData.error) {
|
|
500
|
-
return {
|
|
501
|
-
llmContent: editData.error.raw,
|
|
502
|
-
returnDisplay: `Error: ${editData.error.display}`,
|
|
503
|
-
error: {
|
|
504
|
-
message: editData.error.raw,
|
|
505
|
-
type: editData.error.type,
|
|
506
|
-
},
|
|
507
|
-
};
|
|
508
|
-
}
|
|
509
|
-
try {
|
|
510
|
-
this.ensureParentDirectoriesExist(this.params.file_path);
|
|
511
|
-
let finalContent = editData.newContent;
|
|
512
|
-
// Restore original line endings if they were CRLF
|
|
513
|
-
if (!editData.isNewFile && editData.originalLineEnding === '\r\n') {
|
|
514
|
-
finalContent = finalContent.replace(/\n/g, '\r\n');
|
|
515
|
-
}
|
|
516
|
-
await this.config
|
|
517
|
-
.getFileSystemService()
|
|
518
|
-
.writeTextFile(this.params.file_path, finalContent);
|
|
519
|
-
let displayResult;
|
|
520
|
-
if (editData.isNewFile) {
|
|
521
|
-
displayResult = `Created ${shortenPath(makeRelative(this.params.file_path, this.config.getTargetDir()))}`;
|
|
522
|
-
}
|
|
523
|
-
else {
|
|
524
|
-
// Generate diff for display, even though core logic doesn't technically need it
|
|
525
|
-
// The CLI wrapper will use this part of the ToolResult
|
|
526
|
-
const fileName = path.basename(this.params.file_path);
|
|
527
|
-
const fileDiff = Diff.createPatch(fileName, editData.currentContent ?? '', // Should not be null here if not isNewFile
|
|
528
|
-
editData.newContent, 'Current', 'Proposed', DEFAULT_DIFF_OPTIONS);
|
|
529
|
-
const originallyProposedContent = this.params.ai_proposed_string || this.params.new_string;
|
|
530
|
-
const diffStat = getDiffStat(fileName, editData.currentContent ?? '', originallyProposedContent, this.params.new_string);
|
|
531
|
-
displayResult = {
|
|
532
|
-
fileDiff,
|
|
533
|
-
fileName,
|
|
534
|
-
originalContent: editData.currentContent,
|
|
535
|
-
newContent: editData.newContent,
|
|
536
|
-
diffStat,
|
|
537
|
-
};
|
|
538
|
-
}
|
|
539
|
-
const llmSuccessMessageParts = [
|
|
540
|
-
editData.isNewFile
|
|
541
|
-
? `Created new file: ${this.params.file_path} with provided content.`
|
|
542
|
-
: `Successfully modified file: ${this.params.file_path} (${editData.occurrences} replacements).`,
|
|
543
|
-
];
|
|
544
|
-
if (this.params.modified_by_user) {
|
|
545
|
-
llmSuccessMessageParts.push(`User modified the \`new_string\` content to be: ${this.params.new_string}.`);
|
|
546
|
-
}
|
|
547
|
-
return {
|
|
548
|
-
llmContent: llmSuccessMessageParts.join(' '),
|
|
549
|
-
returnDisplay: displayResult,
|
|
550
|
-
};
|
|
551
|
-
}
|
|
552
|
-
catch (error) {
|
|
553
|
-
const errorMsg = error instanceof Error ? error.message : String(error);
|
|
554
|
-
return {
|
|
555
|
-
llmContent: `Error executing edit: ${errorMsg}`,
|
|
556
|
-
returnDisplay: `Error writing file: ${errorMsg}`,
|
|
557
|
-
error: {
|
|
558
|
-
message: errorMsg,
|
|
559
|
-
type: ToolErrorType.FILE_WRITE_FAILURE,
|
|
560
|
-
},
|
|
561
|
-
};
|
|
562
|
-
}
|
|
563
|
-
}
|
|
564
|
-
/**
|
|
565
|
-
* Creates parent directories if they don't exist
|
|
566
|
-
*/
|
|
567
|
-
ensureParentDirectoriesExist(filePath) {
|
|
568
|
-
const dirName = path.dirname(filePath);
|
|
569
|
-
if (!fs.existsSync(dirName)) {
|
|
570
|
-
fs.mkdirSync(dirName, { recursive: true });
|
|
571
|
-
}
|
|
572
|
-
}
|
|
573
|
-
}
|
|
574
|
-
/**
|
|
575
|
-
* Implementation of the Edit tool logic
|
|
576
|
-
*/
|
|
577
|
-
export class SmartEditTool extends BaseDeclarativeTool {
|
|
578
|
-
config;
|
|
579
|
-
static Name = 'replace';
|
|
580
|
-
constructor(config, messageBus) {
|
|
581
|
-
super(SmartEditTool.Name, 'Edit', `Replaces text within a file. Replaces a single occurrence. This tool requires providing significant context around the change to ensure precise targeting. Always use the ${ReadFileTool.Name} tool to examine the file's current content before attempting a text replacement.
|
|
582
|
-
|
|
583
|
-
The user has the ability to modify the \`new_string\` content. If modified, this will be stated in the response.
|
|
584
|
-
|
|
585
|
-
Expectation for required parameters:
|
|
586
|
-
1. \`file_path\` MUST be an absolute path; otherwise an error will be thrown.
|
|
587
|
-
2. \`old_string\` MUST be the exact literal text to replace (including all whitespace, indentation, newlines, and surrounding code etc.).
|
|
588
|
-
3. \`new_string\` MUST be the exact literal text to replace \`old_string\` with (also including all whitespace, indentation, newlines, and surrounding code etc.). Ensure the resulting code is correct and idiomatic and that \`old_string\` and \`new_string\` are different.
|
|
589
|
-
4. \`instruction\` is the detailed instruction of what needs to be changed. It is important to Make it specific and detailed so developers or large language models can understand what needs to be changed and perform the changes on their own if necessary.
|
|
590
|
-
5. NEVER escape \`old_string\` or \`new_string\`, that would break the exact literal text requirement.
|
|
591
|
-
**Important:** If ANY of the above are not satisfied, the tool will fail. CRITICAL for \`old_string\`: Must uniquely identify the single instance to change. Include at least 3 lines of context BEFORE and AFTER the target text, matching whitespace and indentation precisely. If this string matches multiple locations, or does not match exactly, the tool will fail.
|
|
592
|
-
6. Prefer to break down complex and long changes into multiple smaller atomic calls to this tool. Always check the content of the file after changes or not finding a string to match.
|
|
593
|
-
**Multiple replacements:** If there are multiple and ambiguous occurences of the \`old_string\` in the file, the tool will also fail.`, Kind.Edit, {
|
|
594
|
-
properties: {
|
|
595
|
-
file_path: {
|
|
596
|
-
description: "The absolute path to the file to modify. Must start with '/'.",
|
|
597
|
-
type: 'string',
|
|
598
|
-
},
|
|
599
|
-
instruction: {
|
|
600
|
-
description: `A clear, semantic instruction for the code change, acting as a high-quality prompt for an expert LLM assistant. It must be self-contained and explain the goal of the change.
|
|
601
|
-
|
|
602
|
-
A good instruction should concisely answer:
|
|
603
|
-
1. WHY is the change needed? (e.g., "To fix a bug where users can be null...")
|
|
604
|
-
2. WHERE should the change happen? (e.g., "...in the 'renderUserProfile' function...")
|
|
605
|
-
3. WHAT is the high-level change? (e.g., "...add a null check for the 'user' object...")
|
|
606
|
-
4. WHAT is the desired outcome? (e.g., "...so that it displays a loading spinner instead of crashing.")
|
|
607
|
-
|
|
608
|
-
**GOOD Example:** "In the 'calculateTotal' function, correct the sales tax calculation by updating the 'taxRate' constant from 0.05 to 0.075 to reflect the new regional tax laws."
|
|
609
|
-
|
|
610
|
-
**BAD Examples:**
|
|
611
|
-
- "Change the text." (Too vague)
|
|
612
|
-
- "Fix the bug." (Doesn't explain the bug or the fix)
|
|
613
|
-
- "Replace the line with this new line." (Brittle, just repeats the other parameters)
|
|
614
|
-
`,
|
|
615
|
-
type: 'string',
|
|
616
|
-
},
|
|
617
|
-
old_string: {
|
|
618
|
-
description: 'The exact literal text to replace, preferably unescaped. Include at least 3 lines of context BEFORE and AFTER the target text, matching whitespace and indentation precisely. If this string is not the exact literal text (i.e. you escaped it) or does not match exactly, the tool will fail.',
|
|
619
|
-
type: 'string',
|
|
620
|
-
},
|
|
621
|
-
new_string: {
|
|
622
|
-
description: 'The exact literal text to replace `old_string` with, preferably unescaped. Provide the EXACT text. Ensure the resulting code is correct and idiomatic.',
|
|
623
|
-
type: 'string',
|
|
624
|
-
},
|
|
625
|
-
},
|
|
626
|
-
required: ['file_path', 'instruction', 'old_string', 'new_string'],
|
|
627
|
-
type: 'object',
|
|
628
|
-
}, true, // output is markdown
|
|
629
|
-
false, // output cannot be updated
|
|
630
|
-
messageBus);
|
|
631
|
-
this.config = config;
|
|
632
|
-
}
|
|
633
|
-
/**
|
|
634
|
-
* Quickly checks if the file path can be resolved directly against the workspace root.
|
|
635
|
-
* @param filePath The relative file path to check.
|
|
636
|
-
* @returns The absolute path if the file exists, otherwise null.
|
|
637
|
-
*/
|
|
638
|
-
findDirectPath(filePath) {
|
|
639
|
-
const directPath = path.join(this.config.getTargetDir(), filePath);
|
|
640
|
-
return fs.existsSync(directPath) ? directPath : null;
|
|
641
|
-
}
|
|
642
|
-
/**
|
|
643
|
-
* Searches for a file across all configured workspace directories.
|
|
644
|
-
* @param filePath The file path (can be partial) to search for.
|
|
645
|
-
* @returns A list of absolute paths for all matching files found.
|
|
646
|
-
*/
|
|
647
|
-
findAmbiguousPaths(filePath) {
|
|
648
|
-
const workspaceContext = this.config.getWorkspaceContext();
|
|
649
|
-
const fileSystem = this.config.getFileSystemService();
|
|
650
|
-
const searchPaths = workspaceContext.getDirectories();
|
|
651
|
-
return fileSystem.findFiles(filePath, searchPaths);
|
|
652
|
-
}
|
|
653
|
-
/**
|
|
654
|
-
* Attempts to correct a relative file path to an absolute path.
|
|
655
|
-
* This function modifies `params.file_path` in place if successful.
|
|
656
|
-
* @param params The tool parameters containing the file_path to correct.
|
|
657
|
-
* @returns An error message string if correction fails, otherwise null.
|
|
658
|
-
*/
|
|
659
|
-
correctPath(params) {
|
|
660
|
-
const directPath = this.findDirectPath(params.file_path);
|
|
661
|
-
if (directPath) {
|
|
662
|
-
params.file_path = directPath;
|
|
663
|
-
return null;
|
|
664
|
-
}
|
|
665
|
-
const foundFiles = this.findAmbiguousPaths(params.file_path);
|
|
666
|
-
if (foundFiles.length === 0) {
|
|
667
|
-
return `File not found for '${params.file_path}' and path is not absolute.`;
|
|
668
|
-
}
|
|
669
|
-
if (foundFiles.length > 1) {
|
|
670
|
-
return (`The file path '${params.file_path}' is too ambiguous and matches multiple files. ` +
|
|
671
|
-
`Please provide a more specific path. Matches: ${foundFiles.join(', ')}`);
|
|
672
|
-
}
|
|
673
|
-
params.file_path = foundFiles[0];
|
|
674
|
-
return null;
|
|
675
|
-
}
|
|
676
|
-
/**
|
|
677
|
-
* Validates the parameters for the Edit tool
|
|
678
|
-
* @param params Parameters to validate
|
|
679
|
-
* @returns Error message string or null if valid
|
|
680
|
-
*/
|
|
681
|
-
validateToolParamValues(params) {
|
|
682
|
-
if (!params.file_path) {
|
|
683
|
-
return "The 'file_path' parameter must be non-empty.";
|
|
684
|
-
}
|
|
685
|
-
if (!path.isAbsolute(params.file_path)) {
|
|
686
|
-
// Attempt to auto-correct to an absolute path
|
|
687
|
-
const error = this.correctPath(params);
|
|
688
|
-
if (error)
|
|
689
|
-
return error;
|
|
690
|
-
}
|
|
691
|
-
const workspaceContext = this.config.getWorkspaceContext();
|
|
692
|
-
if (!workspaceContext.isPathWithinWorkspace(params.file_path)) {
|
|
693
|
-
const directories = workspaceContext.getDirectories();
|
|
694
|
-
return `File path must be within one of the workspace directories: ${directories.join(', ')}`;
|
|
695
|
-
}
|
|
696
|
-
return null;
|
|
697
|
-
}
|
|
698
|
-
createInvocation(params, messageBus) {
|
|
699
|
-
return new EditToolInvocation(this.config, params, messageBus);
|
|
700
|
-
}
|
|
701
|
-
getModifyContext(_) {
|
|
702
|
-
return {
|
|
703
|
-
getFilePath: (params) => params.file_path,
|
|
704
|
-
getCurrentContent: async (params) => {
|
|
705
|
-
try {
|
|
706
|
-
return this.config
|
|
707
|
-
.getFileSystemService()
|
|
708
|
-
.readTextFile(params.file_path);
|
|
709
|
-
}
|
|
710
|
-
catch (err) {
|
|
711
|
-
if (!isNodeError(err) || err.code !== 'ENOENT')
|
|
712
|
-
throw err;
|
|
713
|
-
return '';
|
|
714
|
-
}
|
|
715
|
-
},
|
|
716
|
-
getProposedContent: async (params) => {
|
|
717
|
-
try {
|
|
718
|
-
const currentContent = await this.config
|
|
719
|
-
.getFileSystemService()
|
|
720
|
-
.readTextFile(params.file_path);
|
|
721
|
-
return applyReplacement(currentContent, params.old_string, params.new_string, params.old_string === '' && currentContent === '');
|
|
722
|
-
}
|
|
723
|
-
catch (err) {
|
|
724
|
-
if (!isNodeError(err) || err.code !== 'ENOENT')
|
|
725
|
-
throw err;
|
|
726
|
-
return '';
|
|
727
|
-
}
|
|
728
|
-
},
|
|
729
|
-
createUpdatedParams: (oldContent, modifiedProposedContent, originalParams) => {
|
|
730
|
-
const content = originalParams.new_string;
|
|
731
|
-
return {
|
|
732
|
-
...originalParams,
|
|
733
|
-
ai_proposed_string: content,
|
|
734
|
-
old_string: oldContent,
|
|
735
|
-
new_string: modifiedProposedContent,
|
|
736
|
-
modified_by_user: true,
|
|
737
|
-
};
|
|
738
|
-
},
|
|
739
|
-
};
|
|
740
|
-
}
|
|
741
|
-
}
|
|
742
|
-
//# sourceMappingURL=smart-edit.js.map
|