-
Notifications
You must be signed in to change notification settings - Fork 13.3k
Expand file tree
/
Copy pathedit.ts
More file actions
1262 lines (1120 loc) · 38.9 KB
/
edit.ts
File metadata and controls
1262 lines (1120 loc) · 38.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import * as fsPromises from 'node:fs/promises';
import * as path from 'node:path';
import * as os from 'node:os';
import * as crypto from 'node:crypto';
import * as Diff from 'diff';
import {
BaseDeclarativeTool,
BaseToolInvocation,
Kind,
type ToolCallConfirmationDetails,
type ToolConfirmationOutcome,
type ToolEditConfirmationDetails,
type ToolInvocation,
type ToolLocation,
type ToolResult,
type ToolResultDisplay,
} from './tools.js';
import type { MessageBus } from '../confirmation-bus/message-bus.js';
import { ToolErrorType } from './tool-error.js';
import { makeRelative, shortenPath } from '../utils/paths.js';
import { isNodeError } from '../utils/errors.js';
import type { Config } from '../config/config.js';
import { ApprovalMode } from '../policy/types.js';
import { CoreToolCallStatus } from '../scheduler/types.js';
import { DEFAULT_DIFF_OPTIONS, getDiffStat } from './diffOptions.js';
import { getDiffContextSnippet } from './diff-utils.js';
import {
type ModifiableDeclarativeTool,
type ModifyContext,
} from './modifiable-tool.js';
import { IdeClient } from '../ide/ide-client.js';
import { FixLLMEditWithInstruction } from '../utils/llm-edit-fixer.js';
import { safeLiteralReplace, detectLineEnding } from '../utils/textUtils.js';
import { EditStrategyEvent, EditCorrectionEvent } from '../telemetry/types.js';
import {
logEditStrategy,
logEditCorrectionEvent,
} from '../telemetry/loggers.js';
import { correctPath } from '../utils/pathCorrector.js';
import {
EDIT_TOOL_NAME,
READ_FILE_TOOL_NAME,
EDIT_DISPLAY_NAME,
} from './tool-names.js';
import { debugLogger } from '../utils/debugLogger.js';
import levenshtein from 'fast-levenshtein';
import { EDIT_DEFINITION } from './definitions/coreTools.js';
import { resolveToolDeclaration } from './definitions/resolver.js';
import { detectOmissionPlaceholders } from './omissionPlaceholderDetector.js';
const ENABLE_FUZZY_MATCH_RECOVERY = true;
const FUZZY_MATCH_THRESHOLD = 0.1; // Allow up to 10% weighted difference
const WHITESPACE_PENALTY_FACTOR = 0.1; // Whitespace differences cost 10% of a character difference
interface ReplacementContext {
params: EditToolParams;
currentContent: string;
abortSignal: AbortSignal;
}
interface ReplacementResult {
newContent: string;
occurrences: number;
finalOldString: string;
finalNewString: string;
strategy?: 'exact' | 'flexible' | 'regex' | 'fuzzy';
matchRanges?: Array<{ start: number; end: number }>;
}
export function applyReplacement(
currentContent: string | null,
oldString: string,
newString: string,
isNewFile: boolean,
): string {
if (isNewFile) {
return newString;
}
if (currentContent === null) {
// Should not happen if not a new file, but defensively return empty or newString if oldString is also empty
return oldString === '' ? newString : '';
}
// If oldString is empty and it's not a new file, do not modify the content.
if (oldString === '' && !isNewFile) {
return currentContent;
}
// Use intelligent replacement that handles $ sequences safely
return safeLiteralReplace(currentContent, oldString, newString);
}
/**
* Creates a SHA256 hash of the given content.
* @param content The string content to hash.
* @returns A hex-encoded hash string.
*/
function hashContent(content: string): string {
return crypto.createHash('sha256').update(content).digest('hex');
}
function restoreTrailingNewline(
originalContent: string,
modifiedContent: string,
): string {
const hadTrailingNewline = originalContent.endsWith('\n');
if (hadTrailingNewline && !modifiedContent.endsWith('\n')) {
return modifiedContent + '\n';
} else if (!hadTrailingNewline && modifiedContent.endsWith('\n')) {
return modifiedContent.replace(/\n$/, '');
}
return modifiedContent;
}
/**
* Escapes characters with special meaning in regular expressions.
* @param str The string to escape.
* @returns The escaped string.
*/
function escapeRegex(str: string): string {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
async function calculateExactReplacement(
context: ReplacementContext,
): Promise<ReplacementResult | null> {
const { currentContent, params } = context;
const { old_string, new_string } = params;
const normalizedCode = currentContent;
const normalizedSearch = old_string.replace(/\r\n/g, '\n');
const normalizedReplace = new_string.replace(/\r\n/g, '\n');
const exactOccurrences = normalizedCode.split(normalizedSearch).length - 1;
if (!params.allow_multiple && exactOccurrences > 1) {
return {
newContent: currentContent,
occurrences: exactOccurrences,
finalOldString: normalizedSearch,
finalNewString: normalizedReplace,
};
}
if (exactOccurrences > 0) {
let modifiedCode = safeLiteralReplace(
normalizedCode,
normalizedSearch,
normalizedReplace,
);
modifiedCode = restoreTrailingNewline(currentContent, modifiedCode);
return {
newContent: modifiedCode,
occurrences: exactOccurrences,
finalOldString: normalizedSearch,
finalNewString: normalizedReplace,
};
}
return null;
}
async function calculateFlexibleReplacement(
context: ReplacementContext,
): Promise<ReplacementResult | null> {
const { currentContent, params } = context;
const { old_string, new_string } = params;
const normalizedCode = currentContent;
const normalizedSearch = old_string.replace(/\r\n/g, '\n');
const normalizedReplace = new_string.replace(/\r\n/g, '\n');
const sourceLines = normalizedCode.match(/.*(?:\n|$)/g)?.slice(0, -1) ?? [];
const searchLinesStripped = normalizedSearch
.split('\n')
.map((line: string) => line.trim());
const replaceLines = normalizedReplace.split('\n');
let flexibleOccurrences = 0;
let i = 0;
while (i <= sourceLines.length - searchLinesStripped.length) {
const window = sourceLines.slice(i, i + searchLinesStripped.length);
const windowStripped = window.map((line: string) => line.trim());
const isMatch = windowStripped.every(
(line: string, index: number) => line === searchLinesStripped[index],
);
if (isMatch) {
flexibleOccurrences++;
const firstLineInMatch = window[0];
const indentationMatch = firstLineInMatch.match(/^([ \t]*)/);
const indentation = indentationMatch ? indentationMatch[1] : '';
const newBlockWithIndent = applyIndentation(replaceLines, indentation);
sourceLines.splice(
i,
searchLinesStripped.length,
newBlockWithIndent.join('\n'),
);
i += replaceLines.length;
} else {
i++;
}
}
if (flexibleOccurrences > 0) {
let modifiedCode = sourceLines.join('');
modifiedCode = restoreTrailingNewline(currentContent, modifiedCode);
return {
newContent: modifiedCode,
occurrences: flexibleOccurrences,
finalOldString: normalizedSearch,
finalNewString: normalizedReplace,
};
}
return null;
}
async function calculateRegexReplacement(
context: ReplacementContext,
): Promise<ReplacementResult | null> {
const { currentContent, params } = context;
const { old_string, new_string } = params;
// Normalize line endings for consistent processing.
const normalizedSearch = old_string.replace(/\r\n/g, '\n');
const normalizedReplace = new_string.replace(/\r\n/g, '\n');
// This logic is ported from your Python implementation.
// It builds a flexible, multi-line regex from a search string.
const delimiters = ['(', ')', ':', '[', ']', '{', '}', '>', '<', '='];
let processedString = normalizedSearch;
for (const delim of delimiters) {
processedString = processedString.split(delim).join(` ${delim} `);
}
// Split by any whitespace and remove empty strings.
const tokens = processedString.split(/\s+/).filter(Boolean);
if (tokens.length === 0) {
return null;
}
const escapedTokens = tokens.map(escapeRegex);
// Join tokens with `\s*` to allow for flexible whitespace between them.
const pattern = escapedTokens.join('\\s*');
// The final pattern captures leading whitespace (indentation) and then matches the token pattern.
// 'm' flag enables multi-line mode, so '^' matches the start of any line.
const finalPattern = `^([ \t]*)${pattern}`;
// Always use a global regex to count all potential occurrences for accurate validation.
const globalRegex = new RegExp(finalPattern, 'gm');
const matches = currentContent.match(globalRegex);
if (!matches) {
return null;
}
const occurrences = matches.length;
const newLines = normalizedReplace.split('\n');
// Use the appropriate regex for replacement based on allow_multiple.
const replaceRegex = new RegExp(
finalPattern,
params.allow_multiple ? 'gm' : 'm',
);
const modifiedCode = currentContent.replace(
replaceRegex,
(_match, indentation) =>
applyIndentation(newLines, indentation || '').join('\n'),
);
return {
newContent: restoreTrailingNewline(currentContent, modifiedCode),
occurrences,
finalOldString: normalizedSearch,
finalNewString: normalizedReplace,
};
}
export async function calculateReplacement(
config: Config,
context: ReplacementContext,
): Promise<ReplacementResult> {
const { currentContent, params } = context;
const { old_string, new_string } = params;
const normalizedSearch = old_string.replace(/\r\n/g, '\n');
const normalizedReplace = new_string.replace(/\r\n/g, '\n');
if (normalizedSearch === '') {
return {
newContent: currentContent,
occurrences: 0,
finalOldString: normalizedSearch,
finalNewString: normalizedReplace,
};
}
const exactResult = await calculateExactReplacement(context);
if (exactResult) {
const event = new EditStrategyEvent('exact');
logEditStrategy(config, event);
return exactResult;
}
const flexibleResult = await calculateFlexibleReplacement(context);
if (flexibleResult) {
const event = new EditStrategyEvent('flexible');
logEditStrategy(config, event);
return flexibleResult;
}
const regexResult = await calculateRegexReplacement(context);
if (regexResult) {
const event = new EditStrategyEvent('regex');
logEditStrategy(config, event);
return regexResult;
}
let fuzzyResult;
if (
ENABLE_FUZZY_MATCH_RECOVERY &&
(fuzzyResult = await calculateFuzzyReplacement(config, context))
) {
return fuzzyResult;
}
return {
newContent: currentContent,
occurrences: 0,
finalOldString: normalizedSearch,
finalNewString: normalizedReplace,
};
}
export function getErrorReplaceResult(
params: EditToolParams,
occurrences: number,
finalOldString: string,
finalNewString: string,
) {
let error: { display: string; raw: string; type: ToolErrorType } | undefined =
undefined;
if (occurrences === 0) {
error = {
display: `Failed to edit, could not find the string to replace.`,
raw: `Failed to edit, 0 occurrences found for old_string in ${params.file_path}. Ensure you're not escaping content incorrectly and check whitespace, indentation, and context. Use ${READ_FILE_TOOL_NAME} tool to verify.`,
type: ToolErrorType.EDIT_NO_OCCURRENCE_FOUND,
};
} else if (!params.allow_multiple && occurrences !== 1) {
error = {
display: `Failed to edit, expected 1 occurrence but found ${occurrences}.`,
raw: `Failed to edit, Expected 1 occurrence but found ${occurrences} for old_string in file: ${params.file_path}. If you intended to replace multiple occurrences, set 'allow_multiple' to true.`,
type: ToolErrorType.EDIT_EXPECTED_OCCURRENCE_MISMATCH,
};
} else if (finalOldString === finalNewString) {
error = {
display: `No changes to apply. The old_string and new_string are identical.`,
raw: `No changes to apply. The old_string and new_string are identical in file: ${params.file_path}`,
type: ToolErrorType.EDIT_NO_CHANGE,
};
}
return error;
}
/**
* Parameters for the Edit tool
*/
export interface EditToolParams {
/**
* The path to the file to modify
*/
file_path: string;
/**
* The text to replace
*/
old_string: string;
/**
* The text to replace it with
*/
new_string: string;
/**
* If true, the tool will replace all occurrences of `old_string` with `new_string`.
* If false (default), the tool will only succeed if exactly one occurrence is found.
*/
allow_multiple?: boolean;
/**
* The instruction for what needs to be done.
*/
instruction?: string;
/**
* Whether the edit was modified manually by the user.
*/
modified_by_user?: boolean;
/**
* Initially proposed content.
*/
ai_proposed_content?: string;
}
export function isEditToolParams(args: unknown): args is EditToolParams {
if (typeof args !== 'object' || args === null) {
return false;
}
return (
'file_path' in args &&
typeof args.file_path === 'string' &&
'old_string' in args &&
typeof args.old_string === 'string' &&
'new_string' in args &&
typeof args.new_string === 'string'
);
}
interface CalculatedEdit {
currentContent: string | null;
newContent: string;
occurrences: number;
error?: { display: string; raw: string; type: ToolErrorType };
isNewFile: boolean;
originalLineEnding: '\r\n' | '\n';
strategy?: 'exact' | 'flexible' | 'regex' | 'fuzzy';
matchRanges?: Array<{ start: number; end: number }>;
}
class EditToolInvocation
extends BaseToolInvocation<EditToolParams, ToolResult>
implements ToolInvocation<EditToolParams, ToolResult>
{
constructor(
private readonly config: Config,
params: EditToolParams,
messageBus: MessageBus,
toolName?: string,
displayName?: string,
) {
super(params, messageBus, toolName, displayName);
}
override toolLocations(): ToolLocation[] {
return [{ path: this.params.file_path }];
}
private async attemptSelfCorrection(
params: EditToolParams,
currentContent: string,
initialError: { display: string; raw: string; type: ToolErrorType },
abortSignal: AbortSignal,
originalLineEnding: '\r\n' | '\n',
): Promise<CalculatedEdit> {
// In order to keep from clobbering edits made outside our system,
// check if the file has been modified since we first read it.
let errorForLlmEditFixer = initialError.raw;
let contentForLlmEditFixer = currentContent;
const initialContentHash = hashContent(currentContent);
const onDiskContent = await this.config
.getFileSystemService()
.readTextFile(params.file_path);
const onDiskContentHash = hashContent(onDiskContent.replace(/\r\n/g, '\n'));
if (initialContentHash !== onDiskContentHash) {
// The file has changed on disk since we first read it.
// Use the latest content for the correction attempt.
contentForLlmEditFixer = onDiskContent.replace(/\r\n/g, '\n');
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.`;
}
const fixedEdit = await FixLLMEditWithInstruction(
params.instruction ?? 'Apply the requested edit.',
params.old_string,
params.new_string,
errorForLlmEditFixer,
contentForLlmEditFixer,
this.config.getBaseLlmClient(),
abortSignal,
);
// If the self-correction attempt timed out, return the original error.
if (fixedEdit === null) {
return {
currentContent: contentForLlmEditFixer,
newContent: currentContent,
occurrences: 0,
isNewFile: false,
error: initialError,
originalLineEnding,
};
}
if (fixedEdit.noChangesRequired) {
return {
currentContent,
newContent: currentContent,
occurrences: 0,
isNewFile: false,
error: {
display: `No changes required. The file already meets the specified conditions.`,
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}`,
type: ToolErrorType.EDIT_NO_CHANGE_LLM_JUDGEMENT,
},
originalLineEnding,
};
}
const secondAttemptResult = await calculateReplacement(this.config, {
params: {
...params,
old_string: fixedEdit.search,
new_string: fixedEdit.replace,
},
currentContent: contentForLlmEditFixer,
abortSignal,
});
const secondError = getErrorReplaceResult(
params,
secondAttemptResult.occurrences,
secondAttemptResult.finalOldString,
secondAttemptResult.finalNewString,
);
if (secondError) {
// The fix failed, log failure and return the original error
const event = new EditCorrectionEvent('failure');
logEditCorrectionEvent(this.config, event);
return {
currentContent: contentForLlmEditFixer,
newContent: currentContent,
occurrences: 0,
isNewFile: false,
error: initialError,
originalLineEnding,
};
}
const event = new EditCorrectionEvent(CoreToolCallStatus.Success);
logEditCorrectionEvent(this.config, event);
return {
currentContent: contentForLlmEditFixer,
newContent: secondAttemptResult.newContent,
occurrences: secondAttemptResult.occurrences,
isNewFile: false,
error: undefined,
originalLineEnding,
strategy: secondAttemptResult.strategy,
matchRanges: secondAttemptResult.matchRanges,
};
}
/**
* Calculates the potential outcome of an edit operation.
* @param params Parameters for the edit operation
* @returns An object describing the potential edit outcome
* @throws File system errors if reading the file fails unexpectedly (e.g., permissions)
*/
private async calculateEdit(
params: EditToolParams,
abortSignal: AbortSignal,
): Promise<CalculatedEdit> {
let currentContent: string | null = null;
let fileExists = false;
let originalLineEnding: '\r\n' | '\n' = '\n'; // Default for new files
try {
currentContent = await this.config
.getFileSystemService()
.readTextFile(params.file_path);
originalLineEnding = detectLineEnding(currentContent);
currentContent = currentContent.replace(/\r\n/g, '\n');
fileExists = true;
} catch (err: unknown) {
if (!isNodeError(err) || err.code !== 'ENOENT') {
throw err;
}
fileExists = false;
}
const isNewFile = params.old_string === '' && !fileExists;
if (isNewFile) {
return {
currentContent,
newContent: params.new_string,
occurrences: 1,
isNewFile: true,
error: undefined,
originalLineEnding,
};
}
// after this point, it's not a new file/edit
if (!fileExists) {
return {
currentContent,
newContent: '',
occurrences: 0,
isNewFile: false,
error: {
display: `File not found. Cannot apply edit. Use an empty old_string to create a new file.`,
raw: `File not found: ${params.file_path}`,
type: ToolErrorType.FILE_NOT_FOUND,
},
originalLineEnding,
};
}
if (currentContent === null) {
return {
currentContent,
newContent: '',
occurrences: 0,
isNewFile: false,
error: {
display: `Failed to read content of file.`,
raw: `Failed to read content of existing file: ${params.file_path}`,
type: ToolErrorType.READ_CONTENT_FAILURE,
},
originalLineEnding,
};
}
if (params.old_string === '') {
return {
currentContent,
newContent: currentContent,
occurrences: 0,
isNewFile: false,
error: {
display: `Failed to edit. Attempted to create a file that already exists.`,
raw: `File already exists, cannot create: ${params.file_path}`,
type: ToolErrorType.ATTEMPT_TO_CREATE_EXISTING_FILE,
},
originalLineEnding,
};
}
const replacementResult = await calculateReplacement(this.config, {
params,
currentContent,
abortSignal,
});
const initialError = getErrorReplaceResult(
params,
replacementResult.occurrences,
replacementResult.finalOldString,
replacementResult.finalNewString,
);
if (!initialError) {
return {
currentContent,
newContent: replacementResult.newContent,
occurrences: replacementResult.occurrences,
isNewFile: false,
error: undefined,
originalLineEnding,
strategy: replacementResult.strategy,
matchRanges: replacementResult.matchRanges,
};
}
if (this.config.getDisableLLMCorrection()) {
return {
currentContent,
newContent: currentContent,
occurrences: replacementResult.occurrences,
isNewFile: false,
error: initialError,
originalLineEnding,
};
}
// If there was an error, try to self-correct.
return this.attemptSelfCorrection(
params,
currentContent,
initialError,
abortSignal,
originalLineEnding,
);
}
/**
* Handles the confirmation prompt for the Edit tool in the CLI.
* It needs to calculate the diff to show the user.
*/
protected override async getConfirmationDetails(
abortSignal: AbortSignal,
): Promise<ToolCallConfirmationDetails | false> {
if (this.config.getApprovalMode() === ApprovalMode.AUTO_EDIT) {
return false;
}
let editData: CalculatedEdit;
try {
editData = await this.calculateEdit(this.params, abortSignal);
} catch (error) {
if (abortSignal.aborted) {
throw error;
}
const errorMsg = error instanceof Error ? error.message : String(error);
debugLogger.log(`Error preparing edit: ${errorMsg}`);
return false;
}
if (editData.error) {
debugLogger.log(`Error: ${editData.error.display}`);
return false;
}
const fileName = path.basename(this.params.file_path);
const fileDiff = Diff.createPatch(
fileName,
editData.currentContent ?? '',
editData.newContent,
'Current',
'Proposed',
DEFAULT_DIFF_OPTIONS,
);
const ideClient = await IdeClient.getInstance();
const ideConfirmation =
this.config.getIdeMode() && ideClient.isDiffingEnabled()
? ideClient.openDiff(this.params.file_path, editData.newContent)
: undefined;
const confirmationDetails: ToolEditConfirmationDetails = {
type: 'edit',
title: `Confirm Edit: ${shortenPath(makeRelative(this.params.file_path, this.config.getTargetDir()))}`,
fileName,
filePath: this.params.file_path,
fileDiff,
originalContent: editData.currentContent,
newContent: editData.newContent,
onConfirm: async (_outcome: ToolConfirmationOutcome) => {
// Mode transitions (e.g. AUTO_EDIT) and policy updates are now
// handled centrally by the scheduler.
if (ideConfirmation) {
const result = await ideConfirmation;
if (result.status === 'accepted' && result.content) {
// TODO(chrstn): See https://github.com/google-gemini/gemini-cli/pull/5618#discussion_r2255413084
// for info on a possible race condition where the file is modified on disk while being edited.
this.params.old_string = editData.currentContent ?? '';
this.params.new_string = result.content;
}
}
},
ideConfirmation,
};
return confirmationDetails;
}
getDescription(): string {
const relativePath = makeRelative(
this.params.file_path,
this.config.getTargetDir(),
);
if (this.params.old_string === '') {
return `Create ${shortenPath(relativePath)}`;
}
const oldStringSnippet =
this.params.old_string.split('\n')[0].substring(0, 30) +
(this.params.old_string.length > 30 ? '...' : '');
const newStringSnippet =
this.params.new_string.split('\n')[0].substring(0, 30) +
(this.params.new_string.length > 30 ? '...' : '');
if (this.params.old_string === this.params.new_string) {
return `No file changes to ${shortenPath(relativePath)}`;
}
return `${shortenPath(relativePath)}: ${oldStringSnippet} => ${newStringSnippet}`;
}
/**
* Executes the edit operation with the given parameters.
* @param params Parameters for the edit operation
* @returns Result of the edit operation
*/
async execute(signal: AbortSignal): Promise<ToolResult> {
const resolvedPath = path.resolve(
this.config.getTargetDir(),
this.params.file_path,
);
const validationError = this.config.validatePathAccess(resolvedPath);
if (validationError) {
return {
llmContent: validationError,
returnDisplay: 'Error: Path not in workspace.',
error: {
message: validationError,
type: ToolErrorType.PATH_NOT_IN_WORKSPACE,
},
};
}
let editData: CalculatedEdit;
try {
editData = await this.calculateEdit(this.params, signal);
} catch (error) {
if (signal.aborted) {
throw error;
}
const errorMsg = error instanceof Error ? error.message : String(error);
return {
llmContent: `Error preparing edit: ${errorMsg}`,
returnDisplay: `Error preparing edit: ${errorMsg}`,
error: {
message: errorMsg,
type: ToolErrorType.EDIT_PREPARATION_FAILURE,
},
};
}
if (editData.error) {
return {
llmContent: editData.error.raw,
returnDisplay: `Error: ${editData.error.display}`,
error: {
message: editData.error.raw,
type: editData.error.type,
},
};
}
try {
await this.ensureParentDirectoriesExistAsync(this.params.file_path);
let finalContent = editData.newContent;
// Restore original line endings if they were CRLF, or use OS default for new files
const useCRLF =
(!editData.isNewFile && editData.originalLineEnding === '\r\n') ||
(editData.isNewFile && os.EOL === '\r\n');
if (useCRLF) {
finalContent = finalContent.replace(/\r?\n/g, '\r\n');
}
await this.config
.getFileSystemService()
.writeTextFile(this.params.file_path, finalContent);
let displayResult: ToolResultDisplay;
if (editData.isNewFile) {
displayResult = `Created ${shortenPath(makeRelative(this.params.file_path, this.config.getTargetDir()))}`;
} else {
// Generate diff for display, even though core logic doesn't technically need it
// The CLI wrapper will use this part of the ToolResult
const fileName = path.basename(this.params.file_path);
const fileDiff = Diff.createPatch(
fileName,
editData.currentContent ?? '', // Should not be null here if not isNewFile
editData.newContent,
'Current',
'Proposed',
DEFAULT_DIFF_OPTIONS,
);
const diffStat = getDiffStat(
fileName,
editData.currentContent ?? '',
editData.newContent,
this.params.new_string,
);
displayResult = {
fileDiff,
fileName,
filePath: this.params.file_path,
originalContent: editData.currentContent,
newContent: editData.newContent,
diffStat,
isNewFile: editData.isNewFile,
};
}
const llmSuccessMessageParts = [
editData.isNewFile
? `Created new file: ${this.params.file_path} with provided content.`
: `Successfully modified file: ${this.params.file_path} (${editData.occurrences} replacements).`,
];
// Return a diff of the file before and after the write so that the agent
// can avoid the need to spend a turn doing a verification read.
const snippet = getDiffContextSnippet(
editData.currentContent ?? '',
finalContent,
5,
);
llmSuccessMessageParts.push(`Here is the updated code:
${snippet}`);
const fuzzyFeedback = getFuzzyMatchFeedback(editData);
if (fuzzyFeedback) {
llmSuccessMessageParts.push(fuzzyFeedback);
}
if (this.params.modified_by_user) {
llmSuccessMessageParts.push(
`User modified the \`new_string\` content to be: ${this.params.new_string}.`,
);
}
return {
llmContent: llmSuccessMessageParts.join(' '),
returnDisplay: displayResult,
};
} catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
return {
llmContent: `Error executing edit: ${errorMsg}`,
returnDisplay: `Error writing file: ${errorMsg}`,
error: {
message: errorMsg,
type: ToolErrorType.FILE_WRITE_FAILURE,
},
};
}
}
/**
* Creates parent directories if they don't exist
*/
private async ensureParentDirectoriesExistAsync(
filePath: string,
): Promise<void> {
const dirName = path.dirname(filePath);
try {
await fsPromises.access(dirName);
} catch {
await fsPromises.mkdir(dirName, { recursive: true });
}
}
}
/**
* Implementation of the Edit tool logic
*/
export class EditTool
extends BaseDeclarativeTool<EditToolParams, ToolResult>
implements ModifiableDeclarativeTool<EditToolParams>
{
static readonly Name = EDIT_TOOL_NAME;
constructor(
private readonly config: Config,
messageBus: MessageBus,
) {
super(
EditTool.Name,
EDIT_DISPLAY_NAME,
EDIT_DEFINITION.base.description!,
Kind.Edit,
EDIT_DEFINITION.base.parametersJsonSchema,
messageBus,
true, // isOutputMarkdown
false, // canUpdateOutput
);
}
/**
* Validates the parameters for the Edit tool
* @param params Parameters to validate
* @returns Error message string or null if valid
*/
protected override validateToolParamValues(
params: EditToolParams,
): string | null {
if (!params.file_path) {
return "The 'file_path' parameter must be non-empty.";
}
let filePath = params.file_path;
if (!path.isAbsolute(filePath)) {
// Attempt to auto-correct to an absolute path
const result = correctPath(filePath, this.config);
if (!result.success) {
return result.error;
}
filePath = result.correctedPath;
}
params.file_path = filePath;
const newPlaceholders = detectOmissionPlaceholders(params.new_string);
if (newPlaceholders.length > 0) {