@burtson-labs/agent-core 1.6.94 → 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.
@@ -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
- return {
303
- output: `Validation failed for "${relPath}":\n${validation.error}\n\nThe file was NOT written. Fix the errors and retry.`,
304
- isError: true
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, content);
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 = content.split('\n').length;
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, content);
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
- if (find === replace) {
441
- return { output: 'Error: find and replace are identical — no edit to apply', isError: true };
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 finalReplace = (() => {
634
- if (replaceAll) {
635
- return replace;
636
- }
637
- if (find.includes('\n')) {
638
- return replace;
639
- }
640
- if (!replace.includes('\n')) {
641
- return replace;
642
- }
643
- if (/^\s/.test(replace)) {
644
- return replace;
645
- }
646
- const matchIndex = before.indexOf(find);
647
- if (matchIndex === -1) {
648
- return replace;
649
- }
650
- const lineStart = before.lastIndexOf('\n', matchIndex - 1) + 1;
651
- const indent = before.slice(lineStart, matchIndex);
652
- if (indent.length === 0 || !/^[ \t]+$/.test(indent)) {
653
- return replace;
654
- }
655
- const lines = replace.split('\n');
656
- return lines
657
- .map((line, i) => (i === 0 || line.length === 0 ? line : indent + line))
658
- .join('\n');
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
- const after = replaceAll
693
- ? before.split(find).join(finalReplace)
694
- : nearLineSpan
695
- ? before.slice(0, nearLineSpan.start) + finalReplace + before.slice(nearLineSpan.end)
696
- : usedFuzzyWhitespace && fuzzySpan
697
- ? before.slice(0, fuzzySpan.start) + spliceReplace + before.slice(fuzzySpan.end)
698
- : before.replace(find, finalReplace);
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
- return {
718
- output: `Validation failed after apply_edit on "${relPath}":\n${afterValidation.error}\n\nThe file was NOT written. Fix the \`find\`/\`replace\` values and retry.`,
719
- isError: true
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
  };
@@ -885,16 +991,18 @@ const replaceRangeTool = {
885
991
  // every replacement written the natural way ("// entry point\n" → "Inserted 2
886
992
  // lines"). It is only kept when the range runs to the end of the file, where
887
993
  // that newline is the file's own final newline.
888
- const text = String(content);
889
994
  const hasFollowingLines = endIdx < lines.length;
890
- const replacementLines = text === ''
995
+ const linesFor = (t) => t === ''
891
996
  ? []
892
- : splitTextLines(hasFollowingLines ? text.replace(/\r?\n$/, '') : text).lines;
893
- const after = [
997
+ : splitTextLines(hasFollowingLines ? t.replace(/\r?\n$/, '') : t).lines;
998
+ const buildAfter = (replacement) => [
894
999
  ...lines.slice(0, startIdx),
895
- ...replacementLines,
1000
+ ...replacement,
896
1001
  ...lines.slice(endIdx)
897
1002
  ].join(eol);
1003
+ let replacementLines = linesFor(String(content));
1004
+ let after = buildAfter(replacementLines);
1005
+ let escapeNote;
898
1006
  if (after === before) {
899
1007
  return { output: 'replace_range produced no change to the file.', isError: true };
900
1008
  }
@@ -903,10 +1011,27 @@ const replaceRangeTool = {
903
1011
  if (!afterValidation.ok) {
904
1012
  const beforeValidation = await ctx.languageAdapters.validate(absPath, before, ctx);
905
1013
  if (introducedNewErrors(beforeValidation.error, afterValidation.error)) {
906
- return {
907
- 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.`,
908
- isError: true
909
- };
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
+ }
910
1035
  }
911
1036
  }
912
1037
  }
@@ -922,40 +1047,99 @@ const replaceRangeTool = {
922
1047
  ? `Inserted ${added} line${added === 1 ? '' : 's'} before line ${startLine}`
923
1048
  : `Replaced lines ${startLine}-${endLine} (+${added} -${removed})`;
924
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;
925
1059
  const validationWarning = validatePostWrite(absPath, after);
926
1060
  const postEditCheck = await (0, post_edit_checks_1.runPostEditTypeCheck)(absPath, ctx).catch(() => ({ newErrorCount: 0, warning: undefined }));
927
- 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');
928
1062
  return {
929
1063
  output: trailers ? `${baseMessage}\n\n${trailers}` : baseMessage
930
1064
  };
931
1065
  }
932
1066
  };
933
1067
  exports.replaceRangeTool = replaceRangeTool;
934
- // ── apply_patch ────────────────────────────────────────────────────────────────
935
- //
936
- // Multi-file envelope. One tool call → many edits across many files.
937
- // Cheaper than N round-trips of apply_edit when the model is doing a
938
- // rename, refactor, or any batch change. Format follows the Codex/
939
- // OpenCode "*** Begin Patch / *** End Patch" envelope so models trained
940
- // on it (gpt-4/5, qwen 2.5+, claude) can emit it natively.
941
- //
942
- // Supported actions in v1:
943
- // *** Update File: <path>
944
- // @@ <unique context line that exists in the file>
945
- // - removed line
946
- // + added line
947
- // unchanged context line (single space prefix)
948
- // *** Add File: <path>
949
- // + content line 1
950
- // + content line 2
951
- // *** Delete File: <path>
952
- //
953
- // (Move is intentionally out of scope for v1 — implement as Add+Delete.)
954
- //
955
- // Each Update block translates to a find/replace internally:
956
- // find = context lines + removed lines (in their original order)
957
- // replace = context lines + added lines (in their original order)
958
- // The same uniqueness/indentation guards as apply_edit apply per-update.
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
+ }
959
1143
  const applyPatchTool = {
960
1144
  name: 'apply_patch',
961
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.',
@@ -1032,9 +1216,10 @@ const applyPatchTool = {
1032
1216
  continue;
1033
1217
  }
1034
1218
  if (current.kind === 'add') {
1035
- // Add file: every line should start with `+ ` (or be empty).
1219
+ // Add file: every body line starts with `+`. The marker spelling
1220
+ // is settled once the block is complete (addFileLines).
1036
1221
  if (line.startsWith('+')) {
1037
- current.lines.push(line.slice(line[1] === ' ' ? 2 : 1));
1222
+ current.lines.push(line.slice(1));
1038
1223
  }
1039
1224
  continue;
1040
1225
  }
@@ -1053,11 +1238,13 @@ const applyPatchTool = {
1053
1238
  currentHunk = [];
1054
1239
  current.hunks.push(currentHunk);
1055
1240
  }
1241
+ // One marker character; resolvePatchHunk decides whether the
1242
+ // model wrote "marker + space" instead.
1056
1243
  if (line.startsWith('-')) {
1057
- currentHunk.push({ kind: 'removed', text: line.slice(line[1] === ' ' ? 2 : 1) });
1244
+ currentHunk.push({ kind: 'removed', text: line.slice(1) });
1058
1245
  }
1059
1246
  else if (line.startsWith('+')) {
1060
- currentHunk.push({ kind: 'added', text: line.slice(line[1] === ' ' ? 2 : 1) });
1247
+ currentHunk.push({ kind: 'added', text: line.slice(1) });
1061
1248
  }
1062
1249
  else if (line.startsWith(' ')) {
1063
1250
  // Context line preserved IN ORDER — combined with removed/
@@ -1110,8 +1297,9 @@ const applyPatchTool = {
1110
1297
  }
1111
1298
  if (action.kind === 'add') {
1112
1299
  try {
1113
- await ctx.writeFile(absPath, action.lines.join('\n') + (action.lines.length > 0 ? '\n' : ''));
1114
- results.push(`Added: ${action.path} (${action.lines.length} lines)`);
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)`);
1115
1303
  }
1116
1304
  catch (err) {
1117
1305
  results.push(`FAILED Add ${action.path}: ${err instanceof Error ? err.message : String(err)}`);
@@ -1149,32 +1337,18 @@ const applyPatchTool = {
1149
1337
  const hunkFailureNotes = [];
1150
1338
  for (let hi = 0; hi < action.hunks.length; hi++) {
1151
1339
  const hunk = action.hunks[hi];
1152
- const findLines = [];
1153
- const replaceLines = [];
1154
- let contextCount = 0;
1155
- for (const item of hunk) {
1156
- if (item.kind === 'context') {
1157
- findLines.push(item.text);
1158
- replaceLines.push(item.text);
1159
- contextCount++;
1160
- }
1161
- else if (item.kind === 'removed') {
1162
- findLines.push(item.text);
1163
- }
1164
- else if (item.kind === 'added') {
1165
- replaceLines.push(item.text);
1166
- }
1167
- }
1168
- const find = findLines.join('\n');
1169
- 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;
1170
1344
  if (!find) {
1171
1345
  hunksFailed++;
1172
1346
  hunkFailureNotes.push(`hunk #${hi + 1}: empty (no removed lines and no context)`);
1173
1347
  continue;
1174
1348
  }
1175
- const occurrences = after.split(find).length - 1;
1176
1349
  if (occurrences === 1) {
1177
- after = after.replace(find, replace);
1350
+ // Function replacer: a string one would expand `$&`, `$$`, `$1` in the patch text.
1351
+ after = after.replace(find, () => replace);
1178
1352
  hunksApplied++;
1179
1353
  continue;
1180
1354
  }
@@ -1211,6 +1385,27 @@ const applyPatchTool = {
1211
1385
  }
1212
1386
  }
1213
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
+ }
1214
1409
  const replaceLineCount = replace.split('\n').length;
1215
1410
  const replacedLines = [
1216
1411
  ...afterLines.slice(0, matchedStart),
@@ -1585,7 +1780,7 @@ const listFilesTool = {
1585
1780
  if (!files.length) {
1586
1781
  return { output: `No files matched pattern "${pattern}"` };
1587
1782
  }
1588
- const list = files.slice(0, 200).join('\n');
1783
+ const list = files.slice(0, 200).map((f) => workspaceDisplayPath(f, ctx.workspaceRoot)).join('\n');
1589
1784
  const suffix = files.length > 200 ? `\n\n[list_files: showing first 200 of ${files.length} files]` : '';
1590
1785
  return { output: `${files.length} file(s) matched "${pattern}":\n\n${list}${suffix}` };
1591
1786
  }
@@ -1595,6 +1790,25 @@ const listFilesTool = {
1595
1790
  }
1596
1791
  };
1597
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
+ }
1598
1812
  // ── ls ─────────────────────────────────────────────────────────────────────────
1599
1813
  // Dead-simple directory listing. Exists alongside list_files because small
1600
1814
  // models (<= 7B) reliably skip the glob+cwd combo but handle single-path
@@ -1962,6 +2176,25 @@ const ALLOWED_COMMANDS = new Set([
1962
2176
  'curl', 'wget'
1963
2177
  ]);
1964
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
+ }
1965
2198
  /**
1966
2199
  * Map of well-known CLIs the agent might be asked to install but that
1967
2200
  * aren't on the allow-list themselves (terraform, kubectl when not yet
@@ -2137,6 +2370,15 @@ function shellTokenize(input) {
2137
2370
  }
2138
2371
  return out;
2139
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
+ };
2140
2382
  const runCommandTool = {
2141
2383
  name: 'run_command',
2142
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`.',
@@ -2161,6 +2403,25 @@ const runCommandTool = {
2161
2403
  // command line was being treated as a single executable name).
2162
2404
  let cmd = rawCmd;
2163
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;
2164
2425
  const preparsedArgs = maybeParseJsonArrayArgs(argsString);
2165
2426
  const firstSpace = rawCmd.search(/\s/);
2166
2427
  if (firstSpace > 0 && !preparsedArgs) {
@@ -2181,6 +2442,19 @@ const runCommandTool = {
2181
2442
  }
2182
2443
  }
2183
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
+ }
2184
2458
  // un-escape `<` / `>` in `git commit` messages.
2185
2459
  // from a real Bandit commit: the
2186
2460
  // `Co-authored-by: Bandit <bandit@burtson.ai>` trailer was emitted