@burtson-labs/agent-core 1.6.93 → 1.6.95
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/LICENSE +11 -11
- package/dist/tools/core-tools.d.ts +51 -0
- package/dist/tools/core-tools.d.ts.map +1 -1
- package/dist/tools/core-tools.js +466 -142
- package/dist/tools/core-tools.js.map +1 -1
- package/dist/tools/grep-glob.d.ts +35 -0
- package/dist/tools/grep-glob.d.ts.map +1 -0
- package/dist/tools/grep-glob.js +115 -0
- package/dist/tools/grep-glob.js.map +1 -0
- package/dist/tools/index.d.ts +1 -0
- package/dist/tools/index.d.ts.map +1 -1
- package/dist/tools/index.js +1 -0
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/language-adapters.d.ts +15 -1
- package/dist/tools/language-adapters.d.ts.map +1 -1
- package/dist/tools/language-adapters.js +58 -4
- package/dist/tools/language-adapters.js.map +1 -1
- package/dist/tools/loop/llmStream.d.ts +37 -0
- package/dist/tools/loop/llmStream.d.ts.map +1 -1
- package/dist/tools/loop/llmStream.js +155 -3
- package/dist/tools/loop/llmStream.js.map +1 -1
- package/dist/tools/loop/loopShared.d.ts +12 -0
- package/dist/tools/loop/loopShared.d.ts.map +1 -1
- package/dist/tools/loop/loopShared.js +24 -0
- package/dist/tools/loop/loopShared.js.map +1 -1
- package/dist/tools/loop/toolCallNormalize.d.ts +2 -0
- package/dist/tools/loop/toolCallNormalize.d.ts.map +1 -1
- package/dist/tools/loop/toolCallNormalize.js +3 -0
- package/dist/tools/loop/toolCallNormalize.js.map +1 -1
- package/dist/tools/skill-loader.d.ts.map +1 -1
- package/dist/tools/skill-loader.js +11 -0
- package/dist/tools/skill-loader.js.map +1 -1
- package/dist/tools/skills/semantic-search-skill.d.ts +3 -2
- package/dist/tools/skills/semantic-search-skill.d.ts.map +1 -1
- package/dist/tools/skills/semantic-search-skill.js +22 -2
- package/dist/tools/skills/semantic-search-skill.js.map +1 -1
- package/dist/tools/skills/test-gen-skill.d.ts.map +1 -1
- package/dist/tools/skills/test-gen-skill.js +11 -0
- package/dist/tools/skills/test-gen-skill.js.map +1 -1
- package/dist/tools/tool-registry.d.ts.map +1 -1
- package/dist/tools/tool-registry.js +10 -0
- package/dist/tools/tool-registry.js.map +1 -1
- package/dist/tools/tool-types.d.ts +16 -0
- package/dist/tools/tool-types.d.ts.map +1 -1
- package/dist/tools/tool-use-loop.d.ts +6 -0
- package/dist/tools/tool-use-loop.d.ts.map +1 -1
- package/dist/tools/tool-use-loop.js +105 -12
- package/dist/tools/tool-use-loop.js.map +1 -1
- package/dist/tools/tool-use-parser.d.ts +15 -0
- package/dist/tools/tool-use-parser.d.ts.map +1 -1
- package/dist/tools/tool-use-parser.js +80 -1
- package/dist/tools/tool-use-parser.js.map +1 -1
- package/dist/tools/unified-patch.d.ts +17 -0
- package/dist/tools/unified-patch.d.ts.map +1 -1
- package/dist/tools/unified-patch.js +62 -1
- package/dist/tools/unified-patch.js.map +1 -1
- package/package.json +1 -1
package/dist/tools/core-tools.js
CHANGED
|
@@ -7,6 +7,11 @@
|
|
|
7
7
|
*/
|
|
8
8
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
9
|
exports.createSkillTool = exports.watchCommandTool = exports.runCommandTool = exports.searchCodeTool = exports.findDirectoryTool = exports.lsTool = exports.listFilesTool = exports.applyPatchTool = exports.replaceRangeTool = exports.applyEditTool = exports.deleteFileTool = exports.writeFileTool = exports.readFileTool = void 0;
|
|
10
|
+
exports.decodeOverEscaped = decodeOverEscaped;
|
|
11
|
+
exports.addFileLines = addFileLines;
|
|
12
|
+
exports.resolvePatchHunk = resolvePatchHunk;
|
|
13
|
+
exports.workspaceDisplayPath = workspaceDisplayPath;
|
|
14
|
+
exports.runCommandRefusal = runCommandRefusal;
|
|
10
15
|
exports.runCommandFailureHint = runCommandFailureHint;
|
|
11
16
|
exports.toSkillId = toSkillId;
|
|
12
17
|
exports.buildSkillMarkdown = buildSkillMarkdown;
|
|
@@ -112,6 +117,38 @@ const BINARY_EXTENSIONS = new Set([
|
|
|
112
117
|
'.mp3', '.mp4', '.mov', '.wav', '.flac', '.ogg',
|
|
113
118
|
'.exe', '.dll', '.so', '.dylib', '.bin', '.dat', '.db', '.sqlite'
|
|
114
119
|
]);
|
|
120
|
+
/**
|
|
121
|
+
* File text whose escapes were written twice: `\n`, `\t`, `\"`, `\'` and
|
|
122
|
+
* `\\` as two characters where the file needs one. gemma4:12b does this in
|
|
123
|
+
* native tool arguments (2026-10-20 benchmark: every edit in all three runs
|
|
124
|
+
* of a Python task carried `\"\"\"docstring\"\"\"` and `\n\n\ndef`, each
|
|
125
|
+
* rejected by the syntax check, 7 to 27 times per run until the run ended).
|
|
126
|
+
* Returns the decoded text, or null when there is nothing to decode. The
|
|
127
|
+
* edit tools use it only after the literal text has FAILED validation, and
|
|
128
|
+
* keep the decoded text only when it passes — legitimate escapes inside
|
|
129
|
+
* string literals (`"a\nb"`) parse as written and are never touched.
|
|
130
|
+
*/
|
|
131
|
+
function decodeOverEscaped(text) {
|
|
132
|
+
if (!/\\[ntr"'\\]/.test(text)) {
|
|
133
|
+
return null;
|
|
134
|
+
}
|
|
135
|
+
const decoded = text.replace(/\\([ntr"'\\])/g, (_m, c) => c === 'n' ? '\n' : c === 't' ? '\t' : c === 'r' ? '\r' : c);
|
|
136
|
+
return decoded === text ? null : decoded;
|
|
137
|
+
}
|
|
138
|
+
const OVER_ESCAPE_NOTE = (field) => `Note: \`${field}\` had literal backslash escapes (\\n, \\", \\t) that did not parse, so they were written as real newlines, quotes and tabs. ` +
|
|
139
|
+
`Send file text as it should appear in the file: a real line break, not \\n; a plain ", not \\".`;
|
|
140
|
+
/** Hint appended to a validation failure when decoding the escapes did not help either. */
|
|
141
|
+
const OVER_ESCAPE_HINT = (field) => `\n\nYour \`${field}\` contains literal backslash escapes (\\n, \\"). The tool writes the text exactly as sent — send real line breaks and plain quotes, not escape sequences.`;
|
|
142
|
+
/** 1-based line number of a character offset. */
|
|
143
|
+
function lineOfOffset(text, offset) {
|
|
144
|
+
let line = 1;
|
|
145
|
+
for (let i = 0; i < offset && i < text.length; i++) {
|
|
146
|
+
if (text.charCodeAt(i) === 10) {
|
|
147
|
+
line++;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
return line;
|
|
151
|
+
}
|
|
115
152
|
function binaryRefusalMessage(ext, relPath) {
|
|
116
153
|
const baseMsg = `"${relPath}" is a ${ext} file — its bytes are not plain text and cannot be read as UTF-8.`;
|
|
117
154
|
const hints = {
|
|
@@ -284,6 +321,8 @@ const writeFileTool = {
|
|
|
284
321
|
// apply_edit: if the file already had errors, only block when
|
|
285
322
|
// THIS write introduced new ones. Pre-existing rot doesn't get
|
|
286
323
|
// to gate every subsequent edit.
|
|
324
|
+
let toWrite = content;
|
|
325
|
+
let escapeNote;
|
|
287
326
|
if (ctx.languageAdapters) {
|
|
288
327
|
const validation = await ctx.languageAdapters.validate(absPath, content, ctx);
|
|
289
328
|
if (!validation.ok) {
|
|
@@ -299,26 +338,37 @@ const writeFileTool = {
|
|
|
299
338
|
beforeError = undefined;
|
|
300
339
|
}
|
|
301
340
|
if (beforeError === undefined || introducedNewErrors(beforeError, validation.error)) {
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
341
|
+
// Twice-escaped text (see decodeOverEscaped): keep the decoded
|
|
342
|
+
// form only when it passes where the literal one failed.
|
|
343
|
+
const decoded = decodeOverEscaped(content);
|
|
344
|
+
const decodedValidation = decoded !== null ? await ctx.languageAdapters.validate(absPath, decoded, ctx) : undefined;
|
|
345
|
+
if (decoded !== null && decodedValidation
|
|
346
|
+
&& (decodedValidation.ok || (beforeError !== undefined && !introducedNewErrors(beforeError, decodedValidation.error)))) {
|
|
347
|
+
toWrite = decoded;
|
|
348
|
+
escapeNote = OVER_ESCAPE_NOTE('content');
|
|
349
|
+
}
|
|
350
|
+
else {
|
|
351
|
+
return {
|
|
352
|
+
output: `Validation failed for "${relPath}":\n${validation.error}\n\nThe file was NOT written. Fix the errors and retry.${decoded !== null ? OVER_ESCAPE_HINT('content') : ''}`,
|
|
353
|
+
isError: true
|
|
354
|
+
};
|
|
355
|
+
}
|
|
306
356
|
}
|
|
307
357
|
}
|
|
308
358
|
}
|
|
309
|
-
await ctx.writeFile(absPath,
|
|
359
|
+
await ctx.writeFile(absPath, toWrite);
|
|
310
360
|
// The model authored every byte it just wrote, so a follow-up
|
|
311
361
|
// apply_edit/replace_range on this file is not a blind edit. Without
|
|
312
362
|
// this, "write the HTML, then add the logo" was rejected with "you
|
|
313
363
|
// have not read this file" and cost a read + a loop-breaker trip.
|
|
314
364
|
ctx.markFileRead?.(absPath);
|
|
315
|
-
const lineCount =
|
|
365
|
+
const lineCount = toWrite.split('\n').length;
|
|
316
366
|
// Same "don't restate" footer as apply_edit — same Qwen failure
|
|
317
367
|
// mode applies here when the model overwrites an entire file.
|
|
318
368
|
const baseMessage = `Wrote ${lineCount} lines to ${relPath}. File saved. Do not restate the file contents — the user can see the diff. Move on to the next pending task or reply with a brief summary if the work is complete.`;
|
|
319
|
-
const validationWarning = validatePostWrite(absPath,
|
|
369
|
+
const validationWarning = validatePostWrite(absPath, toWrite);
|
|
320
370
|
const postEditCheck = await (0, post_edit_checks_1.runPostEditTypeCheck)(absPath, ctx).catch(() => ({ newErrorCount: 0, warning: undefined }));
|
|
321
|
-
const trailers = [validationWarning, postEditCheck.warning].filter(Boolean).join('\n\n');
|
|
371
|
+
const trailers = [escapeNote, validationWarning, postEditCheck.warning].filter(Boolean).join('\n\n');
|
|
322
372
|
return {
|
|
323
373
|
output: trailers ? `${baseMessage}\n\n${trailers}` : baseMessage
|
|
324
374
|
};
|
|
@@ -437,9 +487,8 @@ const applyEditTool = {
|
|
|
437
487
|
if (find === '') {
|
|
438
488
|
return { output: 'Error: find parameter must not be empty — use write_file to create a new file', isError: true };
|
|
439
489
|
}
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
}
|
|
490
|
+
// find === replace is checked after the file is read: when the text is
|
|
491
|
+
// already in the file the model is re-sending an edit it already made.
|
|
443
492
|
// Scratchpad-placeholder detector. Small models occasionally dump their
|
|
444
493
|
// own internal reasoning into `replace` as a bracketed "token" where
|
|
445
494
|
// code should go, e.g.
|
|
@@ -506,6 +555,18 @@ const applyEditTool = {
|
|
|
506
555
|
catch (err) {
|
|
507
556
|
return { output: `Error reading "${relPath}": ${err instanceof Error ? err.message : String(err)}. apply_edit only works on existing files — use write_file to create a new one.`, isError: true };
|
|
508
557
|
}
|
|
558
|
+
if (find === replace) {
|
|
559
|
+
const at = before.indexOf(find);
|
|
560
|
+
// 2026-10-20 benchmark (gemma4:12b): after a successful edit the model
|
|
561
|
+
// sent find === replace (the new text) six times; "no edit to apply"
|
|
562
|
+
// did not tell it the change was already there.
|
|
563
|
+
return {
|
|
564
|
+
output: at >= 0
|
|
565
|
+
? `No change: \`find\` and \`replace\` are identical, and that text is already in "${relPath}" at line ${lineOfOffset(before, at)}. If this is the change you meant to make, it is already done — do not send it again; continue with the next step.`
|
|
566
|
+
: 'Error: find and replace are identical — no edit to apply',
|
|
567
|
+
isError: true
|
|
568
|
+
};
|
|
569
|
+
}
|
|
509
570
|
// Count occurrences with a literal (non-regex) scan so metacharacters in
|
|
510
571
|
// `find` don't blow up. split+length-1 is cheap and correct for literals.
|
|
511
572
|
let occurrences = before.split(find).length - 1;
|
|
@@ -545,6 +606,30 @@ const applyEditTool = {
|
|
|
545
606
|
// No exact match AND no fuzzy match. Real miss. Surface the
|
|
546
607
|
// closest line in the file so the model can correct the find
|
|
547
608
|
// text without burning an iteration on a re-read.
|
|
609
|
+
// A twice-escaped `find` (`\"\"\"doc\"\"\"`, 2026-10-20) is not in the
|
|
610
|
+
// file as written; when its decoded form is, run the edit with both
|
|
611
|
+
// fields decoded and say so.
|
|
612
|
+
const decodedFind = decodeOverEscaped(find);
|
|
613
|
+
if (decodedFind !== null && before.includes(decodedFind)) {
|
|
614
|
+
const decodedReplace = decodeOverEscaped(replace) ?? replace;
|
|
615
|
+
const retried = await applyEditTool.execute({ ...params, find: decodedFind, replace: decodedReplace }, ctx);
|
|
616
|
+
return retried.isError ? retried : { ...retried, output: `${retried.output}\n\n${OVER_ESCAPE_NOTE('find')}` };
|
|
617
|
+
}
|
|
618
|
+
// The edit was already applied: `find` is gone and `replace` is
|
|
619
|
+
// there. 2026-10-20 benchmark (gemma4:12b): a successful edit was
|
|
620
|
+
// re-sent 12 times, each answered with an indentation hint about a
|
|
621
|
+
// line that existed only because the edit had been made, until the
|
|
622
|
+
// run hit its iteration limit.
|
|
623
|
+
const replaceTrimmed = replace.trim();
|
|
624
|
+
const appliedAt = replaceTrimmed.length >= 20 ? before.indexOf(replaceTrimmed) : -1;
|
|
625
|
+
if (appliedAt >= 0) {
|
|
626
|
+
const startLine = lineOfOffset(before, appliedAt);
|
|
627
|
+
const endLine = startLine + replaceTrimmed.split('\n').length - 1;
|
|
628
|
+
return {
|
|
629
|
+
output: `\`find\` text was not found in "${relPath}", but your \`replace\` text is already there (line${endLine > startLine ? `s ${startLine}-${endLine}` : ` ${startLine}`}). This edit has already been applied — do not send it again. Continue with the next change, or re-read the file if you are unsure what it contains now.`,
|
|
630
|
+
isError: true
|
|
631
|
+
};
|
|
632
|
+
}
|
|
548
633
|
const hint = findIndentationHint(before, find);
|
|
549
634
|
const snippet = nearestMatchSnippet(before, find);
|
|
550
635
|
return {
|
|
@@ -630,72 +715,78 @@ const applyEditTool = {
|
|
|
630
715
|
// indent to every additional line. Skipped on `replace_all` (each
|
|
631
716
|
// match could have a different indent) and on edits where the model
|
|
632
717
|
// already supplied absolute indent on the first line.
|
|
633
|
-
const
|
|
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
|
-
// When fuzzy whitespace matched, the model's `find` had different
|
|
661
|
-
// indentation than the file. Its `replace` was almost certainly
|
|
662
|
-
// written at the same (wrong) indent as its `find`, so splicing
|
|
663
|
-
// it verbatim into the matched span would land mis-indented code
|
|
664
|
-
// in the middle of correctly-indented code. Compute the indent
|
|
665
|
-
// delta between the find and the matched text and shift every
|
|
666
|
-
// line of `replace` by that delta so the edit lands at the
|
|
667
|
-
// right column. No-op when find and matched first lines have
|
|
668
|
-
// the same indent (fuzzy fired on inner-line whitespace, not
|
|
669
|
-
// outer indent).
|
|
670
|
-
let spliceReplace = finalReplace;
|
|
671
|
-
if (usedFuzzyWhitespace && fuzzySpan) {
|
|
672
|
-
const matchedText = before.slice(fuzzySpan.start, fuzzySpan.end);
|
|
673
|
-
const findIndent = (find.match(/^[ \t]*/) ?? [''])[0];
|
|
674
|
-
const matchedIndent = (matchedText.match(/^[ \t]*/) ?? [''])[0];
|
|
675
|
-
const delta = matchedIndent.length - findIndent.length;
|
|
676
|
-
if (delta !== 0) {
|
|
677
|
-
spliceReplace = finalReplace
|
|
678
|
-
.split('\n')
|
|
679
|
-
.map((line) => {
|
|
680
|
-
if (line.length === 0) {
|
|
681
|
-
return line;
|
|
682
|
-
}
|
|
683
|
-
if (delta > 0) {
|
|
684
|
-
return ' '.repeat(delta) + line;
|
|
685
|
-
}
|
|
686
|
-
const leading = (line.match(/^[ \t]*/) ?? [''])[0].length;
|
|
687
|
-
return line.slice(Math.min(-delta, leading));
|
|
688
|
-
})
|
|
718
|
+
const buildAfter = (rep) => {
|
|
719
|
+
const finalReplace = (() => {
|
|
720
|
+
if (replaceAll) {
|
|
721
|
+
return rep;
|
|
722
|
+
}
|
|
723
|
+
if (find.includes('\n')) {
|
|
724
|
+
return rep;
|
|
725
|
+
}
|
|
726
|
+
if (!rep.includes('\n')) {
|
|
727
|
+
return rep;
|
|
728
|
+
}
|
|
729
|
+
if (/^\s/.test(rep)) {
|
|
730
|
+
return rep;
|
|
731
|
+
}
|
|
732
|
+
const matchIndex = before.indexOf(find);
|
|
733
|
+
if (matchIndex === -1) {
|
|
734
|
+
return rep;
|
|
735
|
+
}
|
|
736
|
+
const lineStart = before.lastIndexOf('\n', matchIndex - 1) + 1;
|
|
737
|
+
const indent = before.slice(lineStart, matchIndex);
|
|
738
|
+
if (indent.length === 0 || !/^[ \t]+$/.test(indent)) {
|
|
739
|
+
return rep;
|
|
740
|
+
}
|
|
741
|
+
const lines = rep.split('\n');
|
|
742
|
+
return lines
|
|
743
|
+
.map((line, i) => (i === 0 || line.length === 0 ? line : indent + line))
|
|
689
744
|
.join('\n');
|
|
745
|
+
})();
|
|
746
|
+
// When fuzzy whitespace matched, the model's `find` had different
|
|
747
|
+
// indentation than the file. Its `replace` was almost certainly
|
|
748
|
+
// written at the same (wrong) indent as its `find`, so splicing
|
|
749
|
+
// it verbatim into the matched span would land mis-indented code
|
|
750
|
+
// in the middle of correctly-indented code. Compute the indent
|
|
751
|
+
// delta between the find and the matched text and shift every
|
|
752
|
+
// line of `replace` by that delta so the edit lands at the
|
|
753
|
+
// right column. No-op when find and matched first lines have
|
|
754
|
+
// the same indent (fuzzy fired on inner-line whitespace, not
|
|
755
|
+
// outer indent).
|
|
756
|
+
let spliceReplace = finalReplace;
|
|
757
|
+
if (usedFuzzyWhitespace && fuzzySpan) {
|
|
758
|
+
const matchedText = before.slice(fuzzySpan.start, fuzzySpan.end);
|
|
759
|
+
const findIndent = (find.match(/^[ \t]*/) ?? [''])[0];
|
|
760
|
+
const matchedIndent = (matchedText.match(/^[ \t]*/) ?? [''])[0];
|
|
761
|
+
const delta = matchedIndent.length - findIndent.length;
|
|
762
|
+
if (delta !== 0) {
|
|
763
|
+
spliceReplace = finalReplace
|
|
764
|
+
.split('\n')
|
|
765
|
+
.map((line) => {
|
|
766
|
+
if (line.length === 0) {
|
|
767
|
+
return line;
|
|
768
|
+
}
|
|
769
|
+
if (delta > 0) {
|
|
770
|
+
return ' '.repeat(delta) + line;
|
|
771
|
+
}
|
|
772
|
+
const leading = (line.match(/^[ \t]*/) ?? [''])[0].length;
|
|
773
|
+
return line.slice(Math.min(-delta, leading));
|
|
774
|
+
})
|
|
775
|
+
.join('\n');
|
|
776
|
+
}
|
|
690
777
|
}
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
778
|
+
return replaceAll
|
|
779
|
+
? before.split(find).join(finalReplace)
|
|
780
|
+
: nearLineSpan
|
|
781
|
+
? before.slice(0, nearLineSpan.start) + finalReplace + before.slice(nearLineSpan.end)
|
|
782
|
+
: usedFuzzyWhitespace && fuzzySpan
|
|
783
|
+
? before.slice(0, fuzzySpan.start) + spliceReplace + before.slice(fuzzySpan.end)
|
|
784
|
+
// Function replacer: a string replacement expands `$$`, `$&`, `$'`
|
|
785
|
+
// and `` $` `` (a Makefile's `$$HOME` landed as `$HOME`).
|
|
786
|
+
: before.replace(find, () => finalReplace);
|
|
787
|
+
};
|
|
788
|
+
let after = buildAfter(replace);
|
|
789
|
+
let escapeNote;
|
|
699
790
|
if (after === before) {
|
|
700
791
|
// Defensive — should be impossible given the guards above, but stay honest.
|
|
701
792
|
return { output: 'Edit produced no change to the file.', isError: true };
|
|
@@ -714,10 +805,25 @@ const applyEditTool = {
|
|
|
714
805
|
// the model gave up after iterating on its find/replace 8x.
|
|
715
806
|
const beforeValidation = await ctx.languageAdapters.validate(absPath, before, ctx);
|
|
716
807
|
if (introducedNewErrors(beforeValidation.error, afterValidation.error)) {
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
808
|
+
// Twice-escaped `replace` (see decodeOverEscaped): keep the
|
|
809
|
+
// decoded form only when it passes where the literal one failed.
|
|
810
|
+
const decoded = decodeOverEscaped(replace);
|
|
811
|
+
let repaired = false;
|
|
812
|
+
if (decoded !== null) {
|
|
813
|
+
const candidate = buildAfter(decoded);
|
|
814
|
+
const candidateValidation = candidate !== before ? await ctx.languageAdapters.validate(absPath, candidate, ctx) : undefined;
|
|
815
|
+
if (candidateValidation && (candidateValidation.ok || !introducedNewErrors(beforeValidation.error, candidateValidation.error))) {
|
|
816
|
+
after = candidate;
|
|
817
|
+
escapeNote = OVER_ESCAPE_NOTE('replace');
|
|
818
|
+
repaired = true;
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
if (!repaired) {
|
|
822
|
+
return {
|
|
823
|
+
output: `Validation failed after apply_edit on "${relPath}":\n${afterValidation.error}\n\nThe file was NOT written. Fix the \`find\`/\`replace\` values and retry.${decoded !== null ? OVER_ESCAPE_HINT('replace') : ''}`,
|
|
824
|
+
isError: true
|
|
825
|
+
};
|
|
826
|
+
}
|
|
721
827
|
}
|
|
722
828
|
// Pre-existing errors only — write proceeds. Surface the
|
|
723
829
|
// situation in the result so the model knows the file isn't
|
|
@@ -768,7 +874,7 @@ const applyEditTool = {
|
|
|
768
874
|
// call to 38s+ and eventually tripped a 504.
|
|
769
875
|
const baseMessage = `Replaced ${matches} in ${relPath} (${deltaLabel}). File saved. Do not restate the file contents — the user can see the diff. Do not re-read this file just to make another edit — you already have the structure in context. Move on to the next pending task or reply with a brief summary if the work is complete.`;
|
|
770
876
|
const postEditCheck = await (0, post_edit_checks_1.runPostEditTypeCheck)(absPath, ctx).catch(() => ({ newErrorCount: 0, warning: undefined }));
|
|
771
|
-
const trailers = [validationWarning, postEditCheck.warning].filter(Boolean).join('\n\n');
|
|
877
|
+
const trailers = [escapeNote, validationWarning, postEditCheck.warning].filter(Boolean).join('\n\n');
|
|
772
878
|
return {
|
|
773
879
|
output: trailers ? `${baseMessage}\n\n${trailers}` : baseMessage
|
|
774
880
|
};
|
|
@@ -787,7 +893,7 @@ const replaceRangeTool = {
|
|
|
787
893
|
{ name: 'path', description: 'File path. Relative paths resolve against the workspace root; absolute and ~ paths are also accepted.', required: true },
|
|
788
894
|
{ name: 'start_line', description: '1-based first line to replace. For insertion, this is the line to insert before.', required: true },
|
|
789
895
|
{ name: 'end_line', description: '1-based last line to replace, inclusive. Use start_line-1 to insert before start_line. Defaults to start_line for a one-line replacement.' },
|
|
790
|
-
{ name: 'content', description: 'Replacement text for the range. Empty string deletes the range. Use real newline characters for multi-line replacements.', required: true },
|
|
896
|
+
{ name: 'content', description: 'Replacement text for the range. Empty string deletes the range. Use real newline characters for multi-line replacements. A newline at the end is optional and does not add a blank line.', required: true },
|
|
791
897
|
{ name: 'expected_hash', description: 'Advisory only — when passed, the framework compares it against the current range hash and records a warning in the result if they differ, but the edit still proceeds. The read-tracking guard is the real safety mechanism; you do not need to pass this for normal edits. Kept for backwards compatibility with callers that copy shown_hash from read_file.' },
|
|
792
898
|
{ name: 'expected_old', description: 'Optional exact old text for the range. When passed, the edit is rejected if the current content does not match — use for short, surgical replacements where the exact source line is known. Stricter than expected_hash; intentionally NOT advisory.' }
|
|
793
899
|
],
|
|
@@ -879,12 +985,24 @@ const replaceRangeTool = {
|
|
|
879
985
|
isError: true
|
|
880
986
|
};
|
|
881
987
|
}
|
|
882
|
-
|
|
883
|
-
|
|
988
|
+
// A newline at the end of `content` terminates its last line; it is not one more
|
|
989
|
+
// (empty) line. Joining already puts a line break between the replacement and
|
|
990
|
+
// whatever follows the range, so counting it again left a stray blank line after
|
|
991
|
+
// every replacement written the natural way ("// entry point\n" → "Inserted 2
|
|
992
|
+
// lines"). It is only kept when the range runs to the end of the file, where
|
|
993
|
+
// that newline is the file's own final newline.
|
|
994
|
+
const hasFollowingLines = endIdx < lines.length;
|
|
995
|
+
const linesFor = (t) => t === ''
|
|
996
|
+
? []
|
|
997
|
+
: splitTextLines(hasFollowingLines ? t.replace(/\r?\n$/, '') : t).lines;
|
|
998
|
+
const buildAfter = (replacement) => [
|
|
884
999
|
...lines.slice(0, startIdx),
|
|
885
|
-
...
|
|
1000
|
+
...replacement,
|
|
886
1001
|
...lines.slice(endIdx)
|
|
887
1002
|
].join(eol);
|
|
1003
|
+
let replacementLines = linesFor(String(content));
|
|
1004
|
+
let after = buildAfter(replacementLines);
|
|
1005
|
+
let escapeNote;
|
|
888
1006
|
if (after === before) {
|
|
889
1007
|
return { output: 'replace_range produced no change to the file.', isError: true };
|
|
890
1008
|
}
|
|
@@ -893,10 +1011,27 @@ const replaceRangeTool = {
|
|
|
893
1011
|
if (!afterValidation.ok) {
|
|
894
1012
|
const beforeValidation = await ctx.languageAdapters.validate(absPath, before, ctx);
|
|
895
1013
|
if (introducedNewErrors(beforeValidation.error, afterValidation.error)) {
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
1014
|
+
// Twice-escaped `content` (see decodeOverEscaped): keep the
|
|
1015
|
+
// decoded form only when it passes where the literal one failed.
|
|
1016
|
+
const decoded = decodeOverEscaped(String(content));
|
|
1017
|
+
let repaired = false;
|
|
1018
|
+
if (decoded !== null) {
|
|
1019
|
+
const decodedLines = linesFor(decoded);
|
|
1020
|
+
const candidate = buildAfter(decodedLines);
|
|
1021
|
+
const candidateValidation = candidate !== before ? await ctx.languageAdapters.validate(absPath, candidate, ctx) : undefined;
|
|
1022
|
+
if (candidateValidation && (candidateValidation.ok || !introducedNewErrors(beforeValidation.error, candidateValidation.error))) {
|
|
1023
|
+
replacementLines = decodedLines;
|
|
1024
|
+
after = candidate;
|
|
1025
|
+
escapeNote = OVER_ESCAPE_NOTE('content');
|
|
1026
|
+
repaired = true;
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
if (!repaired) {
|
|
1030
|
+
return {
|
|
1031
|
+
output: `Validation failed after replace_range on "${relPath}":\n${afterValidation.error}\n\nThe file was NOT written. Re-read the surrounding lines and retry with a smaller or corrected replacement.${decoded !== null ? OVER_ESCAPE_HINT('content') : ''}`,
|
|
1032
|
+
isError: true
|
|
1033
|
+
};
|
|
1034
|
+
}
|
|
900
1035
|
}
|
|
901
1036
|
}
|
|
902
1037
|
}
|
|
@@ -912,40 +1047,99 @@ const replaceRangeTool = {
|
|
|
912
1047
|
? `Inserted ${added} line${added === 1 ? '' : 's'} before line ${startLine}`
|
|
913
1048
|
: `Replaced lines ${startLine}-${endLine} (+${added} -${removed})`;
|
|
914
1049
|
const baseMessage = `${rangeLabel} in ${relPath}. File saved. Do not restate the file contents — the user can see the diff. Do not re-read this file just to make another nearby edit; continue with the next range or verify when done.`;
|
|
1050
|
+
// Line numbers below the range moved. 2026-10-20 benchmark (gemma4:26b):
|
|
1051
|
+
// after a +2-line replace_range the model sent the next range with the
|
|
1052
|
+
// numbers from its earlier read, replaced the wrong lines, and spent the
|
|
1053
|
+
// rest of the run on a file it had broken. Say where the old lines are.
|
|
1054
|
+
const shift = added - removed;
|
|
1055
|
+
const firstBelow = endLine < startLine ? startLine : endLine + 1;
|
|
1056
|
+
const shiftNote = shift !== 0 && firstBelow <= lines.length
|
|
1057
|
+
? `Line numbers from line ${firstBelow} down moved by ${shift > 0 ? '+' : ''}${shift}: what your last read showed as line ${firstBelow} is now line ${firstBelow + shift}. Use the new numbers for further replace_range calls in this file.`
|
|
1058
|
+
: undefined;
|
|
915
1059
|
const validationWarning = validatePostWrite(absPath, after);
|
|
916
1060
|
const postEditCheck = await (0, post_edit_checks_1.runPostEditTypeCheck)(absPath, ctx).catch(() => ({ newErrorCount: 0, warning: undefined }));
|
|
917
|
-
const trailers = [hashWarning, validationWarning, postEditCheck.warning].filter(Boolean).join('\n\n');
|
|
1061
|
+
const trailers = [shiftNote, escapeNote, hashWarning, validationWarning, postEditCheck.warning].filter(Boolean).join('\n\n');
|
|
918
1062
|
return {
|
|
919
1063
|
output: trailers ? `${baseMessage}\n\n${trailers}` : baseMessage
|
|
920
1064
|
};
|
|
921
1065
|
}
|
|
922
1066
|
};
|
|
923
1067
|
exports.replaceRangeTool = replaceRangeTool;
|
|
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
|
-
|
|
1068
|
+
/** `text` read as "marker + space" (the extra space dropped). */
|
|
1069
|
+
function dropMarkerSpace(text) {
|
|
1070
|
+
return text.startsWith(' ') ? text.slice(1) : text;
|
|
1071
|
+
}
|
|
1072
|
+
function leadingSpaces(line) {
|
|
1073
|
+
return /^ */.exec(line)?.[0].length ?? 0;
|
|
1074
|
+
}
|
|
1075
|
+
/**
|
|
1076
|
+
* True when every non-blank line is indented by an odd number of spaces
|
|
1077
|
+
* (and only spaces). A model that writes `+ ` before each line produces
|
|
1078
|
+
* that shape for code indented in even steps, which nearly all code is.
|
|
1079
|
+
*/
|
|
1080
|
+
function allOddSpaceIndented(lines) {
|
|
1081
|
+
const nonBlank = lines.filter((l) => l.trim().length > 0);
|
|
1082
|
+
if (nonBlank.length === 0) {
|
|
1083
|
+
return false;
|
|
1084
|
+
}
|
|
1085
|
+
return nonBlank.every((l) => !/^ *\t/.test(l) && leadingSpaces(l) % 2 === 1);
|
|
1086
|
+
}
|
|
1087
|
+
/** Body lines of an `*** Add File:` block (text after the `+`). */
|
|
1088
|
+
function addFileLines(rawLines) {
|
|
1089
|
+
const nonBlank = rawLines.filter((l) => l.trim().length > 0);
|
|
1090
|
+
// Every line spelled `+ text`: the model used the marker-plus-space
|
|
1091
|
+
// form for the whole file (a real file has unindented lines).
|
|
1092
|
+
const markerSpace = nonBlank.length > 0 && nonBlank.every((l) => l.startsWith(' '));
|
|
1093
|
+
return rawLines.map((l) => (markerSpace ? dropMarkerSpace(l) : l));
|
|
1094
|
+
}
|
|
1095
|
+
/**
|
|
1096
|
+
* Turn one hunk into a find/replace against `file`. The one-character
|
|
1097
|
+
* reading wins when its find text is in the file. When it is not and the
|
|
1098
|
+
* "marker + space" reading of the removed and added lines is, the model
|
|
1099
|
+
* wrote that form and both sides use it. A hunk with no removed lines
|
|
1100
|
+
* cannot be told apart by matching (its context matches either way), so
|
|
1101
|
+
* its added lines use the marker-space reading only when every one of
|
|
1102
|
+
* them is indented by an odd number of spaces and the context is not.
|
|
1103
|
+
*/
|
|
1104
|
+
function resolvePatchHunk(hunk, file) {
|
|
1105
|
+
const build = (markerSpace) => {
|
|
1106
|
+
const findLines = [];
|
|
1107
|
+
const replaceLines = [];
|
|
1108
|
+
for (const item of hunk) {
|
|
1109
|
+
const text = markerSpace && item.kind !== 'context' ? dropMarkerSpace(item.text) : item.text;
|
|
1110
|
+
if (item.kind === 'context') {
|
|
1111
|
+
findLines.push(text);
|
|
1112
|
+
replaceLines.push(text);
|
|
1113
|
+
}
|
|
1114
|
+
else if (item.kind === 'removed') {
|
|
1115
|
+
findLines.push(text);
|
|
1116
|
+
}
|
|
1117
|
+
else {
|
|
1118
|
+
replaceLines.push(text);
|
|
1119
|
+
}
|
|
1120
|
+
}
|
|
1121
|
+
return { find: findLines.join('\n'), replace: replaceLines.join('\n') };
|
|
1122
|
+
};
|
|
1123
|
+
const count = (find) => (find ? file.split(find).length - 1 : 0);
|
|
1124
|
+
const oneChar = build(false);
|
|
1125
|
+
const oneCharCount = count(oneChar.find);
|
|
1126
|
+
const hasRemoved = hunk.some((i) => i.kind === 'removed');
|
|
1127
|
+
if (oneCharCount === 0 && hasRemoved) {
|
|
1128
|
+
const markerSpace = build(true);
|
|
1129
|
+
const markerSpaceCount = count(markerSpace.find);
|
|
1130
|
+
if (markerSpaceCount > 0) {
|
|
1131
|
+
return { ...markerSpace, occurrences: markerSpaceCount, spelling: 'marker-space' };
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
if (!hasRemoved) {
|
|
1135
|
+
const added = hunk.filter((i) => i.kind === 'added').map((i) => i.text);
|
|
1136
|
+
const context = hunk.filter((i) => i.kind === 'context').map((i) => i.text);
|
|
1137
|
+
if (allOddSpaceIndented(added) && !allOddSpaceIndented(context)) {
|
|
1138
|
+
return { ...build(true), occurrences: oneCharCount, spelling: 'marker-space' };
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
return { ...oneChar, occurrences: oneCharCount, spelling: 'one-char' };
|
|
1142
|
+
}
|
|
949
1143
|
const applyPatchTool = {
|
|
950
1144
|
name: 'apply_patch',
|
|
951
1145
|
description: 'Apply a multi-file patch in a single tool call. Use this when you have to change 2+ files (rename, refactor, multi-method comment pass) — much cheaper than calling apply_edit N times. Two accepted formats: (1) **standard unified diff** — what `git diff` produces, with `--- a/path`, `+++ b/path`, `@@` hunks, ` `/`-`/`+` body lines. Most models emit this format natively. Single-file unified diffs accepted; for multi-file, concatenate diffs with their own headers. (2) **Codex envelope** — `*** Begin Patch` / `*** End Patch` wrapping `*** Update File: <path>` / `*** Add File:` / `*** Delete File:` blocks. The tool auto-detects the format from the input.',
|
|
@@ -1022,9 +1216,10 @@ const applyPatchTool = {
|
|
|
1022
1216
|
continue;
|
|
1023
1217
|
}
|
|
1024
1218
|
if (current.kind === 'add') {
|
|
1025
|
-
// Add file: every line
|
|
1219
|
+
// Add file: every body line starts with `+`. The marker spelling
|
|
1220
|
+
// is settled once the block is complete (addFileLines).
|
|
1026
1221
|
if (line.startsWith('+')) {
|
|
1027
|
-
current.lines.push(line.slice(
|
|
1222
|
+
current.lines.push(line.slice(1));
|
|
1028
1223
|
}
|
|
1029
1224
|
continue;
|
|
1030
1225
|
}
|
|
@@ -1043,11 +1238,13 @@ const applyPatchTool = {
|
|
|
1043
1238
|
currentHunk = [];
|
|
1044
1239
|
current.hunks.push(currentHunk);
|
|
1045
1240
|
}
|
|
1241
|
+
// One marker character; resolvePatchHunk decides whether the
|
|
1242
|
+
// model wrote "marker + space" instead.
|
|
1046
1243
|
if (line.startsWith('-')) {
|
|
1047
|
-
currentHunk.push({ kind: 'removed', text: line.slice(
|
|
1244
|
+
currentHunk.push({ kind: 'removed', text: line.slice(1) });
|
|
1048
1245
|
}
|
|
1049
1246
|
else if (line.startsWith('+')) {
|
|
1050
|
-
currentHunk.push({ kind: 'added', text: line.slice(
|
|
1247
|
+
currentHunk.push({ kind: 'added', text: line.slice(1) });
|
|
1051
1248
|
}
|
|
1052
1249
|
else if (line.startsWith(' ')) {
|
|
1053
1250
|
// Context line preserved IN ORDER — combined with removed/
|
|
@@ -1100,8 +1297,9 @@ const applyPatchTool = {
|
|
|
1100
1297
|
}
|
|
1101
1298
|
if (action.kind === 'add') {
|
|
1102
1299
|
try {
|
|
1103
|
-
|
|
1104
|
-
|
|
1300
|
+
const addLines = addFileLines(action.lines);
|
|
1301
|
+
await ctx.writeFile(absPath, addLines.join('\n') + (addLines.length > 0 ? '\n' : ''));
|
|
1302
|
+
results.push(`Added: ${action.path} (${addLines.length} lines)`);
|
|
1105
1303
|
}
|
|
1106
1304
|
catch (err) {
|
|
1107
1305
|
results.push(`FAILED Add ${action.path}: ${err instanceof Error ? err.message : String(err)}`);
|
|
@@ -1139,32 +1337,18 @@ const applyPatchTool = {
|
|
|
1139
1337
|
const hunkFailureNotes = [];
|
|
1140
1338
|
for (let hi = 0; hi < action.hunks.length; hi++) {
|
|
1141
1339
|
const hunk = action.hunks[hi];
|
|
1142
|
-
const
|
|
1143
|
-
const
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
if (item.kind === 'context') {
|
|
1147
|
-
findLines.push(item.text);
|
|
1148
|
-
replaceLines.push(item.text);
|
|
1149
|
-
contextCount++;
|
|
1150
|
-
}
|
|
1151
|
-
else if (item.kind === 'removed') {
|
|
1152
|
-
findLines.push(item.text);
|
|
1153
|
-
}
|
|
1154
|
-
else if (item.kind === 'added') {
|
|
1155
|
-
replaceLines.push(item.text);
|
|
1156
|
-
}
|
|
1157
|
-
}
|
|
1158
|
-
const find = findLines.join('\n');
|
|
1159
|
-
const replace = replaceLines.join('\n');
|
|
1340
|
+
const contextCount = hunk.filter((item) => item.kind === 'context').length;
|
|
1341
|
+
const resolved = resolvePatchHunk(hunk, after);
|
|
1342
|
+
const { find, occurrences } = resolved;
|
|
1343
|
+
let { replace } = resolved;
|
|
1160
1344
|
if (!find) {
|
|
1161
1345
|
hunksFailed++;
|
|
1162
1346
|
hunkFailureNotes.push(`hunk #${hi + 1}: empty (no removed lines and no context)`);
|
|
1163
1347
|
continue;
|
|
1164
1348
|
}
|
|
1165
|
-
const occurrences = after.split(find).length - 1;
|
|
1166
1349
|
if (occurrences === 1) {
|
|
1167
|
-
|
|
1350
|
+
// Function replacer: a string one would expand `$&`, `$$`, `$1` in the patch text.
|
|
1351
|
+
after = after.replace(find, () => replace);
|
|
1168
1352
|
hunksApplied++;
|
|
1169
1353
|
continue;
|
|
1170
1354
|
}
|
|
@@ -1201,6 +1385,27 @@ const applyPatchTool = {
|
|
|
1201
1385
|
}
|
|
1202
1386
|
}
|
|
1203
1387
|
if (matchedStart >= 0) {
|
|
1388
|
+
// A whitespace-tolerant match says nothing about the marker
|
|
1389
|
+
// spelling. When every matched file line is indented exactly
|
|
1390
|
+
// one space less than the patch's line, the model wrote
|
|
1391
|
+
// "marker + space": drop that space from the added lines too.
|
|
1392
|
+
if (resolved.spelling === 'one-char') {
|
|
1393
|
+
// Removed lines only: context lines may be spelled either way.
|
|
1394
|
+
const findKinds = hunk.filter((item) => item.kind !== 'added').map((item) => item.kind);
|
|
1395
|
+
const findWindow = find.split('\n');
|
|
1396
|
+
const fileWindow = afterLines.slice(matchedStart, matchedStart + findLineCount);
|
|
1397
|
+
const pairs = findWindow
|
|
1398
|
+
.map((l, i) => [l, fileWindow[i] ?? '', findKinds[i]])
|
|
1399
|
+
.filter(([l, , kind]) => kind === 'removed' && l.trim().length > 0);
|
|
1400
|
+
const offByOne = pairs.length > 0 &&
|
|
1401
|
+
pairs.every(([l, f]) => leadingSpaces(l) === leadingSpaces(f) + 1 && !/^\s*\t/.test(f));
|
|
1402
|
+
if (offByOne) {
|
|
1403
|
+
replace = hunk
|
|
1404
|
+
.filter((item) => item.kind !== 'removed')
|
|
1405
|
+
.map((item) => (item.kind === 'added' ? dropMarkerSpace(item.text) : item.text))
|
|
1406
|
+
.join('\n');
|
|
1407
|
+
}
|
|
1408
|
+
}
|
|
1204
1409
|
const replaceLineCount = replace.split('\n').length;
|
|
1205
1410
|
const replacedLines = [
|
|
1206
1411
|
...afterLines.slice(0, matchedStart),
|
|
@@ -1323,6 +1528,7 @@ function introducedNewErrors(before, after) {
|
|
|
1323
1528
|
.replace(/\bat position \d+/gi, 'at position N')
|
|
1324
1529
|
.replace(/\b(line|ln) \d+(?: column| col)?(?: \d+)?/gi, 'line N')
|
|
1325
1530
|
.replace(/:\s*\d+:\d+/g, ':N:N') // file:line:col → file:N:N
|
|
1531
|
+
.replace(/\(\d+,\d+(?:,\d+,\d+)?\)/g, '(N,N)') // file(line,col) — csc, mcs, tsc, MSBuild
|
|
1326
1532
|
.replace(/\bcharacter \d+/gi, 'character N')
|
|
1327
1533
|
.replace(/\boffset \d+/gi, 'offset N');
|
|
1328
1534
|
const normalize = (s) => {
|
|
@@ -1339,6 +1545,45 @@ function introducedNewErrors(before, after) {
|
|
|
1339
1545
|
}
|
|
1340
1546
|
return false;
|
|
1341
1547
|
}
|
|
1548
|
+
/**
|
|
1549
|
+
* Apply a unified-diff payload. A diff that covers several files (each with its own
|
|
1550
|
+
* `--- a/<path>` / `+++ b/<path>` header, as `git diff` writes them and as the tool
|
|
1551
|
+
* description asks for) is applied file by file.
|
|
1552
|
+
*
|
|
1553
|
+
* It used to apply the first file and stop: the parser read one file's hunks, the second
|
|
1554
|
+
* header ended the parse, and the result said "Applied 1 hunk to src/format.ts" with no
|
|
1555
|
+
* mention of the rest. qwen3.6:27b renamed a function with one two-file patch, was told
|
|
1556
|
+
* it had applied, and left the call site in the other file unchanged (BanditBench
|
|
1557
|
+
* 2026-10-05, edit.rename_across_files).
|
|
1558
|
+
*
|
|
1559
|
+
* Each file is all-or-nothing; files are independent, like the actions of the Codex
|
|
1560
|
+
* envelope: the ones that apply are written, the ones that do not are reported with the
|
|
1561
|
+
* reason, and the call is an error only when nothing was written.
|
|
1562
|
+
*/
|
|
1563
|
+
async function executeUnifiedDiffPatch(patchText, pathOverride, ctx) {
|
|
1564
|
+
const sections = (0, unified_patch_1.splitUnifiedPatchByFile)(patchText);
|
|
1565
|
+
if (sections.length <= 1) {
|
|
1566
|
+
return executeUnifiedDiffForFile(patchText, pathOverride, ctx);
|
|
1567
|
+
}
|
|
1568
|
+
// Several files: every section names its own path, so an explicit `path` (meant for a
|
|
1569
|
+
// diff without headers) does not apply.
|
|
1570
|
+
const results = [];
|
|
1571
|
+
for (const section of sections) {
|
|
1572
|
+
const header = /^\+\+\+ (?:b\/)?(.+?)\s*$/m.exec(section) ?? /^--- (?:a\/)?(.+?)\s*$/m.exec(section);
|
|
1573
|
+
const result = await executeUnifiedDiffForFile(section, undefined, ctx);
|
|
1574
|
+
results.push({ ...result, file: header?.[1] ?? '(no path)' });
|
|
1575
|
+
}
|
|
1576
|
+
const applied = results.filter((r) => !r.isError).length;
|
|
1577
|
+
const failed = results.length - applied;
|
|
1578
|
+
const body = results.map((r) => (r.isError ? `FAILED "${r.file}" — ${r.output}` : r.output)).join('\n\n');
|
|
1579
|
+
if (failed === 0) {
|
|
1580
|
+
return { output: body, isError: false };
|
|
1581
|
+
}
|
|
1582
|
+
const summary = applied === 0
|
|
1583
|
+
? `apply_patch failed for all ${results.length} files in the diff. Nothing was written.`
|
|
1584
|
+
: `apply_patch applied ${applied} of ${results.length} files. The ${failed === 1 ? 'file marked FAILED was' : 'files marked FAILED were'} NOT changed — fix and re-send only ${failed === 1 ? 'that file' : 'those files'}.`;
|
|
1585
|
+
return { output: `${summary}\n\n${body}`, isError: applied === 0 };
|
|
1586
|
+
}
|
|
1342
1587
|
/**
|
|
1343
1588
|
* Apply a single-file unified-diff payload. Path is read from the
|
|
1344
1589
|
* `+++ b/<path>` header unless the caller passed an explicit `path`
|
|
@@ -1347,7 +1592,7 @@ function introducedNewErrors(before, after) {
|
|
|
1347
1592
|
* — apply_patch is a different INPUT format, not a different write
|
|
1348
1593
|
* pipeline.
|
|
1349
1594
|
*/
|
|
1350
|
-
async function
|
|
1595
|
+
async function executeUnifiedDiffForFile(patchText, pathOverride, ctx) {
|
|
1351
1596
|
const parsed = (0, unified_patch_1.parseUnifiedPatch)(patchText);
|
|
1352
1597
|
if (!parsed) {
|
|
1353
1598
|
return {
|
|
@@ -1535,7 +1780,7 @@ const listFilesTool = {
|
|
|
1535
1780
|
if (!files.length) {
|
|
1536
1781
|
return { output: `No files matched pattern "${pattern}"` };
|
|
1537
1782
|
}
|
|
1538
|
-
const list = files.slice(0, 200).join('\n');
|
|
1783
|
+
const list = files.slice(0, 200).map((f) => workspaceDisplayPath(f, ctx.workspaceRoot)).join('\n');
|
|
1539
1784
|
const suffix = files.length > 200 ? `\n\n[list_files: showing first 200 of ${files.length} files]` : '';
|
|
1540
1785
|
return { output: `${files.length} file(s) matched "${pattern}":\n\n${list}${suffix}` };
|
|
1541
1786
|
}
|
|
@@ -1545,6 +1790,25 @@ const listFilesTool = {
|
|
|
1545
1790
|
}
|
|
1546
1791
|
};
|
|
1547
1792
|
exports.listFilesTool = listFilesTool;
|
|
1793
|
+
/**
|
|
1794
|
+
* A path as the model should see it: relative to the workspace root when it
|
|
1795
|
+
* is inside it (read_file, apply_edit and search take those), absolute
|
|
1796
|
+
* otherwise. Hosts return absolute paths; repeating a temp-dir root such as
|
|
1797
|
+
* `/private/var/folders/.../T/<run>/` on every line cost ~20 tokens a file
|
|
1798
|
+
* and nothing the model could use.
|
|
1799
|
+
*/
|
|
1800
|
+
function workspaceDisplayPath(filePath, workspaceRoot) {
|
|
1801
|
+
if (!workspaceRoot) {
|
|
1802
|
+
return filePath;
|
|
1803
|
+
}
|
|
1804
|
+
const norm = (p) => p.replace(/\\/g, '/');
|
|
1805
|
+
const root = norm(workspaceRoot).replace(/\/+$/, '');
|
|
1806
|
+
const file = norm(filePath);
|
|
1807
|
+
if (root && file.startsWith(`${root}/`)) {
|
|
1808
|
+
return file.slice(root.length + 1);
|
|
1809
|
+
}
|
|
1810
|
+
return filePath;
|
|
1811
|
+
}
|
|
1548
1812
|
// ── ls ─────────────────────────────────────────────────────────────────────────
|
|
1549
1813
|
// Dead-simple directory listing. Exists alongside list_files because small
|
|
1550
1814
|
// models (<= 7B) reliably skip the glob+cwd combo but handle single-path
|
|
@@ -1912,6 +2176,25 @@ const ALLOWED_COMMANDS = new Set([
|
|
|
1912
2176
|
'curl', 'wget'
|
|
1913
2177
|
]);
|
|
1914
2178
|
const BLOCKED_PATTERNS = [/rm\s+-rf/, /rmdir/, /format/, /mkfs/, /dd\s+if=/];
|
|
2179
|
+
/**
|
|
2180
|
+
* The run_command allow-list and blocked patterns, as one check other
|
|
2181
|
+
* command-running tools can apply before they call `ctx.runCommand`. Returns
|
|
2182
|
+
* the refusal message, or null when the command may run. A workspace skill's
|
|
2183
|
+
* `command` used to bypass both — `sh`, `bash` and friends included.
|
|
2184
|
+
*/
|
|
2185
|
+
function runCommandRefusal(cmd, args) {
|
|
2186
|
+
const baseCmd = cmd.split(/[\\/]/).pop() ?? cmd;
|
|
2187
|
+
if (!ALLOWED_COMMANDS.has(baseCmd)) {
|
|
2188
|
+
return rejectionMessage(baseCmd);
|
|
2189
|
+
}
|
|
2190
|
+
const fullCommand = [cmd, ...args].join(' ');
|
|
2191
|
+
for (const blocked of BLOCKED_PATTERNS) {
|
|
2192
|
+
if (blocked.test(fullCommand)) {
|
|
2193
|
+
return `Error: command contains a blocked pattern (${blocked.source})`;
|
|
2194
|
+
}
|
|
2195
|
+
}
|
|
2196
|
+
return null;
|
|
2197
|
+
}
|
|
1915
2198
|
/**
|
|
1916
2199
|
* Map of well-known CLIs the agent might be asked to install but that
|
|
1917
2200
|
* aren't on the allow-list themselves (terraform, kubectl when not yet
|
|
@@ -2087,6 +2370,15 @@ function shellTokenize(input) {
|
|
|
2087
2370
|
}
|
|
2088
2371
|
return out;
|
|
2089
2372
|
}
|
|
2373
|
+
/** Interpreters run_command may start, and their inline-code flag. */
|
|
2374
|
+
const INTERPRETER_CODE_FLAG = {
|
|
2375
|
+
python: '-c',
|
|
2376
|
+
python3: '-c',
|
|
2377
|
+
node: '-e',
|
|
2378
|
+
ruby: '-e',
|
|
2379
|
+
perl: '-e',
|
|
2380
|
+
php: '-r'
|
|
2381
|
+
};
|
|
2090
2382
|
const runCommandTool = {
|
|
2091
2383
|
name: 'run_command',
|
|
2092
2384
|
description: 'Run a shell command in the workspace and return the output. Allowed commands span common dev stacks: node/pnpm/npm/npx, python/pip/pytest, git, cargo, go, dotnet, mvn/gradle/java, ruby/bundle, php/composer, swift/xcodebuild, make/cmake, docker, package managers (brew, npm install -g, pip install, pipx, cargo install, gem install, go install), and read-only inspection tools (ls, cat, head, tail, grep, find, jq, yq). When the user asks you to install a CLI or package, run the install via the right package manager — the host\'s permission gate prompts the user before each invocation, so attempting an install is the correct behavior, not refusal. Only fall back to "ask the user to run it in their shell" when the command is genuinely outside the allow-list AND no package-manager equivalent exists. Call the binary directly via cmd/args (cmd="git", args="status") — NEVER wrap it in `bash -c` / `sh -c` / `zsh -c`; shell interpreters are blocked and the runner already spawns the program for you. For pipes or globs, use `search_code` (grep) or `list_files` (find), or run the steps separately. NO SHELL: `&&`, `|`, `;`, `source`, `cd`, and `~`/glob expansion do NOT work — run each step as its own call. Python: prefer `python3 -m pip` (bare `pip` is often not on PATH); if pip reports an "externally-managed-environment" (PEP 668), create a venv once (cmd="python3", args="-m venv .venv") and then call `.venv/bin/pip` and `.venv/bin/python` DIRECTLY — never `source .venv/bin/activate`.',
|
|
@@ -2111,6 +2403,25 @@ const runCommandTool = {
|
|
|
2111
2403
|
// command line was being treated as a single executable name).
|
|
2112
2404
|
let cmd = rawCmd;
|
|
2113
2405
|
let argsString = params.args ?? '';
|
|
2406
|
+
// Arguments or inline code sent under a name this tool does not have.
|
|
2407
|
+
// 2026-10-20 benchmark (gemma4:12b): `{"cmd":"python3","python_args":"-c
|
|
2408
|
+
// \"...\""}` and `{"cmd":"python3","python_script":"assert ..."}` ran a
|
|
2409
|
+
// bare `python3`, which read an empty stdin and exited 0 — five
|
|
2410
|
+
// "verifications" that ran nothing were taken as passing checks, and one
|
|
2411
|
+
// run ended on a false "verified" claim. Unknown names are mapped where
|
|
2412
|
+
// the intent is unambiguous; a bare interpreter is refused below.
|
|
2413
|
+
const interpreterBase = (rawCmd.split(/\s/)[0].split('/').pop() ?? '').toLowerCase();
|
|
2414
|
+
const codeFlag = INTERPRETER_CODE_FLAG[interpreterBase];
|
|
2415
|
+
if (!argsString.trim()) {
|
|
2416
|
+
const argsAlias = Object.keys(params).find((k) => k !== 'args' && /(^|_)(args|arguments|argv)$/i.test(k) && String(params[k] ?? '').trim());
|
|
2417
|
+
if (argsAlias) {
|
|
2418
|
+
argsString = String(params[argsAlias]);
|
|
2419
|
+
}
|
|
2420
|
+
}
|
|
2421
|
+
const scriptAlias = codeFlag
|
|
2422
|
+
? Object.keys(params).find((k) => /^(\w+_)?(script|code|source|program)$/i.test(k) && String(params[k] ?? '').trim())
|
|
2423
|
+
: undefined;
|
|
2424
|
+
let inlineCode = scriptAlias ? String(params[scriptAlias]) : undefined;
|
|
2114
2425
|
const preparsedArgs = maybeParseJsonArrayArgs(argsString);
|
|
2115
2426
|
const firstSpace = rawCmd.search(/\s/);
|
|
2116
2427
|
if (firstSpace > 0 && !preparsedArgs) {
|
|
@@ -2131,6 +2442,19 @@ const runCommandTool = {
|
|
|
2131
2442
|
}
|
|
2132
2443
|
}
|
|
2133
2444
|
const args = preparsedArgs ?? (argsString ? shellTokenize(argsString) : []);
|
|
2445
|
+
if (inlineCode !== undefined && codeFlag) {
|
|
2446
|
+
args.unshift(codeFlag, inlineCode);
|
|
2447
|
+
inlineCode = undefined;
|
|
2448
|
+
}
|
|
2449
|
+
// An interpreter with no script, no -c/-e and no module reads its program
|
|
2450
|
+
// from stdin; commands here get no stdin, so it exits 0 having run
|
|
2451
|
+
// nothing. That is not a check — refuse it with the fix.
|
|
2452
|
+
if (codeFlag && args.length === 0) {
|
|
2453
|
+
return {
|
|
2454
|
+
output: `\`${baseCmd}\` with no arguments runs nothing here (it would read a program from stdin, and run_command has none) and exits 0 — that is not a check. Pass the code in \`args\`, e.g. cmd="${baseCmd}" args="${codeFlag} \\"<code>\\"", or run a script file or module (args="path/to/script${baseCmd.startsWith('node') ? '.js' : '.py'}").`,
|
|
2455
|
+
isError: true
|
|
2456
|
+
};
|
|
2457
|
+
}
|
|
2134
2458
|
// un-escape `<` / `>` in `git commit` messages.
|
|
2135
2459
|
// from a real Bandit commit: the
|
|
2136
2460
|
// `Co-authored-by: Bandit <bandit@burtson.ai>` trailer was emitted
|