@alexwkleung/reika 0.15.0 → 0.16.0
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/README.md +3 -2
- package/README.zh-CN.md +2 -1
- package/dist/{chunk-UAN6WUP7.js → chunk-B5PNRULB.js} +2 -2
- package/dist/{chunk-KRT4W3M6.js → chunk-UKVR4EVN.js} +647 -145
- package/dist/cli.js +4 -4
- package/dist/{command-WSXF7YQF.js → command-ISL5BRNZ.js} +2 -2
- package/dist/{headless-KB3EJ6ZL.js → headless-NWTMU3R7.js} +1 -1
- package/dist/{tui-WP36TRUY.js → tui-B4EBWUW6.js} +2 -2
- package/package.json +1 -1
|
@@ -4503,7 +4503,7 @@ function buildGrindPrompt(opts) {
|
|
|
4503
4503
|
'Pin down the task. Before your first tool call, state in a sentence or two what "done" means and anything ambiguous about the request.',
|
|
4504
4504
|
"Look before you act. Find the code involved (grep through bash), read it, find how this codebase already handles similar things, and find the tests that cover it. Never guess a path.",
|
|
4505
4505
|
"Choose deliberately. Name at least two ways to do it and pick one, in a sentence, saying why.",
|
|
4506
|
-
|
|
4506
|
+
`Make the smallest change that does the job. Read a file before you edit it. ${gutterRule(opts.canEditByPosition)}`,
|
|
4507
4507
|
"Prove it by running something. Run the existing tests. Then write and run a quick check for the edge cases your change touches \u2014 empty input, boundaries, error paths, whatever this task makes risky. Put throwaway checks in a temp dir (`mktemp -d`), not the project. A check you only reasoned through does not count. If a check fails, fix the code and run it again: that loop is the work, not a failure.",
|
|
4508
4508
|
"Review your own diff. Run `git diff`, reread it as a reviewer would, and check the callers of anything whose behavior changed.",
|
|
4509
4509
|
"Report honestly. In your final reply, say what you verified by running it, what you did not verify, and what is still uncertain."
|
|
@@ -4628,7 +4628,7 @@ function buildAgentPrompt(opts) {
|
|
|
4628
4628
|
...subagentNudge ? [
|
|
4629
4629
|
"When the request is to trace, explain, or summarize how something works across several files, your FIRST tool call is subagent: give it the question plus every path and symbol you already know, and ask for the chain with file and function names, not line numbers. Its reads stay out of your context and its report counts as tool output. A question one or two files answer, read yourself."
|
|
4630
4630
|
] : [],
|
|
4631
|
-
|
|
4631
|
+
`Before edit, read the file to see exact text. ${gutterRule(opts.canEditByPosition)}`,
|
|
4632
4632
|
"If a tool call fails, do not give up \u2014 try a different tool (grep, list, read) to recover.",
|
|
4633
4633
|
"Only the listed tools exist. Use their exact names.",
|
|
4634
4634
|
"Before creating a new file in an existing directory, OR adding to a registry/list/array, you MUST read at least one existing example to learn its shape and exact exported interface. Never invent a structure.",
|
|
@@ -4698,9 +4698,14 @@ function buildChatPrompt(_bundle) {
|
|
|
4698
4698
|
"You do not have access to the user's filesystem or shell in this mode. If web-search tools are available, use them only when the answer requires current information or external documentation."
|
|
4699
4699
|
].join("\n\n");
|
|
4700
4700
|
}
|
|
4701
|
+
function gutterRule(canEditByPosition) {
|
|
4702
|
+
if (!canEditByPosition) {
|
|
4703
|
+
return "read output prefixes each line with `NNNNN\u2502` \u2014 that gutter is NOT part of the file; copy only the text after `\u2502` into old_string, verbatim including indentation.";
|
|
4704
|
+
}
|
|
4705
|
+
return "read output prefixes each line with `N:hash\u2502` \u2014 that gutter is NOT part of the file. To replace text you have in view, copy only the text after `\u2502` into old_string, verbatim including indentation. When you no longer have the exact text, edit by position instead: insert_after or insert_before a short string from one line, or replace start_line..end_line written as the `N:hash` from the gutter.";
|
|
4706
|
+
}
|
|
4701
4707
|
|
|
4702
4708
|
// src/provider/toolcall.ts
|
|
4703
|
-
var CHARS_PER_TOKEN = 4;
|
|
4704
4709
|
var BUDGET_SAFETY = 0.9;
|
|
4705
4710
|
var CAP_DENSITY_FLOOR = 2.5;
|
|
4706
4711
|
var SENT_DENSITY_FLOOR = 1;
|
|
@@ -4736,7 +4741,7 @@ var SMALL_AGED_PAYLOAD_FLOOR_CHARS = 2048;
|
|
|
4736
4741
|
var SMALL_AGED_PAYLOAD_FLOOR_TOTAL_CHARS = 4096;
|
|
4737
4742
|
var DIFF_STRUCTURE_RE = /^(?:diff --git |--- |\+\+\+ |@@ )/;
|
|
4738
4743
|
var AGED_READ_SKELETON_CHARS = 1024;
|
|
4739
|
-
var READ_GUTTER_RE = /^\s*(\d+)
|
|
4744
|
+
var READ_GUTTER_RE = /^\s*(\d+)(?::[0-9a-f]+)?│(.*)$/;
|
|
4740
4745
|
var DECLARATION_RE = /^(?:export|import|from|declare|async|function|class|interface|type|enum|const|let|var|def|fn|pub|impl|struct|trait|package|module|public|private|protected|func|abstract|extension|namespace)\b/;
|
|
4741
4746
|
var BLOCK_OPENER_RE = /(?:\{|=>|:)\s*$/;
|
|
4742
4747
|
var NON_STRUCTURE_RE = /^(?:[)\]}]|\/\/|\/\*|\*|#|--|;;)/;
|
|
@@ -5346,9 +5351,9 @@ function toolsToChatTools(tools) {
|
|
|
5346
5351
|
}
|
|
5347
5352
|
|
|
5348
5353
|
// src/provider/tokens.ts
|
|
5349
|
-
var
|
|
5354
|
+
var CHARS_PER_TOKEN = 4;
|
|
5350
5355
|
function estimateTokens(text) {
|
|
5351
|
-
return Math.ceil(text.length /
|
|
5356
|
+
return Math.ceil(text.length / CHARS_PER_TOKEN);
|
|
5352
5357
|
}
|
|
5353
5358
|
function estimateRequestTokens(system, history, tools, opts) {
|
|
5354
5359
|
const messages = messagesToChatParams(system, history, {
|
|
@@ -5556,6 +5561,7 @@ var FENCE_BLOCK = /```([^\n`]*)\n([\s\S]*?)```/g;
|
|
|
5556
5561
|
var MIN_SNIPPET_CHARS = 8;
|
|
5557
5562
|
var NON_IDENTIFIER_CHAR = /[^A-Za-z0-9_$.]/;
|
|
5558
5563
|
var MAX_SNIPPETS_PER_STEP = 6;
|
|
5564
|
+
var REMOVAL_INTENT = /\b(?:remov(?:e|es|ed|ing|al)|delet(?:e|es|ed|ing|ion)|drop(?:s|ped|ping)?|strip(?:s|ped|ping)?|prun(?:e|es|ed|ing)|eliminat(?:e|es|ed|ing|ion)|get(?:ting)? rid|clean(?:s|ed|ing)?[ -]?up|unused|dead code|revert(?:s|ed|ing)?|undo(?:es|ing)?|mov(?:e|es|ed|ing)|renam(?:e|es|ed|ing)|inlin(?:e|es|ed|ing)|extract(?:s|ed|ing)?|consolidat(?:e|es|ed|ing)|merg(?:e|es|ed|ing)|de-?dup\w*|simplif(?:y|ies|ied|ying)|trim(?:s|med|ming)?|collaps(?:e|es|ed|ing)|shorten(?:s|ed|ing)?)\b/i;
|
|
5559
5565
|
function collapseWhitespace(s) {
|
|
5560
5566
|
return s.replace(/\s+/g, " ").trim();
|
|
5561
5567
|
}
|
|
@@ -5602,8 +5608,9 @@ function extractStepRefs(body) {
|
|
|
5602
5608
|
const c = commandLineOf(line);
|
|
5603
5609
|
if (c) addCommand(c);
|
|
5604
5610
|
}
|
|
5605
|
-
|
|
5606
|
-
|
|
5611
|
+
const prose = noFences.replace(/`[^`\n]*`/g, " ");
|
|
5612
|
+
for (const m of prose.matchAll(BARE_PATH)) addPath(m[1]);
|
|
5613
|
+
return { paths, snippets, commands, removes: REMOVAL_INTENT.test(prose) };
|
|
5607
5614
|
}
|
|
5608
5615
|
var BULLET_START = /^\s{0,3}[-*•]\s+(\S.*)$/;
|
|
5609
5616
|
function lineQuotesCommand(text) {
|
|
@@ -5670,18 +5677,28 @@ function pathsMatch(planPath, editedPath) {
|
|
|
5670
5677
|
const b = normalizePath(editedPath);
|
|
5671
5678
|
return a === b || a.endsWith("/" + b) || b.endsWith("/" + a);
|
|
5672
5679
|
}
|
|
5673
|
-
function
|
|
5680
|
+
function changedLines(diffText) {
|
|
5681
|
+
const out = [];
|
|
5682
|
+
for (const line of diffText.split("\n")) {
|
|
5683
|
+
if (line.startsWith("+") || line.startsWith("-")) out.push(line.slice(2));
|
|
5684
|
+
}
|
|
5685
|
+
return out.join("\n");
|
|
5686
|
+
}
|
|
5687
|
+
function applyEdit(steps, editedPath, diffText, counts) {
|
|
5688
|
+
const deletionOnly = counts !== void 0 && counts.added === 0 && counts.removed > 0;
|
|
5689
|
+
const eligible = (s) => !s.done && !s.waived && (!deletionOnly || s.removes === true);
|
|
5674
5690
|
for (let i = 0; i < steps.length; i++) {
|
|
5675
5691
|
const s = steps[i];
|
|
5676
|
-
if (
|
|
5692
|
+
if (eligible(s) && s.paths.some((p) => pathsMatch(p, editedPath))) {
|
|
5677
5693
|
s.done = true;
|
|
5678
5694
|
return { index: i, by: "path" };
|
|
5679
5695
|
}
|
|
5680
5696
|
}
|
|
5681
5697
|
if (diffText) {
|
|
5698
|
+
const changed = changedLines(diffText);
|
|
5682
5699
|
for (let i = 0; i < steps.length; i++) {
|
|
5683
5700
|
const s = steps[i];
|
|
5684
|
-
if (
|
|
5701
|
+
if (eligible(s) && s.snippets.some((sn) => changed.includes(sn))) {
|
|
5685
5702
|
s.done = true;
|
|
5686
5703
|
return { index: i, by: "content" };
|
|
5687
5704
|
}
|
|
@@ -5689,11 +5706,26 @@ function applyEdit(steps, editedPath, diffText) {
|
|
|
5689
5706
|
}
|
|
5690
5707
|
return null;
|
|
5691
5708
|
}
|
|
5709
|
+
function applyTreeChanges(steps, changes) {
|
|
5710
|
+
let match = null;
|
|
5711
|
+
for (const f of changes.files) {
|
|
5712
|
+
const hit = applyEdit(steps, f.path, f.hunks.map((h) => h.text).join("\n"), f);
|
|
5713
|
+
if (hit) match = hit;
|
|
5714
|
+
}
|
|
5715
|
+
return match;
|
|
5716
|
+
}
|
|
5717
|
+
function containsCommand(ran, command) {
|
|
5718
|
+
for (let at = ran.indexOf(command); at >= 0; at = ran.indexOf(command, at + 1)) {
|
|
5719
|
+
const next = ran[at + command.length];
|
|
5720
|
+
if (next === void 0 || /[\s;&|)]/.test(next)) return true;
|
|
5721
|
+
}
|
|
5722
|
+
return false;
|
|
5723
|
+
}
|
|
5692
5724
|
function applyCommand(steps, commandText) {
|
|
5693
5725
|
const ran = collapseWhitespace(commandText);
|
|
5694
5726
|
for (let i = 0; i < steps.length; i++) {
|
|
5695
5727
|
const s = steps[i];
|
|
5696
|
-
if (!s.done && !s.waived && s.commands.some((c) => ran
|
|
5728
|
+
if (!s.done && !s.waived && s.commands.some((c) => containsCommand(ran, c))) {
|
|
5697
5729
|
s.done = true;
|
|
5698
5730
|
return i;
|
|
5699
5731
|
}
|
|
@@ -5772,19 +5804,32 @@ function seedPlanProgress(history) {
|
|
|
5772
5804
|
const marker = latestPlanMarker(history);
|
|
5773
5805
|
if (!marker || marker.steps.length === 0) return null;
|
|
5774
5806
|
const steps = marker.steps;
|
|
5807
|
+
const settled = marker.message.role === "assistant" ? marker.message.planSettled : void 0;
|
|
5808
|
+
for (const s of steps) {
|
|
5809
|
+
if (settled?.done.includes(s.n)) s.done = true;
|
|
5810
|
+
else if (settled?.waived.includes(s.n)) s.waived = true;
|
|
5811
|
+
}
|
|
5775
5812
|
for (let i = marker.index + 1; i < history.length; i++) {
|
|
5776
5813
|
const m = history[i];
|
|
5777
5814
|
const edited = editedPathFrom(m);
|
|
5778
5815
|
if (edited && m.role === "tool") {
|
|
5779
|
-
applyEdit(steps, edited, m.diff?.text);
|
|
5780
|
-
} else if (m.role === "tool" && m.command?.text
|
|
5781
|
-
|
|
5782
|
-
|
|
5783
|
-
for (const s of steps) if (m.planWaived.includes(s.n) && !s.done) s.waived = true;
|
|
5816
|
+
applyEdit(steps, edited, m.diff?.text, m.diff);
|
|
5817
|
+
} else if (m.role === "tool" && (m.changes || m.command?.text)) {
|
|
5818
|
+
if (m.changes) applyTreeChanges(steps, m.changes);
|
|
5819
|
+
if (m.command?.text && ranSuccessfully(m)) applyCommand(steps, m.command.text);
|
|
5784
5820
|
}
|
|
5785
5821
|
}
|
|
5786
5822
|
return steps;
|
|
5787
5823
|
}
|
|
5824
|
+
function recordPlanSettled(history, steps) {
|
|
5825
|
+
const marker = latestPlanMarker(history);
|
|
5826
|
+
if (!marker || marker.message.role !== "assistant") return;
|
|
5827
|
+
if (marker.steps.length !== steps.length) return;
|
|
5828
|
+
marker.message.planSettled = {
|
|
5829
|
+
done: steps.filter((s) => s.done).map((s) => s.n),
|
|
5830
|
+
waived: steps.filter((s) => s.waived).map((s) => s.n)
|
|
5831
|
+
};
|
|
5832
|
+
}
|
|
5788
5833
|
function stepLine(s) {
|
|
5789
5834
|
const text = s.text.length > MAX_STEP_TEXT ? s.text.slice(0, MAX_STEP_TEXT - 1) + "\u2026" : s.text;
|
|
5790
5835
|
return `[${s.done ? "x" : s.waived ? "~" : " "}] ${s.n}. ${text}`;
|
|
@@ -5943,7 +5988,6 @@ function createSearchTool(provider) {
|
|
|
5943
5988
|
}
|
|
5944
5989
|
|
|
5945
5990
|
// src/agent/compaction.ts
|
|
5946
|
-
var CHARS_PER_TOKEN3 = 4;
|
|
5947
5991
|
var KEEP_FRACTION = 0.3;
|
|
5948
5992
|
var RECAP_FRACTION = 0.1;
|
|
5949
5993
|
var HANDOFF_FINDINGS_FRACTION = 0.15;
|
|
@@ -5964,7 +6008,7 @@ function foldPoint(history, contextWindow, calibration = 1, minGen = DEFAULT_MIN
|
|
|
5964
6008
|
if (!contextWindow) return null;
|
|
5965
6009
|
const calib = calibration > 0 ? calibration : 1;
|
|
5966
6010
|
const avail = availTokens(contextWindow, minGen);
|
|
5967
|
-
const keepBudget = avail *
|
|
6011
|
+
const keepBudget = avail * CHARS_PER_TOKEN * KEEP_FRACTION / calib;
|
|
5968
6012
|
let chars = 0;
|
|
5969
6013
|
let keepFrom = history.length;
|
|
5970
6014
|
for (let i = history.length - 1; i >= 0; i--) {
|
|
@@ -5980,7 +6024,8 @@ function foldPoint(history, contextWindow, calibration = 1, minGen = DEFAULT_MIN
|
|
|
5980
6024
|
return { recapStart, keepFrom, avail, calib };
|
|
5981
6025
|
}
|
|
5982
6026
|
function wouldFold(history, contextWindow, calibration = 1, minGen = DEFAULT_MIN_GEN_TOKENS) {
|
|
5983
|
-
|
|
6027
|
+
const point = foldPoint(history, contextWindow, calibration, minGen);
|
|
6028
|
+
return point !== null && point.keepFrom - point.recapStart > keptPlan(history, point).length;
|
|
5984
6029
|
}
|
|
5985
6030
|
function foldAfterShed(history, estimate, contextWindow, calibration = 1, minGen = DEFAULT_MIN_GEN_TOKENS, shedReasoning = true, requirePressure = true) {
|
|
5986
6031
|
const copy = history.map((m) => ({ ...m }));
|
|
@@ -5993,17 +6038,35 @@ function compactHistory(history, contextWindow, calibration = 1, minGen = DEFAUL
|
|
|
5993
6038
|
const point = foldPoint(history, contextWindow, calibration, minGen);
|
|
5994
6039
|
if (!point) return 0;
|
|
5995
6040
|
const { recapStart, keepFrom, avail, calib } = point;
|
|
5996
|
-
|
|
6041
|
+
return foldRange(history, recapStart, keepFrom, avail, calib, note, keptPlan(history, point));
|
|
6042
|
+
}
|
|
6043
|
+
function keptPlan(history, point) {
|
|
6044
|
+
const plan = latestPlanMarker(history);
|
|
6045
|
+
if (!plan || plan.steps.length === 0) return [];
|
|
6046
|
+
const at = plan.index;
|
|
6047
|
+
if (at < point.recapStart || at + 1 >= point.keepFrom) return [];
|
|
6048
|
+
if (history[at + 1].role !== "user") return [];
|
|
6049
|
+
const steps = seedPlanProgress(history);
|
|
6050
|
+
if (!steps || steps.every((s) => s.done || s.waived)) return [];
|
|
6051
|
+
recordPlanSettled(history, steps);
|
|
6052
|
+
return [at, at + 1];
|
|
6053
|
+
}
|
|
6054
|
+
function foldRange(history, recapStart, keepFrom, avail, calib, note, keep = []) {
|
|
6055
|
+
if (keepFrom - recapStart <= keep.length) return 0;
|
|
6056
|
+
const span = history.slice(recapStart, keepFrom).filter((_, k) => !keep.includes(recapStart + k));
|
|
6057
|
+
const kept = keep.map((k) => history[k]);
|
|
5997
6058
|
const turnStart = Math.max(recapStart, lastUserMessageIndex(history) + 1);
|
|
5998
6059
|
const preserved = carriedSpecBlock(history.slice(turnStart, keepFrom)) ?? electSpecBlock(history, recapStart, keepFrom);
|
|
5999
6060
|
const recap = buildRecap(span, avail, calib, note);
|
|
6000
|
-
history.splice(
|
|
6001
|
-
|
|
6002
|
-
|
|
6061
|
+
history.splice(
|
|
6062
|
+
recapStart,
|
|
6063
|
+
keepFrom - recapStart,
|
|
6064
|
+
{ role: "compaction", content: preserved ? `${preserved}
|
|
6003
6065
|
|
|
6004
|
-
${recap}` : recap
|
|
6005
|
-
|
|
6006
|
-
|
|
6066
|
+
${recap}` : recap },
|
|
6067
|
+
...kept
|
|
6068
|
+
);
|
|
6069
|
+
return keepFrom - recapStart - kept.length;
|
|
6007
6070
|
}
|
|
6008
6071
|
var AGE_LOW_FRACTION = ageLowFraction();
|
|
6009
6072
|
function ageLowFraction() {
|
|
@@ -6242,7 +6305,7 @@ function describeFile(path, ranges) {
|
|
|
6242
6305
|
}
|
|
6243
6306
|
var NOTE_SHARE = 0.7;
|
|
6244
6307
|
function buildRecap(span, avail, calib, note) {
|
|
6245
|
-
const recapBudget = avail *
|
|
6308
|
+
const recapBudget = avail * CHARS_PER_TOKEN * RECAP_FRACTION / calib;
|
|
6246
6309
|
const priorRecaps = [];
|
|
6247
6310
|
const entries = [];
|
|
6248
6311
|
const toolCounts = {};
|
|
@@ -6422,7 +6485,7 @@ function distillPlanHandoff(history, contextWindow, calibration = 1, minGen = DE
|
|
|
6422
6485
|
if (span.every((m) => m.role === "compaction")) return { folded: 0, reason: "already-distilled" };
|
|
6423
6486
|
const calib = calibration > 0 ? calibration : 1;
|
|
6424
6487
|
const findingsBudget = contextWindow ? Math.floor(
|
|
6425
|
-
availTokens(contextWindow, minGen) *
|
|
6488
|
+
availTokens(contextWindow, minGen) * CHARS_PER_TOKEN * findingsBudgetFraction / calib
|
|
6426
6489
|
) : Number.MAX_SAFE_INTEGER;
|
|
6427
6490
|
const digest = buildHandoffDigest(span, findingsBudget);
|
|
6428
6491
|
history.splice(spanStart, span.length, { role: "compaction", content: digest });
|
|
@@ -9816,7 +9879,30 @@ function gitMetadataWarning(cwd, full) {
|
|
|
9816
9879
|
}
|
|
9817
9880
|
|
|
9818
9881
|
// src/tools/read.ts
|
|
9882
|
+
import { createHash as createHash4 } from "node:crypto";
|
|
9883
|
+
|
|
9884
|
+
// src/tools/_lineref.ts
|
|
9819
9885
|
import { createHash as createHash3 } from "node:crypto";
|
|
9886
|
+
function positionalEditsEnabled() {
|
|
9887
|
+
return process.env.REIKA_EDIT_POSITION === "1";
|
|
9888
|
+
}
|
|
9889
|
+
var LINE_HASH_CHARS = 3;
|
|
9890
|
+
function lineHash(line) {
|
|
9891
|
+
return createHash3("sha1").update(line.replace(/\r$/, "")).digest("hex").slice(0, LINE_HASH_CHARS);
|
|
9892
|
+
}
|
|
9893
|
+
function gutterLine(n, line, hashed = positionalEditsEnabled()) {
|
|
9894
|
+
return `${String(n).padStart(5, " ")}${hashed ? `:${lineHash(line)}` : ""}\u2502${line}`;
|
|
9895
|
+
}
|
|
9896
|
+
var GUTTER_PREFIX_RE = /^\s*\d+(?::[0-9a-f]+)?│/;
|
|
9897
|
+
function parseLineRef(value) {
|
|
9898
|
+
if (typeof value === "number" && Number.isInteger(value)) return { line: value };
|
|
9899
|
+
if (typeof value !== "string") return null;
|
|
9900
|
+
const m = /^\s*(\d+)\s*(?::\s*([0-9a-fA-F]+))?\s*(?:│.*)?$/.exec(value);
|
|
9901
|
+
if (!m) return null;
|
|
9902
|
+
return { line: Number(m[1]), ...m[2] ? { hash: m[2].toLowerCase() } : {} };
|
|
9903
|
+
}
|
|
9904
|
+
|
|
9905
|
+
// src/tools/read.ts
|
|
9820
9906
|
var READ_DEFAULT_LIMIT = 300;
|
|
9821
9907
|
var readTool = {
|
|
9822
9908
|
name: "read",
|
|
@@ -9839,7 +9925,7 @@ var readTool = {
|
|
|
9839
9925
|
const limit = Math.max(1, Number(args.limit ?? READ_DEFAULT_LIMIT));
|
|
9840
9926
|
const full = resolveUserPath(ctx.cwd, path);
|
|
9841
9927
|
const text = await readFile7(full, "utf8");
|
|
9842
|
-
const contentHash =
|
|
9928
|
+
const contentHash = createHash4("sha1").update(text).digest("hex");
|
|
9843
9929
|
const lines = text.split("\n");
|
|
9844
9930
|
const total = lines.length > 1 && lines[lines.length - 1] === "" ? lines.length - 1 : lines.length;
|
|
9845
9931
|
const relToCwd = relative6(ctx.cwd, full);
|
|
@@ -9854,7 +9940,7 @@ var readTool = {
|
|
|
9854
9940
|
const sliceEnd = Math.min(offset - 1 + limit, total);
|
|
9855
9941
|
const slice = lines.slice(offset - 1, sliceEnd);
|
|
9856
9942
|
const end = offset - 1 + slice.length;
|
|
9857
|
-
const numbered = slice.map((l, i) =>
|
|
9943
|
+
const numbered = slice.map((l, i) => gutterLine(offset + i, l)).join("\n");
|
|
9858
9944
|
const remaining = total - end;
|
|
9859
9945
|
const more = remaining > 0 ? `
|
|
9860
9946
|
\u2026(${remaining} more line${remaining === 1 ? "" : "s"} below \u2014 call read with offset=${end + 1} to continue)` : "";
|
|
@@ -11080,60 +11166,38 @@ ${p.surface}
|
|
|
11080
11166
|
}
|
|
11081
11167
|
|
|
11082
11168
|
// src/tools/edit.ts
|
|
11169
|
+
var EDIT_PARAMETERS = {
|
|
11170
|
+
path: { type: "string", description: "File path, relative to cwd." },
|
|
11171
|
+
old_string: {
|
|
11172
|
+
type: "string",
|
|
11173
|
+
description: "Exact text to replace. Include enough context to be unique in the file."
|
|
11174
|
+
},
|
|
11175
|
+
new_string: { type: "string", description: "Replacement text." }
|
|
11176
|
+
};
|
|
11083
11177
|
var editTool = {
|
|
11084
11178
|
name: "edit",
|
|
11085
11179
|
description: "Replace one exact-match occurrence of old_string with new_string in a file. Fails if old_string is missing or appears more than once \u2014 add surrounding context to make it unique.",
|
|
11086
11180
|
parameters: {
|
|
11087
11181
|
type: "object",
|
|
11088
|
-
properties:
|
|
11089
|
-
path: { type: "string", description: "File path, relative to cwd." },
|
|
11090
|
-
old_string: {
|
|
11091
|
-
type: "string",
|
|
11092
|
-
description: "Exact text to replace. Include enough context to be unique in the file."
|
|
11093
|
-
},
|
|
11094
|
-
new_string: { type: "string", description: "Replacement text." }
|
|
11095
|
-
},
|
|
11182
|
+
properties: EDIT_PARAMETERS,
|
|
11096
11183
|
required: ["path", "old_string", "new_string"]
|
|
11097
11184
|
},
|
|
11098
11185
|
async run(args, ctx) {
|
|
11099
|
-
const path = String(args.path);
|
|
11100
11186
|
const oldStr = String(args.old_string ?? "");
|
|
11101
11187
|
const newStr = String(args.new_string ?? "");
|
|
11102
|
-
const
|
|
11103
|
-
const
|
|
11104
|
-
|
|
11105
|
-
const
|
|
11106
|
-
const warnings = [...outside ? [OUTSIDE_PROJECT_WARNING] : [], ...gitMeta ? [gitMeta] : []];
|
|
11107
|
-
const rel = relative10(ctx.cwd, full) || path;
|
|
11108
|
-
const display = outside ? full : rel;
|
|
11109
|
-
if (gated && !ctx.requestApproval) {
|
|
11110
|
-
if (outside) {
|
|
11111
|
-
return {
|
|
11112
|
-
summary: `Edit refused: ${full} is outside the project directory (${ctx.cwd}), and approvals are bypassed so it cannot be confirmed with the user. Edit inside the project instead.`
|
|
11113
|
-
};
|
|
11114
|
-
}
|
|
11115
|
-
return {
|
|
11116
|
-
summary: `Edit refused: ${display} is git config or a hook, which runs code at the user's next git command. Approvals are bypassed so it cannot be confirmed with the user; edit a project file instead, or leave the change for the user.`
|
|
11117
|
-
};
|
|
11118
|
-
}
|
|
11188
|
+
const target = resolveEditTarget(String(args.path), ctx);
|
|
11189
|
+
const refused = refuseUnconfirmable(target, ctx);
|
|
11190
|
+
if (refused) return refused;
|
|
11191
|
+
const { display } = target;
|
|
11119
11192
|
if (oldStr === "") {
|
|
11120
11193
|
return { summary: `Edit failed: old_string is empty` };
|
|
11121
11194
|
}
|
|
11122
11195
|
if (oldStr === newStr) {
|
|
11123
11196
|
return { summary: `Edit failed: old_string and new_string are identical` };
|
|
11124
11197
|
}
|
|
11125
|
-
|
|
11126
|
-
if (
|
|
11127
|
-
|
|
11128
|
-
tool: "edit",
|
|
11129
|
-
subject: display,
|
|
11130
|
-
preview: intentDiff(oldStr, newStr),
|
|
11131
|
-
warnings
|
|
11132
|
-
});
|
|
11133
|
-
if (!ok) return { summary: declineSummary("Edit", ` for ${display}`, ctx) };
|
|
11134
|
-
approvedOutside = true;
|
|
11135
|
-
}
|
|
11136
|
-
const text = await readFile10(full, "utf8");
|
|
11198
|
+
const consent = await consentBeforeRead(target, ctx, intentDiff(oldStr, newStr));
|
|
11199
|
+
if (consent === "declined") return { summary: declineSummary("Edit", ` for ${display}`, ctx) };
|
|
11200
|
+
const text = await readFile10(target.full, "utf8");
|
|
11137
11201
|
let start;
|
|
11138
11202
|
let matchLen;
|
|
11139
11203
|
let effectiveNew;
|
|
@@ -11144,7 +11208,7 @@ var editTool = {
|
|
|
11144
11208
|
const a = lineOf(text, first);
|
|
11145
11209
|
const b = lineOf(text, second);
|
|
11146
11210
|
return {
|
|
11147
|
-
summary: `Edit failed: old_string appears multiple times in ${display} (lines ${a}, ${b}); add surrounding context to make it unique`
|
|
11211
|
+
summary: `Edit failed: old_string appears multiple times in ${display} (lines ${a}, ${b}); add surrounding context to make it unique` + rangePointer(text.split("\n"), [a - 1, b - 1], blockLineCount(oldStr))
|
|
11148
11212
|
};
|
|
11149
11213
|
}
|
|
11150
11214
|
start = first;
|
|
@@ -11154,7 +11218,11 @@ var editTool = {
|
|
|
11154
11218
|
const fuzzy = fuzzyLineMatch(text, oldStr, newStr);
|
|
11155
11219
|
if (fuzzy.status === "multiple") {
|
|
11156
11220
|
return {
|
|
11157
|
-
summary: `Edit failed: old_string appears multiple times in ${display} (lines ${fuzzy.lines.join(", ")}); add surrounding context to make it unique`
|
|
11221
|
+
summary: `Edit failed: old_string appears multiple times in ${display} (lines ${fuzzy.lines.join(", ")}); add surrounding context to make it unique` + rangePointer(
|
|
11222
|
+
text.split("\n"),
|
|
11223
|
+
fuzzy.lines.map((l) => l - 1),
|
|
11224
|
+
blockLineCount(oldStr)
|
|
11225
|
+
)
|
|
11158
11226
|
};
|
|
11159
11227
|
}
|
|
11160
11228
|
if (fuzzy.status === "mixed") {
|
|
@@ -11175,49 +11243,314 @@ var editTool = {
|
|
|
11175
11243
|
matchLen = fuzzy.len;
|
|
11176
11244
|
effectiveNew = fuzzy.newStr;
|
|
11177
11245
|
}
|
|
11178
|
-
|
|
11179
|
-
|
|
11180
|
-
|
|
11181
|
-
|
|
11182
|
-
|
|
11183
|
-
|
|
11184
|
-
|
|
11185
|
-
|
|
11186
|
-
|
|
11187
|
-
|
|
11188
|
-
|
|
11189
|
-
|
|
11190
|
-
|
|
11191
|
-
|
|
11192
|
-
|
|
11193
|
-
|
|
11194
|
-
|
|
11195
|
-
|
|
11196
|
-
|
|
11197
|
-
|
|
11246
|
+
return commitEdit(ctx, target, text, { start, len: matchLen, newStr: effectiveNew }, consent);
|
|
11247
|
+
}
|
|
11248
|
+
};
|
|
11249
|
+
function resolveEditTarget(path, ctx) {
|
|
11250
|
+
const full = resolveUserPath(ctx.cwd, path);
|
|
11251
|
+
const outside = escapesProject(ctx.cwd, full);
|
|
11252
|
+
const gitMeta = gitMetadataWarning(ctx.cwd, full);
|
|
11253
|
+
const warnings = [...outside ? [OUTSIDE_PROJECT_WARNING] : [], ...gitMeta ? [gitMeta] : []];
|
|
11254
|
+
const rel = relative10(ctx.cwd, full) || path;
|
|
11255
|
+
return {
|
|
11256
|
+
full,
|
|
11257
|
+
rel,
|
|
11258
|
+
display: outside ? full : rel,
|
|
11259
|
+
outside,
|
|
11260
|
+
gated: outside || gitMeta !== void 0,
|
|
11261
|
+
warnings
|
|
11262
|
+
};
|
|
11263
|
+
}
|
|
11264
|
+
function refuseUnconfirmable(t, ctx) {
|
|
11265
|
+
if (!t.gated || ctx.requestApproval) return null;
|
|
11266
|
+
if (t.outside) {
|
|
11267
|
+
return {
|
|
11268
|
+
summary: `Edit refused: ${t.full} is outside the project directory (${ctx.cwd}), and approvals are bypassed so it cannot be confirmed with the user. Edit inside the project instead.`
|
|
11269
|
+
};
|
|
11270
|
+
}
|
|
11271
|
+
return {
|
|
11272
|
+
summary: `Edit refused: ${t.display} is git config or a hook, which runs code at the user's next git command. Approvals are bypassed so it cannot be confirmed with the user; edit a project file instead, or leave the change for the user.`
|
|
11273
|
+
};
|
|
11274
|
+
}
|
|
11275
|
+
async function consentBeforeRead(t, ctx, preview) {
|
|
11276
|
+
if (!t.gated || !ctx.requestApproval) return "not-gated";
|
|
11277
|
+
const ok = await ctx.requestApproval({
|
|
11278
|
+
tool: "edit",
|
|
11279
|
+
subject: t.display,
|
|
11280
|
+
preview,
|
|
11281
|
+
warnings: t.warnings
|
|
11282
|
+
});
|
|
11283
|
+
return ok ? "approved" : "declined";
|
|
11284
|
+
}
|
|
11285
|
+
async function commitEdit(ctx, t, text, r, consent) {
|
|
11286
|
+
const { display, rel } = t;
|
|
11287
|
+
const { start, len: matchLen, newStr: effectiveNew } = r;
|
|
11288
|
+
const matchedOld = text.slice(start, start + matchLen);
|
|
11289
|
+
const beforeText = text.slice(0, start);
|
|
11290
|
+
const diffText = buildEditDiff(
|
|
11291
|
+
matchedOld,
|
|
11292
|
+
effectiveNew,
|
|
11293
|
+
beforeText,
|
|
11294
|
+
text.slice(start + matchLen)
|
|
11295
|
+
);
|
|
11296
|
+
const startLine = editDiffStartLine(beforeText);
|
|
11297
|
+
if (ctx.requestApproval && consent !== "approved") {
|
|
11298
|
+
const ok = await ctx.requestApproval({
|
|
11299
|
+
tool: "edit",
|
|
11300
|
+
subject: display,
|
|
11301
|
+
preview: diffText,
|
|
11302
|
+
startLine
|
|
11303
|
+
});
|
|
11304
|
+
if (!ok) return { summary: declineSummary("Edit", ` for ${display}`, ctx) };
|
|
11305
|
+
}
|
|
11306
|
+
const current = await readFile10(t.full, "utf8").catch(() => null);
|
|
11307
|
+
if (current !== text) {
|
|
11308
|
+
return {
|
|
11309
|
+
summary: `Edit failed: ${display} changed on disk while the edit was being prepared; nothing was written. Re-read it and retry the edit against its current contents`
|
|
11310
|
+
};
|
|
11311
|
+
}
|
|
11312
|
+
const next = text.slice(0, start) + effectiveNew + text.slice(start + matchLen);
|
|
11313
|
+
await writeFile(t.full, next, "utf8");
|
|
11314
|
+
const line = r.line ?? text.slice(0, start).split("\n").length;
|
|
11315
|
+
const added = countPrefixed(diffText, "+ ");
|
|
11316
|
+
const removed = countPrefixed(diffText, "- ");
|
|
11317
|
+
const [depPayload, url] = await Promise.all([
|
|
11318
|
+
surfaceImportedDeps(ctx, effectiveNew),
|
|
11319
|
+
groundUrls(ctx, effectiveNew, rel)
|
|
11320
|
+
]);
|
|
11321
|
+
const refreshed = refreshedFile(display, next);
|
|
11322
|
+
const payload = [r.removed, depPayload, url.note, refreshed].filter(Boolean).join("\n\n") || void 0;
|
|
11323
|
+
const diff = { text: diffText, path: rel, added, removed, startLine };
|
|
11324
|
+
return {
|
|
11325
|
+
summary: `Edited ${display} at line ${line} (+${added} -${removed})`,
|
|
11326
|
+
diff,
|
|
11327
|
+
...payload ? { payload } : {},
|
|
11328
|
+
...url.notice ? { notice: url.notice } : {}
|
|
11329
|
+
};
|
|
11330
|
+
}
|
|
11331
|
+
var POSITION_KEYS = ["insert_after", "insert_before", "start_line", "end_line"];
|
|
11332
|
+
var positionalEditTool = {
|
|
11333
|
+
...editTool,
|
|
11334
|
+
description: 'Change a file. Either replace one exact-match old_string with new_string (fails if missing or not unique), or give a position instead of old_string: insert_after/insert_before the one line containing a short string, or replace lines start_line..end_line, each written "N:hash" as copied from the read gutter. A wrong position writes nothing and says what to fix.',
|
|
11335
|
+
parameters: {
|
|
11336
|
+
type: "object",
|
|
11337
|
+
properties: {
|
|
11338
|
+
...EDIT_PARAMETERS,
|
|
11339
|
+
old_string: {
|
|
11340
|
+
type: "string",
|
|
11341
|
+
description: "Exact text to replace. Omit it when giving a position."
|
|
11342
|
+
},
|
|
11343
|
+
new_string: { type: "string", description: "Replacement or inserted text." },
|
|
11344
|
+
insert_after: {
|
|
11345
|
+
type: "string",
|
|
11346
|
+
description: "Insert new_string after the one line containing this text."
|
|
11347
|
+
},
|
|
11348
|
+
insert_before: {
|
|
11349
|
+
type: "string",
|
|
11350
|
+
description: "Insert new_string before the one line containing this text."
|
|
11351
|
+
},
|
|
11352
|
+
start_line: {
|
|
11353
|
+
type: "string",
|
|
11354
|
+
description: 'First line to replace, "N:hash" from the read gutter (e.g. "120:a3f").'
|
|
11355
|
+
},
|
|
11356
|
+
end_line: {
|
|
11357
|
+
type: "string",
|
|
11358
|
+
description: 'Last line to replace, "N:hash". Defaults to start_line.'
|
|
11359
|
+
}
|
|
11360
|
+
},
|
|
11361
|
+
required: ["path", "new_string"]
|
|
11362
|
+
},
|
|
11363
|
+
async run(args, ctx) {
|
|
11364
|
+
if (!hasPositionArgs(args)) return editTool.run(args, ctx);
|
|
11365
|
+
if (String(args.old_string ?? "") !== "") {
|
|
11198
11366
|
return {
|
|
11199
|
-
summary:
|
|
11367
|
+
summary: "Edit failed: give either old_string or a position (insert_after, insert_before, start_line/end_line), not both"
|
|
11200
11368
|
};
|
|
11201
11369
|
}
|
|
11202
|
-
const
|
|
11203
|
-
|
|
11204
|
-
|
|
11205
|
-
const
|
|
11206
|
-
const
|
|
11207
|
-
|
|
11208
|
-
|
|
11209
|
-
|
|
11210
|
-
|
|
11211
|
-
|
|
11212
|
-
|
|
11370
|
+
const target = resolveEditTarget(String(args.path), ctx);
|
|
11371
|
+
const refused = refuseUnconfirmable(target, ctx);
|
|
11372
|
+
if (refused) return refused;
|
|
11373
|
+
const newStr = String(args.new_string ?? "");
|
|
11374
|
+
const consent = await consentBeforeRead(
|
|
11375
|
+
target,
|
|
11376
|
+
ctx,
|
|
11377
|
+
newStr.split("\n").map((l) => `+ ${l}`).join("\n")
|
|
11378
|
+
);
|
|
11379
|
+
if (consent === "declined") {
|
|
11380
|
+
return { summary: declineSummary("Edit", ` for ${target.display}`, ctx) };
|
|
11381
|
+
}
|
|
11382
|
+
const text = await readFile10(target.full, "utf8");
|
|
11383
|
+
const r = resolvePosition(text, args, target.display);
|
|
11384
|
+
if ("summary" in r) return r;
|
|
11385
|
+
return commitEdit(ctx, target, text, r, consent);
|
|
11386
|
+
}
|
|
11387
|
+
};
|
|
11388
|
+
function hasPositionArgs(args) {
|
|
11389
|
+
return POSITION_KEYS.some((k) => args[k] !== void 0 && args[k] !== null && args[k] !== "");
|
|
11390
|
+
}
|
|
11391
|
+
function positionLands(text, args) {
|
|
11392
|
+
return !("summary" in resolvePosition(text, args, ""));
|
|
11393
|
+
}
|
|
11394
|
+
function resolvePosition(text, args, display) {
|
|
11395
|
+
const given = POSITION_KEYS.filter(
|
|
11396
|
+
(k) => args[k] !== void 0 && args[k] !== null && args[k] !== ""
|
|
11397
|
+
);
|
|
11398
|
+
const inserts = given.filter((k) => k === "insert_after" || k === "insert_before");
|
|
11399
|
+
const ranged = given.length > inserts.length;
|
|
11400
|
+
if (inserts.length > 1 || inserts.length === 1 && ranged) {
|
|
11213
11401
|
return {
|
|
11214
|
-
summary:
|
|
11215
|
-
diff: { text: diffText, path: rel, added, removed, startLine },
|
|
11216
|
-
...payload ? { payload } : {},
|
|
11217
|
-
...url.notice ? { notice: url.notice } : {}
|
|
11402
|
+
summary: "Edit failed: give one position \u2014 insert_after, insert_before, or start_line/end_line"
|
|
11218
11403
|
};
|
|
11219
11404
|
}
|
|
11220
|
-
|
|
11405
|
+
const newStr = String(args.new_string ?? "");
|
|
11406
|
+
const lines = text.split("\n");
|
|
11407
|
+
const total = lines.length > 1 && lines[lines.length - 1] === "" ? lines.length - 1 : lines.length;
|
|
11408
|
+
if (inserts.length === 1) {
|
|
11409
|
+
return resolveInsert(lines, total, inserts[0], String(args[inserts[0]]), newStr, display);
|
|
11410
|
+
}
|
|
11411
|
+
if (args.start_line === void 0 || args.start_line === null || args.start_line === "") {
|
|
11412
|
+
return { summary: "Edit failed: end_line needs a start_line" };
|
|
11413
|
+
}
|
|
11414
|
+
return resolveRange(
|
|
11415
|
+
lines,
|
|
11416
|
+
total,
|
|
11417
|
+
args.start_line,
|
|
11418
|
+
args.end_line ?? args.start_line,
|
|
11419
|
+
newStr,
|
|
11420
|
+
display
|
|
11421
|
+
);
|
|
11422
|
+
}
|
|
11423
|
+
var POSITION_EXCERPT_MAX_LINES = 40;
|
|
11424
|
+
var ANCHOR_HITS_SHOWN = 8;
|
|
11425
|
+
var REMOVED_SHOWN_MAX_LINES = 80;
|
|
11426
|
+
function hashedWindow(lines, from, to) {
|
|
11427
|
+
return lines.slice(from, to).map((l, i) => gutterLine(from + i + 1, l, true)).join("\n");
|
|
11428
|
+
}
|
|
11429
|
+
function offsetOfLine(lines, index) {
|
|
11430
|
+
let n = 0;
|
|
11431
|
+
for (let k = 0; k < index; k++) n += lines[k].length + 1;
|
|
11432
|
+
return n;
|
|
11433
|
+
}
|
|
11434
|
+
function stripOneTrailingNewline(s) {
|
|
11435
|
+
return s.endsWith("\n") ? s.slice(0, -1) : s;
|
|
11436
|
+
}
|
|
11437
|
+
function resolveInsert(lines, total, kind, anchor, newStr, display) {
|
|
11438
|
+
const needle = anchor.trim();
|
|
11439
|
+
if (needle === "" || needle.includes("\n")) {
|
|
11440
|
+
return { summary: `Edit failed: ${kind} must be text from a single line of ${display}` };
|
|
11441
|
+
}
|
|
11442
|
+
if (newStr === "") return { summary: "Edit failed: new_string is empty; nothing to insert" };
|
|
11443
|
+
const hits = [];
|
|
11444
|
+
for (let i2 = 0; i2 < total; i2++) if (lines[i2].includes(needle)) hits.push(i2);
|
|
11445
|
+
if (hits.length === 0) {
|
|
11446
|
+
return {
|
|
11447
|
+
summary: `Edit failed: no line of ${display} contains "${needle}"; nothing was written. Use text copied from a line of the file`
|
|
11448
|
+
};
|
|
11449
|
+
}
|
|
11450
|
+
if (hits.length > 1) {
|
|
11451
|
+
return {
|
|
11452
|
+
summary: `Edit failed: "${needle}" is on ${hits.length} lines of ${display} (lines ${hits.map((h) => h + 1).join(", ")}); nothing was written. Use text only one line contains, or start_line/end_line`,
|
|
11453
|
+
payload: hits.slice(0, ANCHOR_HITS_SHOWN).map((h) => gutterLine(h + 1, lines[h], true)).join("\n")
|
|
11454
|
+
};
|
|
11455
|
+
}
|
|
11456
|
+
const i = hits[0];
|
|
11457
|
+
const body = stripOneTrailingNewline(newStr);
|
|
11458
|
+
const after = kind === "insert_after";
|
|
11459
|
+
return {
|
|
11460
|
+
start: offsetOfLine(lines, i),
|
|
11461
|
+
len: lines[i].length,
|
|
11462
|
+
newStr: after ? `${lines[i]}
|
|
11463
|
+
${body}` : `${body}
|
|
11464
|
+
${lines[i]}`,
|
|
11465
|
+
line: after ? i + 2 : i + 1
|
|
11466
|
+
};
|
|
11467
|
+
}
|
|
11468
|
+
function resolveRange(lines, total, startRaw, endRaw, newStr, display) {
|
|
11469
|
+
const s = parseLineRef(startRaw);
|
|
11470
|
+
const e = parseLineRef(endRaw);
|
|
11471
|
+
if (!s || !e) {
|
|
11472
|
+
return {
|
|
11473
|
+
summary: 'Edit failed: start_line and end_line are "N:hash" as shown in the read gutter (e.g. "120:a3f")'
|
|
11474
|
+
};
|
|
11475
|
+
}
|
|
11476
|
+
if (s.line < 1 || e.line > total || s.line > e.line) {
|
|
11477
|
+
return {
|
|
11478
|
+
summary: `Edit failed: lines ${s.line}-${e.line} are not a range in ${display}, which has ${total} lines`
|
|
11479
|
+
};
|
|
11480
|
+
}
|
|
11481
|
+
const window = () => {
|
|
11482
|
+
const from = Math.max(0, s.line - 2);
|
|
11483
|
+
return hashedWindow(
|
|
11484
|
+
lines,
|
|
11485
|
+
from,
|
|
11486
|
+
Math.min(total, e.line + 1, from + POSITION_EXCERPT_MAX_LINES)
|
|
11487
|
+
);
|
|
11488
|
+
};
|
|
11489
|
+
if (!s.hash || !e.hash) {
|
|
11490
|
+
return {
|
|
11491
|
+
summary: `Edit failed: start_line and end_line need the hash from the read gutter ("${s.line}:${lineHash(lines[s.line - 1])}"); nothing was written. The current lines of ${display} are below`,
|
|
11492
|
+
payload: window()
|
|
11493
|
+
};
|
|
11494
|
+
}
|
|
11495
|
+
const staleAt = lineHash(lines[s.line - 1]) !== s.hash ? s.line : lineHash(lines[e.line - 1]) !== e.hash ? e.line : void 0;
|
|
11496
|
+
if (staleAt !== void 0) {
|
|
11497
|
+
const moved = relocateRange(lines, total, s.hash, e.hash, e.line - s.line);
|
|
11498
|
+
return {
|
|
11499
|
+
summary: `Edit failed: line ${staleAt} of ${display} is not the line you read (its hash changed); nothing was written.` + (moved ? ` The lines you read appear to be at ${moved.from}-${moved.to} now.` : "") + " The current lines are below \u2014 re-issue with their N:hash",
|
|
11500
|
+
payload: window()
|
|
11501
|
+
};
|
|
11502
|
+
}
|
|
11503
|
+
const body = stripOneTrailingNewline(newStr);
|
|
11504
|
+
const old = lines.slice(s.line - 1, e.line).join("\n");
|
|
11505
|
+
if (body === old) {
|
|
11506
|
+
return { summary: "Edit failed: new_string is identical to the lines it replaces" };
|
|
11507
|
+
}
|
|
11508
|
+
const removedLines = lines.slice(s.line - 1, e.line);
|
|
11509
|
+
const shown = removedLines.slice(0, REMOVED_SHOWN_MAX_LINES).map((l, k) => gutterLine(s.line + k, l, false));
|
|
11510
|
+
const more = removedLines.length - shown.length;
|
|
11511
|
+
const removed = `(reika: lines ${s.line}-${e.line} of ${display} were replaced; they were:)
|
|
11512
|
+
` + shown.join("\n") + (more > 0 ? `
|
|
11513
|
+
\u2026(${more} more removed line${more === 1 ? "" : "s"})` : "");
|
|
11514
|
+
if (body !== "") {
|
|
11515
|
+
return {
|
|
11516
|
+
start: offsetOfLine(lines, s.line - 1),
|
|
11517
|
+
len: old.length,
|
|
11518
|
+
newStr: body,
|
|
11519
|
+
line: s.line,
|
|
11520
|
+
removed
|
|
11521
|
+
};
|
|
11522
|
+
}
|
|
11523
|
+
if (e.line < total) {
|
|
11524
|
+
const span = lines.slice(s.line - 1, e.line + 1).join("\n");
|
|
11525
|
+
return {
|
|
11526
|
+
start: offsetOfLine(lines, s.line - 1),
|
|
11527
|
+
len: span.length,
|
|
11528
|
+
newStr: lines[e.line],
|
|
11529
|
+
line: s.line,
|
|
11530
|
+
removed
|
|
11531
|
+
};
|
|
11532
|
+
}
|
|
11533
|
+
if (s.line > 1) {
|
|
11534
|
+
const span = lines.slice(s.line - 2, e.line).join("\n");
|
|
11535
|
+
return {
|
|
11536
|
+
start: offsetOfLine(lines, s.line - 2),
|
|
11537
|
+
len: span.length,
|
|
11538
|
+
newStr: lines[s.line - 2],
|
|
11539
|
+
line: s.line - 1,
|
|
11540
|
+
removed
|
|
11541
|
+
};
|
|
11542
|
+
}
|
|
11543
|
+
return { start: 0, len: old.length, newStr: "", line: 1, removed };
|
|
11544
|
+
}
|
|
11545
|
+
function relocateRange(lines, total, startHash, endHash, span) {
|
|
11546
|
+
let found = null;
|
|
11547
|
+
for (let i = 0; i + span < total; i++) {
|
|
11548
|
+
if (lineHash(lines[i]) !== startHash || lineHash(lines[i + span]) !== endHash) continue;
|
|
11549
|
+
if (found !== null) return null;
|
|
11550
|
+
found = i;
|
|
11551
|
+
}
|
|
11552
|
+
return found === null ? null : { from: found + 1, to: found + span + 1 };
|
|
11553
|
+
}
|
|
11221
11554
|
function intentDiff(oldStr, newStr) {
|
|
11222
11555
|
const minus = oldStr.split("\n").map((l) => `- ${l}`);
|
|
11223
11556
|
const plus = newStr.split("\n").map((l) => `+ ${l}`);
|
|
@@ -11230,7 +11563,7 @@ function refreshedFile(rel, content) {
|
|
|
11230
11563
|
const lines = content.split("\n");
|
|
11231
11564
|
const total = lines.length > 1 && lines[lines.length - 1] === "" ? lines.length - 1 : lines.length;
|
|
11232
11565
|
if (total > REFRESH_MAX_LINES) return void 0;
|
|
11233
|
-
const numbered = lines.slice(0, total).map((l, i) =>
|
|
11566
|
+
const numbered = lines.slice(0, total).map((l, i) => gutterLine(i + 1, l)).join("\n");
|
|
11234
11567
|
return `(reika: ${rel} after your edit \u2014 current contents below. Build any further edits to this file from this exact text; you do not need to re-read it.)
|
|
11235
11568
|
${numbered}`;
|
|
11236
11569
|
}
|
|
@@ -11279,7 +11612,7 @@ function fuzzyLineMatch(text, oldStr, newStr) {
|
|
|
11279
11612
|
const closest = locateClosest(fileLines, oldTrim);
|
|
11280
11613
|
return {
|
|
11281
11614
|
status: "none",
|
|
11282
|
-
hint: formatNotFoundHint(closest, oldLines, oldTrim),
|
|
11615
|
+
hint: formatNotFoundHint(closest, oldLines, oldTrim, fileLines),
|
|
11283
11616
|
failure: closestToFailure(closest, fileLines, oldTrim)
|
|
11284
11617
|
};
|
|
11285
11618
|
}
|
|
@@ -11360,11 +11693,24 @@ function locateByTokenOverlap(fileLines, oldTrim) {
|
|
|
11360
11693
|
}
|
|
11361
11694
|
return best && best.hits >= need ? best.start : null;
|
|
11362
11695
|
}
|
|
11363
|
-
function formatNotFoundHint(closest, oldLines, oldTrim) {
|
|
11696
|
+
function formatNotFoundHint(closest, oldLines, oldTrim, fileLines) {
|
|
11364
11697
|
const i0 = oldTrim.findIndex((t) => t !== "");
|
|
11365
11698
|
if (i0 === -1) return "";
|
|
11366
11699
|
if (!closest.found) return " No line matches it even ignoring whitespace.";
|
|
11367
|
-
return ` Closest match starts at line ${closest.start + 1} ("${oldLines[i0].trim()}") but line ${closest.divergentLine} differs: expected "${closest.expected}", file has "${closest.actual}". Re-read there and copy verbatim
|
|
11700
|
+
return ` Closest match starts at line ${closest.start + 1} ("${oldLines[i0].trim()}") but line ${closest.divergentLine} differs: expected "${closest.expected}", file has "${closest.actual}". Re-read there and copy verbatim.` + rangePointer(fileLines, [closest.start], oldTrim.length);
|
|
11701
|
+
}
|
|
11702
|
+
var RANGE_POINTER_MAX = 4;
|
|
11703
|
+
function rangePointer(fileLines, starts, count) {
|
|
11704
|
+
if (!positionalEditsEnabled()) return "";
|
|
11705
|
+
const total = fileLines.length > 1 && fileLines[fileLines.length - 1] === "" ? fileLines.length - 1 : fileLines.length;
|
|
11706
|
+
const ranges = starts.slice(0, RANGE_POINTER_MAX).map((s) => [s, Math.min(total, s + count) - 1]).filter(([from, to]) => from >= 0 && to >= from).map(
|
|
11707
|
+
([from, to]) => `start_line "${from + 1}:${lineHash(fileLines[from])}", end_line "${to + 1}:${lineHash(fileLines[to])}"`
|
|
11708
|
+
);
|
|
11709
|
+
if (ranges.length === 0) return "";
|
|
11710
|
+
return starts.length > 1 ? ` Or replace one of them as whole lines by position: ${ranges.join("; or ")}.` : ` If those are the lines you meant, replace them as whole lines by position instead: ${ranges[0]}.`;
|
|
11711
|
+
}
|
|
11712
|
+
function blockLineCount(oldStr) {
|
|
11713
|
+
return (oldStr.endsWith("\n") ? oldStr.slice(0, -1) : oldStr).split("\n").length;
|
|
11368
11714
|
}
|
|
11369
11715
|
function closestToFailure(closest, fileLines, oldTrim) {
|
|
11370
11716
|
if (!closest.found) {
|
|
@@ -11392,7 +11738,7 @@ function blockExcerpt(fileLines, blockStart, blockLen, divergentLine) {
|
|
|
11392
11738
|
from = Math.max(0, divergentLine - 1 - Math.floor(EXCERPT_MAX_LINES / 2));
|
|
11393
11739
|
to = Math.min(fileLines.length, from + EXCERPT_MAX_LINES);
|
|
11394
11740
|
}
|
|
11395
|
-
return fileLines.slice(from, to).map((l, idx) =>
|
|
11741
|
+
return fileLines.slice(from, to).map((l, idx) => gutterLine(from + idx + 1, l)).join("\n");
|
|
11396
11742
|
}
|
|
11397
11743
|
|
|
11398
11744
|
// src/tools/write.ts
|
|
@@ -15866,7 +16212,7 @@ function defaultTools(config, opts = {}) {
|
|
|
15866
16212
|
listTool,
|
|
15867
16213
|
grepTool,
|
|
15868
16214
|
globTool,
|
|
15869
|
-
|
|
16215
|
+
editToolForSession(),
|
|
15870
16216
|
writeTool,
|
|
15871
16217
|
bashTool,
|
|
15872
16218
|
subagentTool,
|
|
@@ -15875,6 +16221,9 @@ function defaultTools(config, opts = {}) {
|
|
|
15875
16221
|
if (askEnabled()) tools.push(askUserTool);
|
|
15876
16222
|
return tools;
|
|
15877
16223
|
}
|
|
16224
|
+
function editToolForSession() {
|
|
16225
|
+
return positionalEditsEnabled() ? positionalEditTool : editTool;
|
|
16226
|
+
}
|
|
15878
16227
|
function webTools(config, opts) {
|
|
15879
16228
|
if (opts.offline) return [];
|
|
15880
16229
|
const tools = [fetchUrlTool];
|
|
@@ -15898,7 +16247,7 @@ function minimalTools() {
|
|
|
15898
16247
|
return tools;
|
|
15899
16248
|
}
|
|
15900
16249
|
function grindTools(config, opts = {}) {
|
|
15901
|
-
const tools = [readTool,
|
|
16250
|
+
const tools = [readTool, editToolForSession(), grindBashTool];
|
|
15902
16251
|
if (askEnabled()) tools.push(askUserTool);
|
|
15903
16252
|
tools.push(...webTools(config, opts));
|
|
15904
16253
|
return tools;
|
|
@@ -16908,7 +17257,7 @@ function priorCopyState(prior, history, prefixStable) {
|
|
|
16908
17257
|
}
|
|
16909
17258
|
|
|
16910
17259
|
// src/agent/bashread.ts
|
|
16911
|
-
import { createHash as
|
|
17260
|
+
import { createHash as createHash5 } from "node:crypto";
|
|
16912
17261
|
import { readFile as readFile12, realpath as realpath2, stat as stat6 } from "node:fs/promises";
|
|
16913
17262
|
import { isAbsolute as isAbsolute6, relative as relative13 } from "node:path";
|
|
16914
17263
|
var CAT_FLAGS = /^-[nbsuvetAE]+$/;
|
|
@@ -17030,7 +17379,7 @@ async function traceBashRead(command, cwd) {
|
|
|
17030
17379
|
const info = await stat6(full);
|
|
17031
17380
|
if (!info.isFile() || info.size > MAX_TRACED_BYTES) return void 0;
|
|
17032
17381
|
const text = await readFile12(full, "utf8");
|
|
17033
|
-
const hash =
|
|
17382
|
+
const hash = createHash5("sha1").update(text).digest("hex");
|
|
17034
17383
|
const path = await traceKey(cwd, full);
|
|
17035
17384
|
const r = parsed.range;
|
|
17036
17385
|
if ("last" in r) {
|
|
@@ -17926,6 +18275,38 @@ function shouldSuppressGrounding(missing, refs) {
|
|
|
17926
18275
|
return missingCount >= SUPPRESS_MIN_MISSING && missingCount / total >= SUPPRESS_FRACTION;
|
|
17927
18276
|
}
|
|
17928
18277
|
|
|
18278
|
+
// src/agent/triggeredplan.ts
|
|
18279
|
+
function triggeredPlanEnabled() {
|
|
18280
|
+
return process.env.REIKA_TRIGGERED_PLAN === "1";
|
|
18281
|
+
}
|
|
18282
|
+
var TRIGGER_MIN_FILES = 6;
|
|
18283
|
+
var TRIGGER_MIN_FILL = 0.5;
|
|
18284
|
+
function triggeredPlanReason(o) {
|
|
18285
|
+
if (o.round < 1 || o.lastRound || o.editingStarted || o.hasPlan) return null;
|
|
18286
|
+
if (o.filesRead >= TRIGGER_MIN_FILES && (o.fill ?? 0) >= TRIGGER_MIN_FILL) return "files";
|
|
18287
|
+
if (o.shrinksThisTurn > 0) return "trim";
|
|
18288
|
+
return null;
|
|
18289
|
+
}
|
|
18290
|
+
function buildTriggeredPlanDirective(reason, filesRead) {
|
|
18291
|
+
const why = reason === "files" ? `You have read ${filesRead} files in this task and changed none yet.` : "The context is filling and older tool output is being dropped.";
|
|
18292
|
+
return [
|
|
18293
|
+
"--- plan request (reika, auto-generated \u2014 not user input) ---",
|
|
18294
|
+
why,
|
|
18295
|
+
"Before going further, write the plan for the rest of this task as a numbered list: one step per",
|
|
18296
|
+
"file or change, each naming the file it touches in backticks, and the command that checks it if",
|
|
18297
|
+
"there is one. Do not call any tool in this reply. Reika keeps the list as your checklist, and you",
|
|
18298
|
+
"continue from step 1 on the next round.",
|
|
18299
|
+
"If the task needs no change to any file (a question to answer), reply with only: no plan"
|
|
18300
|
+
].join("\n");
|
|
18301
|
+
}
|
|
18302
|
+
var TRIGGERED_PLAN_CONTINUE = "(reika: the plan above is now tracked as your checklist. Continue with step 1.)";
|
|
18303
|
+
function triggeredPlanFrom(reply) {
|
|
18304
|
+
const text = (reply.content?.trim() || reply.reasoning?.trim()) ?? "";
|
|
18305
|
+
const steps = parsePlanSteps(text);
|
|
18306
|
+
if (steps.length < 2 || !steps.some((s) => s.paths.length > 0)) return null;
|
|
18307
|
+
return { text, steps };
|
|
18308
|
+
}
|
|
18309
|
+
|
|
17929
18310
|
// src/agent/readfirst.ts
|
|
17930
18311
|
import { readFile as readFile14 } from "node:fs/promises";
|
|
17931
18312
|
import { relative as relative15, resolve as resolve9 } from "node:path";
|
|
@@ -18004,7 +18385,7 @@ var MIN_PROBE_CHARS = 12;
|
|
|
18004
18385
|
function probeLine(excerpt) {
|
|
18005
18386
|
let best;
|
|
18006
18387
|
for (const raw of excerpt.split("\n")) {
|
|
18007
|
-
const line = raw.replace(
|
|
18388
|
+
const line = raw.replace(GUTTER_PREFIX_RE, "").trim();
|
|
18008
18389
|
if (line.length >= MIN_PROBE_CHARS && (best === void 0 || line.length > best.length)) {
|
|
18009
18390
|
best = line;
|
|
18010
18391
|
}
|
|
@@ -18044,6 +18425,13 @@ async function oldStringProvesBytes(cwd, path, oldStr, newStr) {
|
|
|
18044
18425
|
return false;
|
|
18045
18426
|
}
|
|
18046
18427
|
}
|
|
18428
|
+
async function positionProvesBytes(cwd, path, args) {
|
|
18429
|
+
try {
|
|
18430
|
+
return positionLands(await readFile14(resolveUserPath(cwd, path), "utf8"), args);
|
|
18431
|
+
} catch {
|
|
18432
|
+
return false;
|
|
18433
|
+
}
|
|
18434
|
+
}
|
|
18047
18435
|
function buildReadFirstDirective(path) {
|
|
18048
18436
|
return `(reika: this edit was NOT applied. The current contents of ${path} are not in your context \u2014 either you have not read it, or the read has since aged out \u2014 so your old_string is a guess and will likely not match the file. Read ` + path + " first, then re-issue the edit with old_string copied character-for-character from the read output \u2014 only the text after the `NNNNN\u2502` gutter, indentation included. If you re-issue the edit without reading, it will be applied as-is.)";
|
|
18049
18437
|
}
|
|
@@ -18193,7 +18581,7 @@ function planPressureLine(pressure, basis) {
|
|
|
18193
18581
|
|
|
18194
18582
|
// src/check/typecheck.ts
|
|
18195
18583
|
import { spawn as spawn5 } from "node:child_process";
|
|
18196
|
-
import { createHash as
|
|
18584
|
+
import { createHash as createHash6 } from "node:crypto";
|
|
18197
18585
|
import { stat as stat8 } from "node:fs/promises";
|
|
18198
18586
|
import { tmpdir as tmpdir2 } from "node:os";
|
|
18199
18587
|
import { dirname as dirname9, isAbsolute as isAbsolute7, join as join17, relative as relative16, resolve as resolve10 } from "node:path";
|
|
@@ -18301,7 +18689,7 @@ async function resolveTscBin(cwd) {
|
|
|
18301
18689
|
return await stat8(bin).catch(() => null) ? bin : null;
|
|
18302
18690
|
}
|
|
18303
18691
|
function defaultBuildInfoFile(cwd) {
|
|
18304
|
-
const h =
|
|
18692
|
+
const h = createHash6("sha1").update(cwd).digest("hex").slice(0, 16);
|
|
18305
18693
|
return join17(tmpdir2(), `reika-tsc-${h}.tsbuildinfo`);
|
|
18306
18694
|
}
|
|
18307
18695
|
async function runTypecheck(cwd, opts = {}) {
|
|
@@ -18701,7 +19089,10 @@ function promptGates(tools, sandbox, unattended) {
|
|
|
18701
19089
|
canSubagent: has("subagent"),
|
|
18702
19090
|
sandbox: sandbox && has("bash") && sandboxExecAvailable(),
|
|
18703
19091
|
canFetch: has("fetch_url"),
|
|
18704
|
-
canSearch: has("search")
|
|
19092
|
+
canSearch: has("search"),
|
|
19093
|
+
canEditByPosition: tools.some(
|
|
19094
|
+
(t) => t.name === "edit" && "insert_after" in (t.parameters.properties ?? {})
|
|
19095
|
+
)
|
|
18705
19096
|
};
|
|
18706
19097
|
}
|
|
18707
19098
|
function buildRoundZeroPrefix(opts) {
|
|
@@ -18762,6 +19153,10 @@ function withdrawalRemedy(toolNames) {
|
|
|
18762
19153
|
}
|
|
18763
19154
|
return "Answer from what you already have";
|
|
18764
19155
|
}
|
|
19156
|
+
function positionalPauseHint(toolNames) {
|
|
19157
|
+
if (!toolNames.has("edit") || !positionalEditsEnabled()) return "";
|
|
19158
|
+
return "If you no longer have the exact text, edit can insert after a line containing a short string (insert_after), or replace start_line..end_line using the N:hash from an earlier read's gutter. A wrong anchor or a stale hash writes nothing and the reply says what to fix, so make the edit directly rather than checking the file first.";
|
|
19159
|
+
}
|
|
18765
19160
|
function withdrawalReturn(toolNames) {
|
|
18766
19161
|
if (toolNames.has("edit") || toolNames.has("write")) {
|
|
18767
19162
|
return "The pause is temporary: reading comes back once an edit to an existing file lands (a new file does not count), or after a few rounds.";
|
|
@@ -18777,6 +19172,7 @@ function withdrawnLedgerLines(toolNames) {
|
|
|
18777
19172
|
"Reading and searching are now PAUSED. Make the edit the task requires with the edit/write",
|
|
18778
19173
|
"tools, state specifically what is still blocking you, or \u2014 if the change is already complete \u2014",
|
|
18779
19174
|
"say so and stop.",
|
|
19175
|
+
...positionalPauseHint(toolNames) ? [positionalPauseHint(toolNames)] : [],
|
|
18780
19176
|
withdrawalReturn(toolNames)
|
|
18781
19177
|
];
|
|
18782
19178
|
}
|
|
@@ -18795,7 +19191,7 @@ function withdrawnLedgerLines(toolNames) {
|
|
|
18795
19191
|
];
|
|
18796
19192
|
}
|
|
18797
19193
|
function buildWithdrawalDirective(toolNames) {
|
|
18798
|
-
return `(reika: this is deliberate, not a fault. ${withdrawnToolsPhrase(toolNames)} are paused because the work has repeated without making progress. Sending this call again now gets this same reply, so do not retry it. ${withdrawalRemedy(toolNames)}, state what is specifically blocking you, or \u2014 if the change is already complete \u2014 say so and stop.
|
|
19194
|
+
return `(reika: this is deliberate, not a fault. ${withdrawnToolsPhrase(toolNames)} are paused because the work has repeated without making progress. Sending this call again now gets this same reply, so do not retry it. ${withdrawalRemedy(toolNames)}, state what is specifically blocking you, or \u2014 if the change is already complete \u2014 say so and stop. ` + (positionalPauseHint(toolNames) ? `${positionalPauseHint(toolNames)} ` : "") + `${withdrawalReturn(toolNames)})`;
|
|
18799
19195
|
}
|
|
18800
19196
|
function shouldWithdrawInspection(opts) {
|
|
18801
19197
|
if (opts.loopActiveRounds < LOOP_WITHDRAW_AFTER) return false;
|
|
@@ -19082,7 +19478,10 @@ ${SUBAGENT_REPORT_FRAME}` : promptForMode;
|
|
|
19082
19478
|
debugLog(`[reika:debug] plan-handoff folded=${folded} reason=${reason}
|
|
19083
19479
|
`);
|
|
19084
19480
|
}
|
|
19085
|
-
|
|
19481
|
+
let planSteps = opts.promptMode === "agent" ? seedPlanProgress(opts.history) : null;
|
|
19482
|
+
const filesReadBeforeEdit = /* @__PURE__ */ new Set();
|
|
19483
|
+
const shrinksAtTurnStart = shrink.sheds + shrink.folds;
|
|
19484
|
+
let triggeredPlanTried = false;
|
|
19086
19485
|
if (planSteps) {
|
|
19087
19486
|
opts.onPlanProgress?.(planSteps);
|
|
19088
19487
|
debugLog(
|
|
@@ -19329,6 +19728,97 @@ ${SUBAGENT_REPORT_FRAME}` : promptForMode;
|
|
|
19329
19728
|
return;
|
|
19330
19729
|
}
|
|
19331
19730
|
}
|
|
19731
|
+
if (triggeredPlanEnabled() && (opts.promptMode ?? "agent") === "agent" && // Minimal and grind run a fixed procedure of their own; a subagent ends in a report.
|
|
19732
|
+
!opts.minimalPrompt && !opts.grindPrompt && !opts.reportAtCap && !triggeredPlanTried && !opts.signal?.aborted) {
|
|
19733
|
+
const reason = triggeredPlanReason({
|
|
19734
|
+
round: i,
|
|
19735
|
+
lastRound: i === opts.config.maxTurns - 1,
|
|
19736
|
+
editingStarted,
|
|
19737
|
+
hasPlan: planSteps !== null,
|
|
19738
|
+
filesRead: filesReadBeforeEdit.size,
|
|
19739
|
+
shrinksThisTurn: shrink.sheds + shrink.folds - shrinksAtTurnStart,
|
|
19740
|
+
fill: window ? rawEstimate() * Math.max(calibration, COMPACTION_CALIBRATION_FLOOR) / compactThreshold(window, minGen()) : void 0
|
|
19741
|
+
});
|
|
19742
|
+
if (reason) {
|
|
19743
|
+
triggeredPlanTried = true;
|
|
19744
|
+
const directive = buildTriggeredPlanDirective(reason, filesReadBeforeEdit.size);
|
|
19745
|
+
opts.onMessage({
|
|
19746
|
+
role: "system",
|
|
19747
|
+
tone: "info",
|
|
19748
|
+
emphasis: "line",
|
|
19749
|
+
content: reason === "files" ? `${filesReadBeforeEdit.size} files read with no change yet \u2014 asking the model for a plan of the remaining steps.` : "Context is being trimmed with no change yet \u2014 asking the model for a plan of the remaining steps."
|
|
19750
|
+
});
|
|
19751
|
+
opts.onPhase?.("thinking");
|
|
19752
|
+
const planTools2 = lastSentTools ?? opts.tools;
|
|
19753
|
+
try {
|
|
19754
|
+
const reply = await callModel({
|
|
19755
|
+
system: prefixStable ? baseSystem : baseSystem + "\n\n" + directive,
|
|
19756
|
+
history: opts.history,
|
|
19757
|
+
// Same tools as the last request, calls forbidden by tool_choice (#426).
|
|
19758
|
+
tools: planTools2,
|
|
19759
|
+
toolChoice: "none",
|
|
19760
|
+
config: withGenReserve(opts.config, genReserve),
|
|
19761
|
+
onContentDelta: opts.onContentDelta,
|
|
19762
|
+
onReasoningDelta: opts.onReasoningDelta,
|
|
19763
|
+
onPromptProgress: opts.onPromptProgress,
|
|
19764
|
+
signal: opts.signal,
|
|
19765
|
+
calibration,
|
|
19766
|
+
maxTokens: window ? computeMaxTokens({
|
|
19767
|
+
contextWindow: window,
|
|
19768
|
+
promptTokens: Math.round(rawEstimate() * calibration),
|
|
19769
|
+
userMaxTokens: opts.config.maxTokens,
|
|
19770
|
+
modelMaxOutput: opts.config.maxOutputTokens
|
|
19771
|
+
}) : opts.config.maxTokens,
|
|
19772
|
+
prefixStable,
|
|
19773
|
+
stampRenders: false,
|
|
19774
|
+
nativeImages: opts.nativeImages,
|
|
19775
|
+
trailingNote: prefixStable ? directive : void 0,
|
|
19776
|
+
// Its own prefix-cache line, as the compaction note's round has (#426), so the next
|
|
19777
|
+
// round's line compares against the request the engine last saw.
|
|
19778
|
+
onRequest: debugEnabled() ? (msgs) => {
|
|
19779
|
+
const d = prefixTrace.record(msgs, {
|
|
19780
|
+
trailingNote: prefixStable,
|
|
19781
|
+
tools: toolsToChatTools(planTools2)
|
|
19782
|
+
});
|
|
19783
|
+
const pct = d.totalChars > 0 ? Math.round(d.stableChars / d.totalChars * 100) : 100;
|
|
19784
|
+
debugLog(
|
|
19785
|
+
`[reika:debug] prefix-cache round=${i} phase=plan cause=${d.cause} stable=${d.stableChars}/${d.totalChars}c (${pct}%)
|
|
19786
|
+
`
|
|
19787
|
+
);
|
|
19788
|
+
} : void 0
|
|
19789
|
+
});
|
|
19790
|
+
if (opts.signal?.aborted) {
|
|
19791
|
+
commitAborted(opts, "", void 0, turnStart, fetchedUrls);
|
|
19792
|
+
return;
|
|
19793
|
+
}
|
|
19794
|
+
const plan = triggeredPlanFrom(reply);
|
|
19795
|
+
debugLog(
|
|
19796
|
+
`[reika:debug] round=${i} triggered-plan reason=${reason} files=${filesReadBeforeEdit.size} ${plan ? `steps=${plan.steps.length}` : "rejected"} content=${reply.content?.length ?? 0}c reasoning=${reply.reasoning?.length ?? 0}c
|
|
19797
|
+
`
|
|
19798
|
+
);
|
|
19799
|
+
if (plan) {
|
|
19800
|
+
const planMsg = {
|
|
19801
|
+
role: "assistant",
|
|
19802
|
+
content: plan.text,
|
|
19803
|
+
reasoning: reply.reasoning,
|
|
19804
|
+
planFinal: true
|
|
19805
|
+
};
|
|
19806
|
+
opts.history.push(planMsg);
|
|
19807
|
+
opts.onMessage(planMsg);
|
|
19808
|
+
opts.history.push({ role: "user", content: TRIGGERED_PLAN_CONTINUE, harness: true });
|
|
19809
|
+
planSteps = seedPlanProgress(opts.history);
|
|
19810
|
+
if (planSteps) opts.onPlanProgress?.(planSteps);
|
|
19811
|
+
}
|
|
19812
|
+
} catch (err) {
|
|
19813
|
+
if (opts.signal?.aborted) {
|
|
19814
|
+
commitAborted(opts, "", void 0, turnStart, fetchedUrls);
|
|
19815
|
+
return;
|
|
19816
|
+
}
|
|
19817
|
+
debugLog(`[reika:debug] round=${i} triggered-plan failed err=${String(err)}
|
|
19818
|
+
`);
|
|
19819
|
+
}
|
|
19820
|
+
}
|
|
19821
|
+
}
|
|
19332
19822
|
const suffixParts = [];
|
|
19333
19823
|
const droppedLedger = droppedPayloadLedgerFor(opts.history, prefixStable);
|
|
19334
19824
|
if (droppedLedger) suffixParts.push(droppedLedger);
|
|
@@ -20181,7 +20671,7 @@ ${response.content}`,
|
|
|
20181
20671
|
});
|
|
20182
20672
|
}
|
|
20183
20673
|
if (isFinal) {
|
|
20184
|
-
if (!assistantContent?.trim() && response.finishReason !== "length" && !opts.signal?.aborted) {
|
|
20674
|
+
if (!assistantContent?.trim() && response.finishReason !== "length" && !subagentForceReport && !opts.signal?.aborted) {
|
|
20185
20675
|
const retry = emptyReplyRetries < MAX_EMPTY_REPLY_RETRIES;
|
|
20186
20676
|
debugLog(`[reika:debug] round=${i} empty-reply retry=${retry}
|
|
20187
20677
|
`);
|
|
@@ -20196,7 +20686,12 @@ ${response.content}`,
|
|
|
20196
20686
|
continue;
|
|
20197
20687
|
}
|
|
20198
20688
|
}
|
|
20199
|
-
if (
|
|
20689
|
+
if (subagentForceReport) {
|
|
20690
|
+
const addendum = (await reportTypecheckAtStop()).trim();
|
|
20691
|
+
if (addendum) assistantMsg.content = `${assistantMsg.content ?? ""}
|
|
20692
|
+
|
|
20693
|
+
${addendum}`.trim();
|
|
20694
|
+
} else if (typecheckEnabled && typecheckBaseline !== null && !opts.signal?.aborted) {
|
|
20200
20695
|
const final = await typecheck();
|
|
20201
20696
|
const decision = decideTypecheckGate({
|
|
20202
20697
|
baseline: typecheckBaseline,
|
|
@@ -20224,7 +20719,7 @@ ${response.content}`,
|
|
|
20224
20719
|
});
|
|
20225
20720
|
}
|
|
20226
20721
|
}
|
|
20227
|
-
if (PLAN_ALIGN && planSteps && editingStarted && opts.promptMode === "agent" && !opts.signal?.aborted) {
|
|
20722
|
+
if (PLAN_ALIGN && planSteps && editingStarted && !subagentForceReport && opts.promptMode === "agent" && !opts.signal?.aborted) {
|
|
20228
20723
|
const gate = decidePlanGate({
|
|
20229
20724
|
steps: planSteps,
|
|
20230
20725
|
gateRounds: planGateRounds,
|
|
@@ -20241,14 +20736,10 @@ ${response.content}`,
|
|
|
20241
20736
|
continue;
|
|
20242
20737
|
}
|
|
20243
20738
|
if (gate.action === "waive") {
|
|
20244
|
-
|
|
20739
|
+
waiveUnchecked(planSteps);
|
|
20740
|
+
recordPlanSettled(opts.history, planSteps);
|
|
20245
20741
|
opts.onPlanProgress?.(planSteps);
|
|
20246
|
-
opts.onMessage({
|
|
20247
|
-
role: "system",
|
|
20248
|
-
tone: "warn",
|
|
20249
|
-
content: gate.userNotice ?? "",
|
|
20250
|
-
planWaived: waived
|
|
20251
|
-
});
|
|
20742
|
+
opts.onMessage({ role: "system", tone: "warn", content: gate.userNotice ?? "" });
|
|
20252
20743
|
}
|
|
20253
20744
|
}
|
|
20254
20745
|
if (opts.promptMode === "plan" && opts.allowRefine !== false && parsePlanSteps(assistantContent ?? "").length > 0) {
|
|
@@ -20287,12 +20778,13 @@ ${response.content}`,
|
|
|
20287
20778
|
const refused = withdrawInspection && (INSPECTION_TOOLS.has(call.name) || refusedBashGrep);
|
|
20288
20779
|
const heldForSubagent = subagentInRound && !refused && call.name !== "subagent" && (INSPECTION_TOOLS.has(call.name) || refusedBashGrep);
|
|
20289
20780
|
const blindEdit = READ_FIRST && !withdrawInspection && call.name === "edit" && tool !== void 0 && typeof call.args.path === "string" && readFirst.wouldBounce(call.args.path, opts.history, prefixStable);
|
|
20290
|
-
const
|
|
20781
|
+
const positional = hasPositionArgs(call.args);
|
|
20782
|
+
const provenEdit = blindEdit && (positional ? await positionProvesBytes(opts.bundle.cwd, String(call.args.path), call.args) : READ_FIRST_EXACT && await oldStringProvesBytes(
|
|
20291
20783
|
opts.bundle.cwd,
|
|
20292
20784
|
String(call.args.path),
|
|
20293
20785
|
String(call.args.old_string ?? ""),
|
|
20294
20786
|
String(call.args.new_string ?? "")
|
|
20295
|
-
);
|
|
20787
|
+
));
|
|
20296
20788
|
if (provenEdit) debugLog(`[reika:debug] round=${i} read-first proven ${call.args.path}
|
|
20297
20789
|
`);
|
|
20298
20790
|
const bouncedBlindEdit = blindEdit && !provenEdit && readFirst.shouldBounce(String(call.args.path), opts.history, prefixStable);
|
|
@@ -20340,7 +20832,7 @@ ${response.content}`,
|
|
|
20340
20832
|
summary = `edit paused \u2014 read ${blindPath} first, then re-issue the edit`;
|
|
20341
20833
|
payload = buildReadFirstDirective(blindPath);
|
|
20342
20834
|
if (debugEnabled()) {
|
|
20343
|
-
const probe = await probeWouldLand(
|
|
20835
|
+
const probe = hasPositionArgs(call.args) ? "would-land=no match=position" : await probeWouldLand(
|
|
20344
20836
|
opts.bundle.cwd,
|
|
20345
20837
|
blindPath,
|
|
20346
20838
|
String(call.args.old_string ?? ""),
|
|
@@ -20448,6 +20940,7 @@ ${grounding}` : grounding;
|
|
|
20448
20940
|
const tracePath = traceReadPath(opts.bundle.cwd, String(call.args.path ?? ""));
|
|
20449
20941
|
const traceOffset = Number(call.args.offset ?? 1);
|
|
20450
20942
|
traceKey2 = `${tracePath}\0${traceOffset}`;
|
|
20943
|
+
if (!editingStarted) filesReadBeforeEdit.add(tracePath);
|
|
20451
20944
|
const { cls, repeats } = readTrace.record(
|
|
20452
20945
|
tracePath,
|
|
20453
20946
|
traceOffset,
|
|
@@ -20464,6 +20957,7 @@ ${grounding}` : grounding;
|
|
|
20464
20957
|
} else if (shellRead) {
|
|
20465
20958
|
groundsPath = shellRead.path;
|
|
20466
20959
|
traceKey2 = `${shellRead.path}\0${shellRead.offset}`;
|
|
20960
|
+
if (!editingStarted) filesReadBeforeEdit.add(shellRead.path);
|
|
20467
20961
|
const { cls, repeats } = readTrace.record(
|
|
20468
20962
|
shellRead.path,
|
|
20469
20963
|
shellRead.offset,
|
|
@@ -20493,6 +20987,13 @@ ${grounding}` : grounding;
|
|
|
20493
20987
|
if (!bouncedBlindEdit && !refusedArgEcho && liftsWithdrawal(call.name, changes))
|
|
20494
20988
|
mutatedSinceWithdrawal = true;
|
|
20495
20989
|
if (!bouncedBlindEdit && !refusedArgEcho && MUTATING_TOOLS.has(call.name)) {
|
|
20990
|
+
if (withdrawInspection && call.name === "edit") {
|
|
20991
|
+
const form = call.args.insert_after || call.args.insert_before ? "insert" : call.args.start_line ? "range" : "old_string";
|
|
20992
|
+
debugLog(
|
|
20993
|
+
`[reika:debug] round=${i} edit-during-pause form=${form} ${summary.startsWith("Edited ") ? "landed" : "failed"} +${diff?.added ?? 0}-${diff?.removed ?? 0} ${String(call.args.path ?? "")}
|
|
20994
|
+
`
|
|
20995
|
+
);
|
|
20996
|
+
}
|
|
20496
20997
|
if (summary.startsWith("Edited ") || summary.startsWith("Wrote ")) {
|
|
20497
20998
|
lastEditFailed = false;
|
|
20498
20999
|
lastEditFailure = void 0;
|
|
@@ -20502,7 +21003,12 @@ ${grounding}` : grounding;
|
|
|
20502
21003
|
groundsAuthored = call.name === "write";
|
|
20503
21004
|
}
|
|
20504
21005
|
if (planSteps) {
|
|
20505
|
-
const match = applyEdit(
|
|
21006
|
+
const match = applyEdit(
|
|
21007
|
+
planSteps,
|
|
21008
|
+
diff?.path ?? summary.split(" ")[1],
|
|
21009
|
+
diff?.text,
|
|
21010
|
+
diff
|
|
21011
|
+
);
|
|
20506
21012
|
if (match) {
|
|
20507
21013
|
opts.onPlanProgress?.(planSteps);
|
|
20508
21014
|
const done = planSteps.filter((s) => s.done).length;
|
|
@@ -20517,11 +21023,7 @@ ${grounding}` : grounding;
|
|
|
20517
21023
|
}
|
|
20518
21024
|
}
|
|
20519
21025
|
if (planSteps && call.name === "bash" && changes) {
|
|
20520
|
-
|
|
20521
|
-
for (const f of changes.files) {
|
|
20522
|
-
const hit = applyEdit(planSteps, f.path, f.hunks.map((hk) => hk.text).join("\n"));
|
|
20523
|
-
if (hit) match = hit;
|
|
20524
|
-
}
|
|
21026
|
+
const match = applyTreeChanges(planSteps, changes);
|
|
20525
21027
|
if (match) {
|
|
20526
21028
|
opts.onPlanProgress?.(planSteps);
|
|
20527
21029
|
const done = planSteps.filter((s) => s.done).length;
|
|
@@ -21968,14 +22470,14 @@ function truncate2(s, max) {
|
|
|
21968
22470
|
}
|
|
21969
22471
|
|
|
21970
22472
|
// src/store/sessions.ts
|
|
21971
|
-
import { createHash as
|
|
22473
|
+
import { createHash as createHash7, randomBytes as randomBytes4 } from "node:crypto";
|
|
21972
22474
|
import { open, mkdir as mkdir3, readdir as readdir8, readFile as readFile15, rename, writeFile as writeFile4 } from "node:fs/promises";
|
|
21973
22475
|
import { homedir as homedir13 } from "node:os";
|
|
21974
22476
|
import { basename as basename4, join as join19 } from "node:path";
|
|
21975
22477
|
var ROOT_HISTORY_DIR = join19(homedir13(), ".config", "reika", "history");
|
|
21976
22478
|
function projectHistoryDir(cwd, root = ROOT_HISTORY_DIR) {
|
|
21977
22479
|
const slug2 = basename4(cwd).replace(/[^A-Za-z0-9._-]/g, "_") || "root";
|
|
21978
|
-
const hash =
|
|
22480
|
+
const hash = createHash7("sha1").update(cwd).digest("hex").slice(0, 8);
|
|
21979
22481
|
return join19(root, "projects", `${slug2}-${hash}`);
|
|
21980
22482
|
}
|
|
21981
22483
|
function newSessionPath(dir, startedAt, stem = sessionStem(startedAt)) {
|
|
@@ -22167,8 +22669,8 @@ export {
|
|
|
22167
22669
|
modeSide,
|
|
22168
22670
|
resolveModeCommand,
|
|
22169
22671
|
latchesFor,
|
|
22170
|
-
callModel,
|
|
22171
22672
|
estimateRequestTokens,
|
|
22673
|
+
callModel,
|
|
22172
22674
|
HIDDEN_TOOL_ARGS,
|
|
22173
22675
|
formatElapsed,
|
|
22174
22676
|
turnEndLabel,
|