@vybestack/llxprt-code-core 0.7.0-nightly.251219.3619c584b → 0.7.0-nightly.251221.60dcdf714

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