@alexwkleung/reika 0.14.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.
@@ -29,7 +29,7 @@ import {
29
29
  streamDispatcher,
30
30
  tokenize,
31
31
  withProbedLimits
32
- } from "./chunk-YCKCJJ3W.js";
32
+ } from "./chunk-B5UA4G44.js";
33
33
  import {
34
34
  API_USER_AGENT,
35
35
  DOCS_DIR,
@@ -41,7 +41,7 @@ import {
41
41
  formatEndpointLine,
42
42
  formatExperimentFlags,
43
43
  sessionStem
44
- } from "./chunk-OSLX5BGM.js";
44
+ } from "./chunk-VM3LKHIQ.js";
45
45
  import {
46
46
  __commonJS,
47
47
  __toESM
@@ -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
- "Make the smallest change that does the job. Read a file before you edit it. 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.",
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
- "Before edit, read the file to see exact text. 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.",
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,13 +4698,38 @@ 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;
4707
4712
  var DEDUP_PAYLOADS = process.env.REIKA_DEDUP_PAYLOADS !== "0";
4713
+ var AGE_CALL_ARGS = process.env.REIKA_AGE_ARGS !== "0";
4714
+ var AGED_ARGS_MIN_CHARS = 300;
4715
+ var AGED_ARG_STRING_MIN_CHARS = 120;
4716
+ var AGED_BASH_HEAD_CHARS = 160;
4717
+ var AGED_ARG_STUB_RE = /chars, sent earlier\]/;
4718
+ function agedArgEcho(args) {
4719
+ return AGED_ARG_STUB_RE.test(JSON.stringify(args));
4720
+ }
4721
+ var AGED_ARG_ECHO_DIRECTIVE = '(reika: not run. This call contains a placeholder like "[412 chars, sent earlier]". Reika put that in place of text from an older call to save room; it is not the text itself. Read the file for the current contents and send the real text. If the placeholder is genuinely part of what you are writing, send the identical call again and it will run.)';
4722
+ function stubCallArgs(name, args) {
4723
+ if (JSON.stringify(args).length < AGED_ARGS_MIN_CHARS) return args;
4724
+ const out = {};
4725
+ for (const [k, v] of Object.entries(args)) {
4726
+ if (typeof v !== "string" || v.length < AGED_ARG_STRING_MIN_CHARS) out[k] = v;
4727
+ else if (name === "bash" && k === "command")
4728
+ out[k] = `${v.split("\n")[0].slice(0, AGED_BASH_HEAD_CHARS)} \u2026[${v.length} chars, sent earlier]`;
4729
+ else out[k] = `[${v.length} chars, sent earlier]`;
4730
+ }
4731
+ return out;
4732
+ }
4708
4733
  var DEDUP_PAYLOAD_STUB = "(reika: identical to an earlier result above \u2014 body omitted, you already have it)";
4709
4734
  var DEDUP_TRAIL_STUB = "(reika: repeat of an earlier identical result \u2014 omitted)";
4710
4735
  var OUTCOME_SUMMARY_RE = /\b(fail(ed|ure)?|error|invalid|declined|denied|timed?\s?out|exceeded|not found|no (results?|match(es)?)|past end|found 0|listed 0|exit \d+|killed by)\b/i;
@@ -4716,7 +4741,7 @@ var SMALL_AGED_PAYLOAD_FLOOR_CHARS = 2048;
4716
4741
  var SMALL_AGED_PAYLOAD_FLOOR_TOTAL_CHARS = 4096;
4717
4742
  var DIFF_STRUCTURE_RE = /^(?:diff --git |--- |\+\+\+ |@@ )/;
4718
4743
  var AGED_READ_SKELETON_CHARS = 1024;
4719
- var READ_GUTTER_RE = /^\s*(\d+)│(.*)$/;
4744
+ var READ_GUTTER_RE = /^\s*(\d+)(?::[0-9a-f]+)?│(.*)$/;
4720
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/;
4721
4746
  var BLOCK_OPENER_RE = /(?:\{|=>|:)\s*$/;
4722
4747
  var NON_STRUCTURE_RE = /^(?:[)\]}]|\/\/|\/\*|\*|#|--|;;)/;
@@ -4826,7 +4851,14 @@ ${recapText}` : system;
4826
4851
  }
4827
4852
  return capPayload(payload, cap);
4828
4853
  };
4829
- const agedStats = { summary: 0, diff: 0, outline: 0, whole: 0, report: 0 };
4854
+ const agedStats = {
4855
+ summary: 0,
4856
+ diff: 0,
4857
+ outline: 0,
4858
+ whole: 0,
4859
+ report: 0,
4860
+ command: 0
4861
+ };
4830
4862
  const serializeAged = (msg, i) => {
4831
4863
  const { content, kind } = agedToolContent(msg, keptWhole.has(i));
4832
4864
  agedStats[kind]++;
@@ -4855,7 +4887,7 @@ ${recapText}` : system;
4855
4887
  type: "function",
4856
4888
  function: {
4857
4889
  name: tc.name,
4858
- arguments: JSON.stringify(tc.args)
4890
+ arguments: JSON.stringify(msg.argsAged ? stubCallArgs(tc.name, tc.args) : tc.args)
4859
4891
  }
4860
4892
  }));
4861
4893
  }
@@ -4968,14 +5000,14 @@ function newestLiveReadIndex(history, freshFrom, stubbed, prefixStable, rerender
4968
5000
  return -1;
4969
5001
  }
4970
5002
  function droppedPayloadCount(history, prefixStable = false) {
5003
+ return droppedPayloadMessages(history, prefixStable).length;
5004
+ }
5005
+ function droppedPayloadMessages(history, prefixStable = false) {
4971
5006
  const freshFrom = prefixStable ? 0 : findFreshToolBlockStart(history);
4972
5007
  const specIdx = prefixStable ? -1 : taskSpecIndex(history);
4973
5008
  return history.filter(
4974
5009
  (m, i) => m.role === "tool" && m.payload && i !== specIdx ? prefixStable ? !!m.aged : i < freshFrom : false
4975
- ).length;
4976
- }
4977
- function hasDroppedPayloads(history, prefixStable = false) {
4978
- return droppedPayloadCount(history, prefixStable) > 0;
5010
+ );
4979
5011
  }
4980
5012
  function findFreshToolBlockStart(history) {
4981
5013
  for (let i = history.length - 1; i >= 0; i--) {
@@ -5172,6 +5204,23 @@ function reportHead(payload, summary) {
5172
5204
  return `${head}
5173
5205
  (\u2026 report continues \u2014 ${payload.length - head.length} chars aged out; the head above is the chain, the cut part was what the subagent did not cover.)`;
5174
5206
  }
5207
+ var AGED_COMMAND_TAIL_LINES = 3;
5208
+ var AGED_COMMAND_TAIL_LINE_CHARS = 200;
5209
+ var SPILL_LOCATOR_RE = / saved to (\S+) — read that path/;
5210
+ function agedCommandResidue(msg) {
5211
+ if (!msg.summary.startsWith("Ran: ") || !msg.payload) return null;
5212
+ const locator = msg.payload.match(SPILL_LOCATOR_RE)?.[1];
5213
+ const failed = msg.exitCode !== void 0 && msg.exitCode !== 0;
5214
+ const tail = failed ? (msg.command?.outputTail ?? "").split("\n").filter((l) => l.trim()).slice(-AGED_COMMAND_TAIL_LINES).map(
5215
+ (l) => l.length > AGED_COMMAND_TAIL_LINE_CHARS ? `${l.slice(0, AGED_COMMAND_TAIL_LINE_CHARS)}\u2026` : l
5216
+ ) : [];
5217
+ if (!locator && tail.length === 0) return null;
5218
+ const parts = [
5219
+ `[reika: this command's output is no longer in context \u2014 a context-size limit, not a tool error.` + (tail.length > 0 ? " The last lines of the run are kept below." : "") + (locator ? ` The saved output is at ${locator}: read or grep that path instead of re-running the command.` : "") + "]"
5220
+ ];
5221
+ if (tail.length > 0) parts.push(tail.join("\n"));
5222
+ return parts.join("\n\n");
5223
+ }
5175
5224
  function readSkeleton(payload, summary) {
5176
5225
  const lines = payload.split("\n");
5177
5226
  const first = lines[0].match(READ_GUTTER_RE);
@@ -5244,7 +5293,13 @@ ${msg.payload}`, kind: "whole" };
5244
5293
  ${report2}`, kind: "report" };
5245
5294
  const diff = diffSkeleton(msg.payload);
5246
5295
  const skeleton = diff ?? readSkeleton(msg.payload, msg.summary);
5247
- if (!skeleton) return { content: msg.summary, kind: "summary" };
5296
+ if (!skeleton) {
5297
+ const residue = agedCommandResidue(msg);
5298
+ if (residue) return { content: `${msg.summary}
5299
+
5300
+ ${residue}`, kind: "command" };
5301
+ return { content: msg.summary, kind: "summary" };
5302
+ }
5248
5303
  if (skeleton.length >= msg.payload.length) {
5249
5304
  return { content: `${msg.summary}
5250
5305
 
@@ -5296,9 +5351,9 @@ function toolsToChatTools(tools) {
5296
5351
  }
5297
5352
 
5298
5353
  // src/provider/tokens.ts
5299
- var CHARS_PER_TOKEN2 = 4;
5354
+ var CHARS_PER_TOKEN = 4;
5300
5355
  function estimateTokens(text) {
5301
- return Math.ceil(text.length / CHARS_PER_TOKEN2);
5356
+ return Math.ceil(text.length / CHARS_PER_TOKEN);
5302
5357
  }
5303
5358
  function estimateRequestTokens(system, history, tools, opts) {
5304
5359
  const messages = messagesToChatParams(system, history, {
@@ -5506,6 +5561,7 @@ var FENCE_BLOCK = /```([^\n`]*)\n([\s\S]*?)```/g;
5506
5561
  var MIN_SNIPPET_CHARS = 8;
5507
5562
  var NON_IDENTIFIER_CHAR = /[^A-Za-z0-9_$.]/;
5508
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;
5509
5565
  function collapseWhitespace(s) {
5510
5566
  return s.replace(/\s+/g, " ").trim();
5511
5567
  }
@@ -5552,8 +5608,9 @@ function extractStepRefs(body) {
5552
5608
  const c = commandLineOf(line);
5553
5609
  if (c) addCommand(c);
5554
5610
  }
5555
- for (const m of noFences.replace(/`[^`\n]*`/g, " ").matchAll(BARE_PATH)) addPath(m[1]);
5556
- return { paths, snippets, commands };
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) };
5557
5614
  }
5558
5615
  var BULLET_START = /^\s{0,3}[-*•]\s+(\S.*)$/;
5559
5616
  function lineQuotesCommand(text) {
@@ -5620,18 +5677,28 @@ function pathsMatch(planPath, editedPath) {
5620
5677
  const b = normalizePath(editedPath);
5621
5678
  return a === b || a.endsWith("/" + b) || b.endsWith("/" + a);
5622
5679
  }
5623
- function applyEdit(steps, editedPath, diffText) {
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);
5624
5690
  for (let i = 0; i < steps.length; i++) {
5625
5691
  const s = steps[i];
5626
- if (!s.done && !s.waived && s.paths.some((p) => pathsMatch(p, editedPath))) {
5692
+ if (eligible(s) && s.paths.some((p) => pathsMatch(p, editedPath))) {
5627
5693
  s.done = true;
5628
5694
  return { index: i, by: "path" };
5629
5695
  }
5630
5696
  }
5631
5697
  if (diffText) {
5698
+ const changed = changedLines(diffText);
5632
5699
  for (let i = 0; i < steps.length; i++) {
5633
5700
  const s = steps[i];
5634
- if (!s.done && !s.waived && s.snippets.some((sn) => diffText.includes(sn))) {
5701
+ if (eligible(s) && s.snippets.some((sn) => changed.includes(sn))) {
5635
5702
  s.done = true;
5636
5703
  return { index: i, by: "content" };
5637
5704
  }
@@ -5639,11 +5706,26 @@ function applyEdit(steps, editedPath, diffText) {
5639
5706
  }
5640
5707
  return null;
5641
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
+ }
5642
5724
  function applyCommand(steps, commandText) {
5643
5725
  const ran = collapseWhitespace(commandText);
5644
5726
  for (let i = 0; i < steps.length; i++) {
5645
5727
  const s = steps[i];
5646
- if (!s.done && !s.waived && s.commands.some((c) => ran.includes(c))) {
5728
+ if (!s.done && !s.waived && s.commands.some((c) => containsCommand(ran, c))) {
5647
5729
  s.done = true;
5648
5730
  return i;
5649
5731
  }
@@ -5722,19 +5804,32 @@ function seedPlanProgress(history) {
5722
5804
  const marker = latestPlanMarker(history);
5723
5805
  if (!marker || marker.steps.length === 0) return null;
5724
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
+ }
5725
5812
  for (let i = marker.index + 1; i < history.length; i++) {
5726
5813
  const m = history[i];
5727
5814
  const edited = editedPathFrom(m);
5728
5815
  if (edited && m.role === "tool") {
5729
- applyEdit(steps, edited, m.diff?.text);
5730
- } else if (m.role === "tool" && m.command?.text && ranSuccessfully(m)) {
5731
- applyCommand(steps, m.command.text);
5732
- } else if (m.role === "system" && m.planWaived) {
5733
- 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);
5734
5820
  }
5735
5821
  }
5736
5822
  return steps;
5737
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
+ }
5738
5833
  function stepLine(s) {
5739
5834
  const text = s.text.length > MAX_STEP_TEXT ? s.text.slice(0, MAX_STEP_TEXT - 1) + "\u2026" : s.text;
5740
5835
  return `[${s.done ? "x" : s.waived ? "~" : " "}] ${s.n}. ${text}`;
@@ -5893,7 +5988,6 @@ function createSearchTool(provider) {
5893
5988
  }
5894
5989
 
5895
5990
  // src/agent/compaction.ts
5896
- var CHARS_PER_TOKEN3 = 4;
5897
5991
  var KEEP_FRACTION = 0.3;
5898
5992
  var RECAP_FRACTION = 0.1;
5899
5993
  var HANDOFF_FINDINGS_FRACTION = 0.15;
@@ -5914,7 +6008,7 @@ function foldPoint(history, contextWindow, calibration = 1, minGen = DEFAULT_MIN
5914
6008
  if (!contextWindow) return null;
5915
6009
  const calib = calibration > 0 ? calibration : 1;
5916
6010
  const avail = availTokens(contextWindow, minGen);
5917
- const keepBudget = avail * CHARS_PER_TOKEN3 * KEEP_FRACTION / calib;
6011
+ const keepBudget = avail * CHARS_PER_TOKEN * KEEP_FRACTION / calib;
5918
6012
  let chars = 0;
5919
6013
  let keepFrom = history.length;
5920
6014
  for (let i = history.length - 1; i >= 0; i--) {
@@ -5930,7 +6024,8 @@ function foldPoint(history, contextWindow, calibration = 1, minGen = DEFAULT_MIN
5930
6024
  return { recapStart, keepFrom, avail, calib };
5931
6025
  }
5932
6026
  function wouldFold(history, contextWindow, calibration = 1, minGen = DEFAULT_MIN_GEN_TOKENS) {
5933
- return foldPoint(history, contextWindow, calibration, minGen) !== null;
6027
+ const point = foldPoint(history, contextWindow, calibration, minGen);
6028
+ return point !== null && point.keepFrom - point.recapStart > keptPlan(history, point).length;
5934
6029
  }
5935
6030
  function foldAfterShed(history, estimate, contextWindow, calibration = 1, minGen = DEFAULT_MIN_GEN_TOKENS, shedReasoning = true, requirePressure = true) {
5936
6031
  const copy = history.map((m) => ({ ...m }));
@@ -5943,17 +6038,35 @@ function compactHistory(history, contextWindow, calibration = 1, minGen = DEFAUL
5943
6038
  const point = foldPoint(history, contextWindow, calibration, minGen);
5944
6039
  if (!point) return 0;
5945
6040
  const { recapStart, keepFrom, avail, calib } = point;
5946
- const span = history.slice(recapStart, keepFrom);
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]);
5947
6058
  const turnStart = Math.max(recapStart, lastUserMessageIndex(history) + 1);
5948
6059
  const preserved = carriedSpecBlock(history.slice(turnStart, keepFrom)) ?? electSpecBlock(history, recapStart, keepFrom);
5949
6060
  const recap = buildRecap(span, avail, calib, note);
5950
- history.splice(recapStart, keepFrom - recapStart, {
5951
- role: "compaction",
5952
- content: preserved ? `${preserved}
6061
+ history.splice(
6062
+ recapStart,
6063
+ keepFrom - recapStart,
6064
+ { role: "compaction", content: preserved ? `${preserved}
5953
6065
 
5954
- ${recap}` : recap
5955
- });
5956
- return keepFrom - recapStart;
6066
+ ${recap}` : recap },
6067
+ ...kept
6068
+ );
6069
+ return keepFrom - recapStart - kept.length;
5957
6070
  }
5958
6071
  var AGE_LOW_FRACTION = ageLowFraction();
5959
6072
  function ageLowFraction() {
@@ -5962,14 +6075,14 @@ function ageLowFraction() {
5962
6075
  return raw;
5963
6076
  }
5964
6077
  var SMALL_PAYLOAD_CHARS = 2e3;
5965
- function batchAgePayloads(history, estimate, contextWindow, minGen = DEFAULT_MIN_GEN_TOKENS, shedReasoning = true) {
6078
+ function batchAgePayloads(history, estimate, contextWindow, minGen = DEFAULT_MIN_GEN_TOKENS, shedReasoning = true, shedArgs = AGE_CALL_ARGS, protectFrom = Infinity) {
5966
6079
  const threshold = compactThreshold(contextWindow, minGen);
5967
- const none = { marked: 0, bulk: 0, crumbs: 0, kept: 0, short: 0 };
6080
+ const none = { marked: 0, bulk: 0, crumbs: 0, args: 0, kept: 0, short: 0 };
5968
6081
  if (estimate() <= threshold) return none;
5969
6082
  const target = threshold * AGE_LOW_FRACTION;
5970
- const protect = protectedTailStart(history);
6083
+ const protect = Math.min(protectedTailStart(history), protectFrom);
5971
6084
  const specIdx = taskSpecIndex(history);
5972
- const out = { marked: 0, bulk: 0, crumbs: 0, kept: 0, short: 0 };
6085
+ const out = { marked: 0, bulk: 0, crumbs: 0, args: 0, kept: 0, short: 0 };
5973
6086
  const survivingCrumbs = () => {
5974
6087
  let n = 0;
5975
6088
  for (let i = 0; i < protect; i++) {
@@ -5979,7 +6092,7 @@ function batchAgePayloads(history, estimate, contextWindow, minGen = DEFAULT_MIN
5979
6092
  }
5980
6093
  return n;
5981
6094
  };
5982
- const marks = shedOrder(history, protect, specIdx, shedReasoning);
6095
+ const marks = shedOrder(history, protect, specIdx, shedReasoning, shedArgs);
5983
6096
  let applied = 0;
5984
6097
  const applyTo = (k) => {
5985
6098
  while (applied < k) marks[applied++].apply();
@@ -6004,11 +6117,12 @@ function batchAgePayloads(history, estimate, contextWindow, minGen = DEFAULT_MIN
6004
6117
  out.marked++;
6005
6118
  if (marks[i].kind === "bulk") out.bulk++;
6006
6119
  else if (marks[i].kind === "crumb") out.crumbs++;
6120
+ else if (marks[i].kind === "args") out.args++;
6007
6121
  }
6008
6122
  out.kept = survivingCrumbs();
6009
6123
  return out;
6010
6124
  }
6011
- function shedOrder(history, protect, specIdx, shedReasoning) {
6125
+ function shedOrder(history, protect, specIdx, shedReasoning, shedArgs) {
6012
6126
  const marks = [];
6013
6127
  for (let i = 0; i < protect; i++) {
6014
6128
  const m = history[i];
@@ -6056,6 +6170,14 @@ function shedOrder(history, protect, specIdx, shedReasoning) {
6056
6170
  }
6057
6171
  }
6058
6172
  }
6173
+ if (shedArgs) {
6174
+ for (let i = 0; i < protect; i++) {
6175
+ const m = history[i];
6176
+ if (m.role !== "assistant" || m.argsAged || !m.toolCalls) continue;
6177
+ if (!m.toolCalls.some((tc) => JSON.stringify(tc.args).length >= AGED_ARGS_MIN_CHARS)) continue;
6178
+ marks.push({ kind: "args", apply: () => m.argsAged = true, undo: () => delete m.argsAged });
6179
+ }
6180
+ }
6059
6181
  return marks;
6060
6182
  }
6061
6183
  function protectedTailStart(history) {
@@ -6068,7 +6190,9 @@ function msgChars(m) {
6068
6190
  case "user":
6069
6191
  return m.content.length;
6070
6192
  case "assistant":
6071
- return (m.content?.length ?? 0) + (m.reasoning?.length ?? 0) + (m.toolCalls ? JSON.stringify(m.toolCalls).length : 0);
6193
+ return (m.content?.length ?? 0) + (m.reasoning?.length ?? 0) + (m.toolCalls ? JSON.stringify(
6194
+ m.argsAged ? m.toolCalls.map((tc) => ({ ...tc, args: stubCallArgs(tc.name, tc.args) })) : m.toolCalls
6195
+ ).length : 0);
6072
6196
  case "tool":
6073
6197
  return m.aged ? agedContentChars(m) : m.summary.length;
6074
6198
  case "compaction":
@@ -6181,7 +6305,7 @@ function describeFile(path, ranges) {
6181
6305
  }
6182
6306
  var NOTE_SHARE = 0.7;
6183
6307
  function buildRecap(span, avail, calib, note) {
6184
- const recapBudget = avail * CHARS_PER_TOKEN3 * RECAP_FRACTION / calib;
6308
+ const recapBudget = avail * CHARS_PER_TOKEN * RECAP_FRACTION / calib;
6185
6309
  const priorRecaps = [];
6186
6310
  const entries = [];
6187
6311
  const toolCounts = {};
@@ -6361,7 +6485,7 @@ function distillPlanHandoff(history, contextWindow, calibration = 1, minGen = DE
6361
6485
  if (span.every((m) => m.role === "compaction")) return { folded: 0, reason: "already-distilled" };
6362
6486
  const calib = calibration > 0 ? calibration : 1;
6363
6487
  const findingsBudget = contextWindow ? Math.floor(
6364
- availTokens(contextWindow, minGen) * CHARS_PER_TOKEN3 * findingsBudgetFraction / calib
6488
+ availTokens(contextWindow, minGen) * CHARS_PER_TOKEN * findingsBudgetFraction / calib
6365
6489
  ) : Number.MAX_SAFE_INTEGER;
6366
6490
  const digest = buildHandoffDigest(span, findingsBudget);
6367
6491
  history.splice(spanStart, span.length, { role: "compaction", content: digest });
@@ -9755,7 +9879,30 @@ function gitMetadataWarning(cwd, full) {
9755
9879
  }
9756
9880
 
9757
9881
  // src/tools/read.ts
9882
+ import { createHash as createHash4 } from "node:crypto";
9883
+
9884
+ // src/tools/_lineref.ts
9758
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
9759
9906
  var READ_DEFAULT_LIMIT = 300;
9760
9907
  var readTool = {
9761
9908
  name: "read",
@@ -9778,7 +9925,7 @@ var readTool = {
9778
9925
  const limit = Math.max(1, Number(args.limit ?? READ_DEFAULT_LIMIT));
9779
9926
  const full = resolveUserPath(ctx.cwd, path);
9780
9927
  const text = await readFile7(full, "utf8");
9781
- const contentHash = createHash3("sha1").update(text).digest("hex");
9928
+ const contentHash = createHash4("sha1").update(text).digest("hex");
9782
9929
  const lines = text.split("\n");
9783
9930
  const total = lines.length > 1 && lines[lines.length - 1] === "" ? lines.length - 1 : lines.length;
9784
9931
  const relToCwd = relative6(ctx.cwd, full);
@@ -9793,7 +9940,7 @@ var readTool = {
9793
9940
  const sliceEnd = Math.min(offset - 1 + limit, total);
9794
9941
  const slice = lines.slice(offset - 1, sliceEnd);
9795
9942
  const end = offset - 1 + slice.length;
9796
- const numbered = slice.map((l, i) => `${String(offset + i).padStart(5, " ")}\u2502${l}`).join("\n");
9943
+ const numbered = slice.map((l, i) => gutterLine(offset + i, l)).join("\n");
9797
9944
  const remaining = total - end;
9798
9945
  const more = remaining > 0 ? `
9799
9946
  \u2026(${remaining} more line${remaining === 1 ? "" : "s"} below \u2014 call read with offset=${end + 1} to continue)` : "";
@@ -11019,60 +11166,38 @@ ${p.surface}
11019
11166
  }
11020
11167
 
11021
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
+ };
11022
11177
  var editTool = {
11023
11178
  name: "edit",
11024
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.",
11025
11180
  parameters: {
11026
11181
  type: "object",
11027
- properties: {
11028
- path: { type: "string", description: "File path, relative to cwd." },
11029
- old_string: {
11030
- type: "string",
11031
- description: "Exact text to replace. Include enough context to be unique in the file."
11032
- },
11033
- new_string: { type: "string", description: "Replacement text." }
11034
- },
11182
+ properties: EDIT_PARAMETERS,
11035
11183
  required: ["path", "old_string", "new_string"]
11036
11184
  },
11037
11185
  async run(args, ctx) {
11038
- const path = String(args.path);
11039
11186
  const oldStr = String(args.old_string ?? "");
11040
11187
  const newStr = String(args.new_string ?? "");
11041
- const full = resolveUserPath(ctx.cwd, path);
11042
- const outside = escapesProject(ctx.cwd, full);
11043
- const gitMeta = gitMetadataWarning(ctx.cwd, full);
11044
- const gated = outside || gitMeta !== void 0;
11045
- const warnings = [...outside ? [OUTSIDE_PROJECT_WARNING] : [], ...gitMeta ? [gitMeta] : []];
11046
- const rel = relative10(ctx.cwd, full) || path;
11047
- const display = outside ? full : rel;
11048
- if (gated && !ctx.requestApproval) {
11049
- if (outside) {
11050
- return {
11051
- 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.`
11052
- };
11053
- }
11054
- return {
11055
- 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.`
11056
- };
11057
- }
11188
+ const target = resolveEditTarget(String(args.path), ctx);
11189
+ const refused = refuseUnconfirmable(target, ctx);
11190
+ if (refused) return refused;
11191
+ const { display } = target;
11058
11192
  if (oldStr === "") {
11059
11193
  return { summary: `Edit failed: old_string is empty` };
11060
11194
  }
11061
11195
  if (oldStr === newStr) {
11062
11196
  return { summary: `Edit failed: old_string and new_string are identical` };
11063
11197
  }
11064
- let approvedOutside = false;
11065
- if (gated && ctx.requestApproval) {
11066
- const ok = await ctx.requestApproval({
11067
- tool: "edit",
11068
- subject: display,
11069
- preview: intentDiff(oldStr, newStr),
11070
- warnings
11071
- });
11072
- if (!ok) return { summary: declineSummary("Edit", ` for ${display}`, ctx) };
11073
- approvedOutside = true;
11074
- }
11075
- 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");
11076
11201
  let start;
11077
11202
  let matchLen;
11078
11203
  let effectiveNew;
@@ -11083,7 +11208,7 @@ var editTool = {
11083
11208
  const a = lineOf(text, first);
11084
11209
  const b = lineOf(text, second);
11085
11210
  return {
11086
- 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))
11087
11212
  };
11088
11213
  }
11089
11214
  start = first;
@@ -11093,7 +11218,11 @@ var editTool = {
11093
11218
  const fuzzy = fuzzyLineMatch(text, oldStr, newStr);
11094
11219
  if (fuzzy.status === "multiple") {
11095
11220
  return {
11096
- 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
+ )
11097
11226
  };
11098
11227
  }
11099
11228
  if (fuzzy.status === "mixed") {
@@ -11114,49 +11243,314 @@ var editTool = {
11114
11243
  matchLen = fuzzy.len;
11115
11244
  effectiveNew = fuzzy.newStr;
11116
11245
  }
11117
- const matchedOld = text.slice(start, start + matchLen);
11118
- const beforeText = text.slice(0, start);
11119
- const diffText = buildEditDiff(
11120
- matchedOld,
11121
- effectiveNew,
11122
- beforeText,
11123
- text.slice(start + matchLen)
11124
- );
11125
- const startLine = editDiffStartLine(beforeText);
11126
- if (ctx.requestApproval && !approvedOutside) {
11127
- const ok = await ctx.requestApproval({
11128
- tool: "edit",
11129
- subject: display,
11130
- preview: diffText,
11131
- startLine
11132
- });
11133
- if (!ok) return { summary: declineSummary("Edit", ` for ${display}`, ctx) };
11134
- }
11135
- const current = await readFile10(full, "utf8").catch(() => null);
11136
- if (current !== text) {
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 ?? "") !== "") {
11137
11366
  return {
11138
- 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`
11367
+ summary: "Edit failed: give either old_string or a position (insert_after, insert_before, start_line/end_line), not both"
11139
11368
  };
11140
11369
  }
11141
- const next = text.slice(0, start) + effectiveNew + text.slice(start + matchLen);
11142
- await writeFile(full, next, "utf8");
11143
- const line = text.slice(0, start).split("\n").length;
11144
- const added = countPrefixed(diffText, "+ ");
11145
- const removed = countPrefixed(diffText, "- ");
11146
- const [depPayload, url] = await Promise.all([
11147
- surfaceImportedDeps(ctx, effectiveNew),
11148
- groundUrls(ctx, effectiveNew, rel)
11149
- ]);
11150
- const refreshed = refreshedFile(display, next);
11151
- const payload = [depPayload, url.note, refreshed].filter(Boolean).join("\n\n") || void 0;
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) {
11152
11401
  return {
11153
- summary: `Edited ${display} at line ${line} (+${added} -${removed})`,
11154
- diff: { text: diffText, path: rel, added, removed, startLine },
11155
- ...payload ? { payload } : {},
11156
- ...url.notice ? { notice: url.notice } : {}
11402
+ summary: "Edit failed: give one position \u2014 insert_after, insert_before, or start_line/end_line"
11157
11403
  };
11158
11404
  }
11159
- };
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
+ }
11160
11554
  function intentDiff(oldStr, newStr) {
11161
11555
  const minus = oldStr.split("\n").map((l) => `- ${l}`);
11162
11556
  const plus = newStr.split("\n").map((l) => `+ ${l}`);
@@ -11169,7 +11563,7 @@ function refreshedFile(rel, content) {
11169
11563
  const lines = content.split("\n");
11170
11564
  const total = lines.length > 1 && lines[lines.length - 1] === "" ? lines.length - 1 : lines.length;
11171
11565
  if (total > REFRESH_MAX_LINES) return void 0;
11172
- const numbered = lines.slice(0, total).map((l, i) => `${String(i + 1).padStart(5, " ")}\u2502${l}`).join("\n");
11566
+ const numbered = lines.slice(0, total).map((l, i) => gutterLine(i + 1, l)).join("\n");
11173
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.)
11174
11568
  ${numbered}`;
11175
11569
  }
@@ -11218,7 +11612,7 @@ function fuzzyLineMatch(text, oldStr, newStr) {
11218
11612
  const closest = locateClosest(fileLines, oldTrim);
11219
11613
  return {
11220
11614
  status: "none",
11221
- hint: formatNotFoundHint(closest, oldLines, oldTrim),
11615
+ hint: formatNotFoundHint(closest, oldLines, oldTrim, fileLines),
11222
11616
  failure: closestToFailure(closest, fileLines, oldTrim)
11223
11617
  };
11224
11618
  }
@@ -11299,11 +11693,24 @@ function locateByTokenOverlap(fileLines, oldTrim) {
11299
11693
  }
11300
11694
  return best && best.hits >= need ? best.start : null;
11301
11695
  }
11302
- function formatNotFoundHint(closest, oldLines, oldTrim) {
11696
+ function formatNotFoundHint(closest, oldLines, oldTrim, fileLines) {
11303
11697
  const i0 = oldTrim.findIndex((t) => t !== "");
11304
11698
  if (i0 === -1) return "";
11305
11699
  if (!closest.found) return " No line matches it even ignoring whitespace.";
11306
- 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;
11307
11714
  }
11308
11715
  function closestToFailure(closest, fileLines, oldTrim) {
11309
11716
  if (!closest.found) {
@@ -11331,7 +11738,7 @@ function blockExcerpt(fileLines, blockStart, blockLen, divergentLine) {
11331
11738
  from = Math.max(0, divergentLine - 1 - Math.floor(EXCERPT_MAX_LINES / 2));
11332
11739
  to = Math.min(fileLines.length, from + EXCERPT_MAX_LINES);
11333
11740
  }
11334
- return fileLines.slice(from, to).map((l, idx) => `${String(from + idx + 1).padStart(5, " ")}\u2502${l}`).join("\n");
11741
+ return fileLines.slice(from, to).map((l, idx) => gutterLine(from + idx + 1, l)).join("\n");
11335
11742
  }
11336
11743
 
11337
11744
  // src/tools/write.ts
@@ -15151,6 +15558,7 @@ var ChromeHost = class {
15151
15558
  this.port = opts.port ?? DEFAULT_PORT;
15152
15559
  this.binary = opts.binary;
15153
15560
  this.profileDir = opts.profileDir ?? join15(homedir10(), ".config", "reika", "chrome");
15561
+ protectLoopbackPort(this.port);
15154
15562
  }
15155
15563
  async newTab() {
15156
15564
  await this.ensure();
@@ -15510,11 +15918,31 @@ async function openSession(wsUrl) {
15510
15918
  };
15511
15919
  }
15512
15920
 
15513
- // src/search/cdp.ts
15514
- var SEARCH_URL = "https://search.brave.com/search?q=";
15515
- var OWN_HOSTS = /(^|\.)(brave\.com|search\.brave\.com)$/;
15921
+ // src/search/engines.ts
15922
+ var DUCKDUCKGO = {
15923
+ name: "duckduckgo",
15924
+ // The HTML version: no script-built page to wait for, real titles in the link text, and every
15925
+ // result's address in the `uddg` parameter of its link.
15926
+ searchUrl: (q) => `https://html.duckduckgo.com/html/?q=${encodeURIComponent(q)}`,
15927
+ ownHosts: /(^|\.)(duckduckgo\.com|duck\.com|duck\.ai)$/,
15928
+ unwrap: (u) => /(^|\.)duckduckgo\.com$/.test(u.hostname) && u.pathname === "/l/" ? u.searchParams.get("uddg") ?? void 0 : void 0,
15929
+ challengeText: /bots use duckduckgo|confirm this search was made by a human|select all squares/i,
15930
+ minAnchors: 10
15931
+ };
15932
+ var BRAVE = {
15933
+ name: "brave",
15934
+ searchUrl: (q) => `https://search.brave.com/search?q=${encodeURIComponent(q)}`,
15935
+ ownHosts: /(^|\.)(brave\.com|brave\.app)$/,
15936
+ challengeText: /verifying you|traditional captcha/i,
15937
+ minAnchors: 10
15938
+ };
15939
+ var ENGINE_ORDER = [DUCKDUCKGO, BRAVE];
15940
+
15941
+ // src/search/extract.ts
15516
15942
  var DATE_LINE = /^(?:(?:jan|feb|mar|apr|may|jun|jul|aug|sep|sept|oct|nov|dec)[a-z]*\.? \d{1,2},? \d{4}|\d+ (?:second|minute|hour|day|week|month|year)s? ago)$/i;
15517
- function extractionScript(maxResults) {
15943
+ var MAX_LINKS = 400;
15944
+ var BODY_TEXT_CHARS = 4e3;
15945
+ function collectScript() {
15518
15946
  return `(() => {
15519
15947
  const clean = s => (s || '').replace(/\\s+/g, ' ').trim();
15520
15948
  const visible = el => {
@@ -15522,64 +15950,102 @@ function extractionScript(maxResults) {
15522
15950
  const st = getComputedStyle(el);
15523
15951
  return r.width > 0 && r.height > 0 && st.display !== 'none' && st.visibility !== 'hidden';
15524
15952
  };
15525
- const own = ${OWN_HOSTS.toString()};
15526
- // A result anchor's innerText is "SiteName / breadcrumb \u203A path / actual title" on separate lines.
15527
- // The last line is the title; the earlier ones are chrome that would otherwise be fed to the model
15528
- // as part of it. No class names involved, so a redesign degrades this to "whole text", not to junk.
15529
- const dateLine = ${DATE_LINE.toString()};
15530
- const titleOf = a => {
15531
- const lines = (a.innerText || '').split('\\n').map(clean).filter(Boolean);
15532
- const named = lines.filter(l => !dateLine.test(l));
15533
- return named.length ? named[named.length - 1] : '';
15534
- };
15953
+ const chromeSel = 'header,footer,nav,[role=banner],[role=contentinfo],[role=navigation]';
15535
15954
  // The container repeats the anchor's own text before the description; removing it stops every
15536
15955
  // snippet from opening with a copy of the title it sits under.
15537
- const snippetFor = (a, title) => {
15538
- const anchorText = clean(a.innerText || '');
15956
+ const snippetFor = a => {
15957
+ const own = clean(a.textContent);
15539
15958
  let node = a.parentElement;
15540
15959
  for (let depth = 0; node && depth < 4; depth++, node = node.parentElement) {
15541
15960
  // Stop before climbing into a container that groups several results, or the snippet picks up
15542
15961
  // the *next* result's title. A block holding many links is a group, not one result's body.
15543
15962
  if (node.querySelectorAll('a[href]').length > 3) break;
15544
- const full = clean(node.innerText || '');
15545
- if (full.length <= anchorText.length + 40) continue;
15546
- const body = clean(full.split(anchorText).join(' ').split(title).join(' '));
15963
+ const full = clean(node.textContent);
15964
+ if (full.length <= own.length + 40) continue;
15965
+ const body = clean(full.split(own).join(' '));
15547
15966
  if (body.length >= 20) return body.slice(0, 300);
15548
15967
  }
15549
15968
  return '';
15550
15969
  };
15551
- const seen = new Set();
15552
- const perHost = new Map();
15970
+ const all = document.querySelectorAll('a[href]');
15971
+ const links = [];
15972
+ for (const a of all) {
15973
+ if (links.length >= ${MAX_LINKS}) break;
15974
+ links.push({
15975
+ href: a.href,
15976
+ inner: a.innerText || '',
15977
+ text: clean(a.textContent),
15978
+ visible: visible(a),
15979
+ chrome: !!a.closest(chromeSel),
15980
+ snippet: snippetFor(a),
15981
+ });
15982
+ }
15983
+ const body = document.body ? document.body.innerText || document.body.textContent || '' : '';
15984
+ return JSON.stringify({ links, anchors: all.length, bodyText: body.slice(0, ${BODY_TEXT_CHARS}) });
15985
+ })()`;
15986
+ }
15987
+ var clean = (s) => s.replace(/\s+/g, " ").trim();
15988
+ function titleOf(link) {
15989
+ const lines = link.inner.split("\n").map(clean).filter(Boolean);
15990
+ const named = lines.filter((l) => !DATE_LINE.test(l));
15991
+ return named.length ? named[named.length - 1] : link.text;
15992
+ }
15993
+ var keyOf = (url) => url.hostname + url.pathname;
15994
+ var looksLikeProse = (s) => (s.match(/ /g) ?? []).length >= 4;
15995
+ function pickResults(page, engine, max) {
15996
+ const descriptions = /* @__PURE__ */ new Map();
15997
+ for (const link of page.links) {
15998
+ if (!link.visible || link.chrome || !looksLikeProse(link.text)) continue;
15999
+ const url = resultUrl(link.href, engine);
16000
+ if (!url) continue;
16001
+ const key = keyOf(url);
16002
+ if (link.text.length > (descriptions.get(key)?.length ?? 0)) descriptions.set(key, link.text);
16003
+ }
16004
+ const seen = /* @__PURE__ */ new Set();
16005
+ const perHost = /* @__PURE__ */ new Map();
15553
16006
  const results = [];
15554
- for (const a of document.querySelectorAll('a[href]')) {
15555
- if (results.length >= ${maxResults}) break;
15556
- if (!visible(a)) continue;
15557
- const title = titleOf(a);
16007
+ for (const link of page.links) {
16008
+ if (results.length >= max) break;
16009
+ if (!link.visible || link.chrome) continue;
16010
+ const title = titleOf(link);
15558
16011
  if (title.length < 8) continue;
15559
- let u;
15560
- try { u = new URL(a.href); } catch { continue; }
15561
- if (!/^https?:$/.test(u.protocol)) continue;
15562
- if (own.test(u.hostname)) continue;
15563
- const key = u.hostname + u.pathname;
16012
+ const url = resultUrl(link.href, engine);
16013
+ if (!url) continue;
16014
+ const key = keyOf(url);
15564
16015
  if (seen.has(key)) continue;
15565
- // A result with a nested sub-link cluster (issues, discussions) contributes a run of tightly
15566
- // packed anchors from one host in DOM order, which crowds out every lower-ranked result. Two
15567
- // per host keeps that from turning eight slots into one site's sitemap.
15568
- const used = perHost.get(u.hostname) || 0;
16016
+ const used = perHost.get(url.hostname) ?? 0;
15569
16017
  if (used >= 2) continue;
15570
- perHost.set(u.hostname, used + 1);
16018
+ perHost.set(url.hostname, used + 1);
15571
16019
  seen.add(key);
15572
- results.push({ title: title.slice(0, 180), url: u.href, snippet: snippetFor(a, title) });
16020
+ const description = descriptions.get(key);
16021
+ const snippet = link.snippet || (description && description.length > title.length ? description : "");
16022
+ results.push({ title: title.slice(0, 180), url: url.href, snippet: snippet.slice(0, 300) });
15573
16023
  }
15574
- return JSON.stringify({
15575
- results,
15576
- anchors: document.querySelectorAll('a[href]').length,
15577
- blocked: /verifying you|not a bot|unusual traffic|are you a robot|verify you are human|complete the security check|traditional captcha/i
15578
- .test(document.body ? document.body.innerText : ''),
15579
- });
15580
- })()`;
16024
+ return results;
16025
+ }
16026
+ function resultUrl(href, engine) {
16027
+ let u;
16028
+ try {
16029
+ u = new URL(href);
16030
+ } catch {
16031
+ return void 0;
16032
+ }
16033
+ const unwrapped = engine.unwrap?.(u);
16034
+ if (unwrapped !== void 0) {
16035
+ try {
16036
+ u = new URL(unwrapped);
16037
+ } catch {
16038
+ return void 0;
16039
+ }
16040
+ }
16041
+ if (!/^https?:$/.test(u.protocol)) return void 0;
16042
+ if (engine.ownHosts.test(u.hostname)) return void 0;
16043
+ return u;
15581
16044
  }
15582
- var MIN_SERP_ANCHORS = 10;
16045
+
16046
+ // src/search/cdp.ts
16047
+ var SHARED_CHALLENGE_TEXT = /not a bot|unusual traffic|are you a robot|verify you are human|complete the security check/i;
16048
+ var MIN_USABLE_RESULTS = 3;
15583
16049
  var CHALLENGE_WAIT_MS = 12e4;
15584
16050
  var CHALLENGE_POLL_MS = 1e3;
15585
16051
  var CdpSearchProvider = class {
@@ -15587,26 +16053,63 @@ var CdpSearchProvider = class {
15587
16053
  this.host = host;
15588
16054
  this.waitMs = opts.challengeWaitMs ?? CHALLENGE_WAIT_MS;
15589
16055
  this.pollMs = opts.challengePollMs ?? CHALLENGE_POLL_MS;
16056
+ this.engines = opts.engines ?? ENGINE_ORDER;
15590
16057
  }
15591
16058
  host;
15592
16059
  waitMs;
15593
16060
  pollMs;
16061
+ engines;
15594
16062
  // One challenge at a time. Parallel searches in a turn are all refused together, and the solve
15595
16063
  // is profile-wide: the first to hit it raises its own tab and waits, the rest wait on the same
15596
16064
  // promise and then simply reload — a second raised window would compete for the user's one solve.
15597
16065
  challenge;
15598
16066
  async search(query, opts = {}) {
15599
16067
  const max = opts.maxResults ?? 8;
15600
- const url = SEARCH_URL + encodeURIComponent(query);
16068
+ const enough = Math.min(max, MIN_USABLE_RESULTS);
16069
+ let results = [];
16070
+ let challenged;
16071
+ let failure;
16072
+ for (const engine of this.engines) {
16073
+ try {
16074
+ const answer = await this.searchEngine(engine, query, max, opts, false);
16075
+ if (answer === "challenged") challenged ??= engine;
16076
+ else results = mergeResults(results, answer, max);
16077
+ } catch (e) {
16078
+ failure ??= e;
16079
+ }
16080
+ if (results.length >= enough) return results;
16081
+ }
16082
+ if (challenged) {
16083
+ try {
16084
+ const answer = await this.searchEngine(challenged, query, max, opts, true);
16085
+ if (answer !== "challenged") results = mergeResults(answer, results, max);
16086
+ } catch (e) {
16087
+ if (results.length === 0) throw e;
16088
+ debugLog(
16089
+ `[cdp] ${challenged.name}: check not completed, keeping the other engines' results`
16090
+ );
16091
+ }
16092
+ return results;
16093
+ }
16094
+ if (results.length === 0 && failure) throw failure;
16095
+ return results;
16096
+ }
16097
+ async searchEngine(engine, query, max, opts, allowChallenge) {
16098
+ const url = engine.searchUrl(query);
15601
16099
  const tab = await this.host.newTab();
15602
16100
  let holdOpen = false;
15603
16101
  try {
15604
16102
  await tab.navigate(url);
15605
- let data = parseExtraction(await tab.evaluate(extractionScript(max)));
15606
- if (interstitial(data)) {
16103
+ let page = parsePage2(await tab.evaluate(collectScript()));
16104
+ let picked = pickResults(page, engine, max);
16105
+ if (interstitial(engine, page, picked.length)) {
16106
+ if (!allowChallenge) {
16107
+ debugLog(`[cdp] ${engine.name} "${query}" -> challenge, trying the next engine`);
16108
+ return "challenged";
16109
+ }
15607
16110
  const owner = !this.challenge;
15608
16111
  if (owner) {
15609
- this.challenge = this.awaitSolve(tab, max, opts).finally(() => {
16112
+ this.challenge = this.awaitSolve(tab, engine, max, opts).finally(() => {
15610
16113
  this.challenge = void 0;
15611
16114
  });
15612
16115
  }
@@ -15617,19 +16120,14 @@ var CdpSearchProvider = class {
15617
16120
  throw e;
15618
16121
  }
15619
16122
  await tab.navigate(url);
15620
- data = parseExtraction(await tab.evaluate(extractionScript(max)));
15621
- if (interstitial(data)) throw unavailable(data);
16123
+ page = parsePage2(await tab.evaluate(collectScript()));
16124
+ picked = pickResults(page, engine, max);
16125
+ if (interstitial(engine, page, picked.length)) throw unavailable(engine, page);
15622
16126
  }
15623
- const results = (data.results ?? []).filter((r) => r.url && r.url.trim().length > 0).slice(0, max).map((r) => ({
15624
- title: r.title ?? "",
15625
- url: r.url,
15626
- snippet: r.snippet ?? "",
15627
- source: "brave"
15628
- }));
15629
16127
  debugLog(
15630
- `[cdp] "${query}" -> ${results.length} result(s), ${data.anchors ?? 0} links on page`
16128
+ `[cdp] ${engine.name} "${query}" -> ${picked.length} result(s), ${page.anchors} links on page`
15631
16129
  );
15632
- return results;
16130
+ return picked.map((r) => ({ ...r, source: engine.name }));
15633
16131
  } finally {
15634
16132
  if (!holdOpen) await tab.close();
15635
16133
  }
@@ -15638,34 +16136,49 @@ var CdpSearchProvider = class {
15638
16136
  // (the page is mid-navigation after the solve, or the user closed the tab) is not a verdict;
15639
16137
  // the deadline is. The window goes back down only on success: on timeout it stays where the user
15640
16138
  // will find it, with the unsolved check on it.
15641
- async awaitSolve(tab, max, opts) {
16139
+ async awaitSolve(tab, engine, max, opts) {
15642
16140
  await tab.show();
15643
16141
  opts.onChallenge?.("raised");
15644
- debugLog("[cdp] bot check: window raised, waiting for the user");
16142
+ debugLog(`[cdp] ${engine.name} bot check: window raised, waiting for the user`);
15645
16143
  const deadline = Date.now() + this.waitMs;
15646
16144
  let last;
15647
16145
  for (; ; ) {
15648
16146
  await sleep2(this.pollMs);
15649
16147
  try {
15650
- last = parseExtraction(await tab.evaluate(extractionScript(max)));
15651
- if (!interstitial(last)) break;
16148
+ last = parsePage2(await tab.evaluate(collectScript()));
16149
+ if (!interstitial(engine, last, pickResults(last, engine, max).length)) break;
15652
16150
  } catch {
15653
16151
  }
15654
16152
  if (Date.now() >= deadline) {
15655
- debugLog("[cdp] bot check: not completed within the wait");
15656
- throw unavailable(last ?? { blocked: true }, true);
16153
+ debugLog(`[cdp] ${engine.name} bot check: not completed within the wait`);
16154
+ throw unavailable(engine, last, true);
15657
16155
  }
15658
16156
  }
15659
- debugLog("[cdp] bot check cleared");
16157
+ debugLog(`[cdp] ${engine.name} bot check cleared`);
15660
16158
  await tab.hide();
15661
16159
  opts.onChallenge?.("cleared");
15662
16160
  }
15663
16161
  };
15664
- function interstitial(data) {
15665
- return !!data.blocked || (data.results ?? []).length === 0 && (data.anchors ?? 0) < MIN_SERP_ANCHORS;
15666
- }
15667
- function unavailable(data, timedOut = false) {
15668
- const message = data.blocked ? "the search page served a bot check instead of results" : `the search page returned no result list (${data.anchors ?? 0} links on the page) \u2014 likely a challenge or interstitial`;
16162
+ function mergeResults(first, then, max) {
16163
+ const seen = new Set(first.map((r) => r.url));
16164
+ const out = [...first];
16165
+ for (const r of then) {
16166
+ if (out.length >= max) break;
16167
+ if (seen.has(r.url)) continue;
16168
+ seen.add(r.url);
16169
+ out.push(r);
16170
+ }
16171
+ return out.slice(0, max);
16172
+ }
16173
+ function challengeText(engine, page) {
16174
+ return SHARED_CHALLENGE_TEXT.test(page.bodyText) || engine.challengeText.test(page.bodyText);
16175
+ }
16176
+ function interstitial(engine, page, picked) {
16177
+ if (picked > 0) return false;
16178
+ return challengeText(engine, page) || page.anchors < engine.minAnchors;
16179
+ }
16180
+ function unavailable(engine, page, timedOut = false) {
16181
+ const message = !page || challengeText(engine, page) ? `the ${engine.name} search page served a bot check instead of results` : `the ${engine.name} search page returned no result list (${page.anchors} links on the page) \u2014 likely a challenge or interstitial`;
15669
16182
  return new SearchUnavailableError(
15670
16183
  message,
15671
16184
  timedOut ? "The search browser was challenged and the check was not completed in time. Its window is open on the challenge \u2014 complete the check once (it persists for that profile), then ask again." : void 0
@@ -15674,15 +16187,21 @@ function unavailable(data, timedOut = false) {
15674
16187
  function sleep2(ms) {
15675
16188
  return new Promise((r) => setTimeout(r, ms));
15676
16189
  }
15677
- function parseExtraction(raw) {
16190
+ function parsePage2(raw) {
15678
16191
  if (typeof raw !== "string") {
15679
16192
  throw new Error("the search page returned nothing to extract");
15680
16193
  }
16194
+ let page;
15681
16195
  try {
15682
- return JSON.parse(raw);
16196
+ page = JSON.parse(raw);
15683
16197
  } catch {
15684
16198
  throw new Error("could not parse results from the search page");
15685
16199
  }
16200
+ return {
16201
+ links: Array.isArray(page.links) ? page.links : [],
16202
+ anchors: typeof page.anchors === "number" ? page.anchors : 0,
16203
+ bodyText: typeof page.bodyText === "string" ? page.bodyText : ""
16204
+ };
15686
16205
  }
15687
16206
 
15688
16207
  // src/tools/index.ts
@@ -15693,7 +16212,7 @@ function defaultTools(config, opts = {}) {
15693
16212
  listTool,
15694
16213
  grepTool,
15695
16214
  globTool,
15696
- editTool,
16215
+ editToolForSession(),
15697
16216
  writeTool,
15698
16217
  bashTool,
15699
16218
  subagentTool,
@@ -15702,6 +16221,9 @@ function defaultTools(config, opts = {}) {
15702
16221
  if (askEnabled()) tools.push(askUserTool);
15703
16222
  return tools;
15704
16223
  }
16224
+ function editToolForSession() {
16225
+ return positionalEditsEnabled() ? positionalEditTool : editTool;
16226
+ }
15705
16227
  function webTools(config, opts) {
15706
16228
  if (opts.offline) return [];
15707
16229
  const tools = [fetchUrlTool];
@@ -15725,7 +16247,7 @@ function minimalTools() {
15725
16247
  return tools;
15726
16248
  }
15727
16249
  function grindTools(config, opts = {}) {
15728
- const tools = [readTool, editTool, grindBashTool];
16250
+ const tools = [readTool, editToolForSession(), grindBashTool];
15729
16251
  if (askEnabled()) tools.push(askUserTool);
15730
16252
  tools.push(...webTools(config, opts));
15731
16253
  return tools;
@@ -16539,14 +17061,25 @@ function observeNoteSlot(obs) {
16539
17061
 
16540
17062
  // src/agent/readtrace.ts
16541
17063
  var FILE_OVERLAP_DEPTH = 4;
17064
+ var DEPTH_WITHOUT_PROGRESS = 5;
16542
17065
  var MAX_NARROWINGS = 3;
16543
17066
  var ReadTrace = class {
17067
+ // Whether the tool message that carried an earlier fetch is gone from the request (shed or
17068
+ // folded). Without one, every earlier fetch stacks, as it did before.
17069
+ constructor(isGone = () => false) {
17070
+ this.isGone = isGone;
17071
+ }
17072
+ isGone;
16544
17073
  // Keyed (path, offset), limit-normalized — matches the loop's repeatKey. A model re-reading the
16545
17074
  // same start line with a different window is the same re-read, not forward paging to a new region.
16546
17075
  // The window is still carried in the entry (not the key) for the narrowing carve-out below, which
16547
17076
  // needs to compare against the previous request rather than fork a new region for every window.
16548
17077
  seen = /* @__PURE__ */ new Map();
16549
17078
  files = /* @__PURE__ */ new Map();
17079
+ // The region key of each file's latest fetch, so attachMessage can link that region too.
17080
+ lastKey = /* @__PURE__ */ new Map();
17081
+ // Bumped by each landed edit; a fetch is "since progress" while its epoch is the current one.
17082
+ epoch = 0;
16550
17083
  counts = {
16551
17084
  unique: 0,
16552
17085
  changed: 0,
@@ -16584,7 +17117,8 @@ var ReadTrace = class {
16584
17117
  repeats = 1;
16585
17118
  narrowings = prior.narrowings + 1;
16586
17119
  } else {
16587
- repeats = prior.repeats + 1;
17120
+ const priorGone = !!prior.msg && this.isGone(prior.msg);
17121
+ repeats = priorGone ? prior.repeats : prior.repeats + 1;
16588
17122
  cls = round - prior.round <= 1 ? "dup-live" : "dup-aged";
16589
17123
  narrowings = prior.narrowings;
16590
17124
  }
@@ -16598,6 +17132,7 @@ var ReadTrace = class {
16598
17132
  narrowings,
16599
17133
  lastLive: cls === "dup-live"
16600
17134
  });
17135
+ this.lastKey.set(path, key);
16601
17136
  this.counts[cls]++;
16602
17137
  this.recordFile(path, offset, window, hash, round, cls, via);
16603
17138
  return { cls, repeats };
@@ -16614,15 +17149,35 @@ var ReadTrace = class {
16614
17149
  const hi = window === Infinity ? Infinity : lo + window - 1;
16615
17150
  let f = this.files.get(path);
16616
17151
  if (!f || f.hash !== hash) {
16617
- f = { hash, ranges: [], depth: 0, lastRound: round, lastVia: via };
17152
+ f = {
17153
+ hash,
17154
+ ranges: [],
17155
+ depth: 0,
17156
+ lastRound: round,
17157
+ lastVia: via,
17158
+ depthSinceProgress: 0,
17159
+ lastProgressRound: round
17160
+ };
16618
17161
  this.files.set(path, f);
16619
17162
  }
16620
17163
  f.lastVia = via;
16621
17164
  if (cls !== "narrowed" && cls !== "regrounded") {
16622
- const points = [lo, ...f.ranges.map(([a]) => a).filter((a) => a >= lo && a <= hi)];
17165
+ const since = f.ranges.filter((r) => r.epoch === this.epoch);
17166
+ const sincePoints = [lo, ...since.map((r) => r.lo).filter((a) => a >= lo && a <= hi)];
17167
+ let sinceDepth = 1;
17168
+ for (const p of sincePoints) {
17169
+ const stacked = 1 + since.filter((r) => p >= r.lo && p <= r.hi).length;
17170
+ if (stacked > sinceDepth) sinceDepth = stacked;
17171
+ }
17172
+ if (sinceDepth >= f.depthSinceProgress || sinceDepth >= DEPTH_WITHOUT_PROGRESS) {
17173
+ f.depthSinceProgress = Math.max(f.depthSinceProgress, sinceDepth);
17174
+ f.lastProgressRound = round;
17175
+ }
17176
+ const held = f.ranges.filter((r) => !r.msg || !this.isGone(r.msg));
17177
+ const points = [lo, ...held.map((r) => r.lo).filter((a) => a >= lo && a <= hi)];
16623
17178
  let depth = 1;
16624
17179
  for (const p of points) {
16625
- const stacked = 1 + f.ranges.filter(([a, b]) => p >= a && p <= b).length;
17180
+ const stacked = 1 + held.filter((r) => p >= r.lo && p <= r.hi).length;
16626
17181
  if (stacked > depth) depth = stacked;
16627
17182
  }
16628
17183
  if (depth > f.depth) {
@@ -16632,7 +17187,20 @@ var ReadTrace = class {
16632
17187
  f.lastRound = round;
16633
17188
  }
16634
17189
  }
16635
- f.ranges.push([lo, hi]);
17190
+ f.ranges.push({ lo, hi, epoch: this.epoch });
17191
+ }
17192
+ // An edit, a write or a command that changed the tree landed: re-reads before it led somewhere.
17193
+ noteProgress() {
17194
+ this.epoch++;
17195
+ for (const f of this.files.values()) f.depthSinceProgress = 0;
17196
+ }
17197
+ // Links the latest fetch of `path` to the tool message that carried it, once that message exists.
17198
+ attachMessage(path, msg) {
17199
+ const last = this.files.get(path)?.ranges.at(-1);
17200
+ if (last && !last.msg) last.msg = msg;
17201
+ const key = this.lastKey.get(path);
17202
+ const entry = key === void 0 ? void 0 : this.seen.get(key);
17203
+ if (entry && !entry.msg) entry.msg = msg;
16636
17204
  }
16637
17205
  // Regions the model is looping on, re-read within the last `recentWithin` rounds of
16638
17206
  // `currentRound`. Two-tier threshold: a dup-live region (content still in context — re-reading it
@@ -16653,9 +17221,10 @@ var ReadTrace = class {
16653
17221
  const named = new Set(out.map((l) => l.path));
16654
17222
  for (const [path, f] of this.files) {
16655
17223
  if (named.has(path)) continue;
16656
- if (currentRound - f.lastRound > recentWithin) continue;
16657
- if (f.depth >= FILE_OVERLAP_DEPTH) {
17224
+ if (f.depth >= FILE_OVERLAP_DEPTH && currentRound - f.lastRound <= recentWithin) {
16658
17225
  out.push({ path, offset: 1, repeats: f.depth });
17226
+ } else if (f.depthSinceProgress >= DEPTH_WITHOUT_PROGRESS && currentRound - f.lastProgressRound <= recentWithin) {
17227
+ out.push({ path, offset: 1, repeats: f.depthSinceProgress });
16659
17228
  }
16660
17229
  }
16661
17230
  return out;
@@ -16673,8 +17242,12 @@ var ReadTrace = class {
16673
17242
  if (e.repeats >= 3) looped++;
16674
17243
  }
16675
17244
  let overlapped = 0;
16676
- for (const f of this.files.values()) if (f.depth >= FILE_OVERLAP_DEPTH) overlapped++;
16677
- return `unique=${c.unique} changed=${c.changed} dup-live=${c["dup-live"]} dup-aged=${c["dup-aged"]} narrowed=${c.narrowed} maxrepeat=${maxRepeat} looped=${looped} overlapped=${overlapped} regrounded=${c.regrounded}`;
17245
+ let refetched = 0;
17246
+ for (const f of this.files.values()) {
17247
+ if (f.depth >= FILE_OVERLAP_DEPTH) overlapped++;
17248
+ if (f.depthSinceProgress >= DEPTH_WITHOUT_PROGRESS) refetched++;
17249
+ }
17250
+ return `unique=${c.unique} changed=${c.changed} dup-live=${c["dup-live"]} dup-aged=${c["dup-aged"]} narrowed=${c.narrowed} maxrepeat=${maxRepeat} looped=${looped} overlapped=${overlapped} regrounded=${c.regrounded} refetched=${refetched}`;
16678
17251
  }
16679
17252
  };
16680
17253
  function priorCopyState(prior, history, prefixStable) {
@@ -16684,7 +17257,7 @@ function priorCopyState(prior, history, prefixStable) {
16684
17257
  }
16685
17258
 
16686
17259
  // src/agent/bashread.ts
16687
- import { createHash as createHash4 } from "node:crypto";
17260
+ import { createHash as createHash5 } from "node:crypto";
16688
17261
  import { readFile as readFile12, realpath as realpath2, stat as stat6 } from "node:fs/promises";
16689
17262
  import { isAbsolute as isAbsolute6, relative as relative13 } from "node:path";
16690
17263
  var CAT_FLAGS = /^-[nbsuvetAE]+$/;
@@ -16806,7 +17379,7 @@ async function traceBashRead(command, cwd) {
16806
17379
  const info = await stat6(full);
16807
17380
  if (!info.isFile() || info.size > MAX_TRACED_BYTES) return void 0;
16808
17381
  const text = await readFile12(full, "utf8");
16809
- const hash = createHash4("sha1").update(text).digest("hex");
17382
+ const hash = createHash5("sha1").update(text).digest("hex");
16810
17383
  const path = await traceKey(cwd, full);
16811
17384
  const r = parsed.range;
16812
17385
  if ("last" in r) {
@@ -17702,6 +18275,38 @@ function shouldSuppressGrounding(missing, refs) {
17702
18275
  return missingCount >= SUPPRESS_MIN_MISSING && missingCount / total >= SUPPRESS_FRACTION;
17703
18276
  }
17704
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
+
17705
18310
  // src/agent/readfirst.ts
17706
18311
  import { readFile as readFile14 } from "node:fs/promises";
17707
18312
  import { relative as relative15, resolve as resolve9 } from "node:path";
@@ -17780,7 +18385,7 @@ var MIN_PROBE_CHARS = 12;
17780
18385
  function probeLine(excerpt) {
17781
18386
  let best;
17782
18387
  for (const raw of excerpt.split("\n")) {
17783
- const line = raw.replace(/^\s*\d+│/, "").trim();
18388
+ const line = raw.replace(GUTTER_PREFIX_RE, "").trim();
17784
18389
  if (line.length >= MIN_PROBE_CHARS && (best === void 0 || line.length > best.length)) {
17785
18390
  best = line;
17786
18391
  }
@@ -17820,6 +18425,13 @@ async function oldStringProvesBytes(cwd, path, oldStr, newStr) {
17820
18425
  return false;
17821
18426
  }
17822
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
+ }
17823
18435
  function buildReadFirstDirective(path) {
17824
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.)";
17825
18437
  }
@@ -17969,7 +18581,7 @@ function planPressureLine(pressure, basis) {
17969
18581
 
17970
18582
  // src/check/typecheck.ts
17971
18583
  import { spawn as spawn5 } from "node:child_process";
17972
- import { createHash as createHash5 } from "node:crypto";
18584
+ import { createHash as createHash6 } from "node:crypto";
17973
18585
  import { stat as stat8 } from "node:fs/promises";
17974
18586
  import { tmpdir as tmpdir2 } from "node:os";
17975
18587
  import { dirname as dirname9, isAbsolute as isAbsolute7, join as join17, relative as relative16, resolve as resolve10 } from "node:path";
@@ -18077,7 +18689,7 @@ async function resolveTscBin(cwd) {
18077
18689
  return await stat8(bin).catch(() => null) ? bin : null;
18078
18690
  }
18079
18691
  function defaultBuildInfoFile(cwd) {
18080
- const h = createHash5("sha1").update(cwd).digest("hex").slice(0, 16);
18692
+ const h = createHash6("sha1").update(cwd).digest("hex").slice(0, 16);
18081
18693
  return join17(tmpdir2(), `reika-tsc-${h}.tsbuildinfo`);
18082
18694
  }
18083
18695
  async function runTypecheck(cwd, opts = {}) {
@@ -18184,15 +18796,46 @@ function runTscProcess(bin, args, cwd, timeoutMs, signal, viaSandboxWrapper = fa
18184
18796
  var TRACKED_TOOLS = /* @__PURE__ */ new Set(["read", "grep", "list", "glob", "bash"]);
18185
18797
  var WEB_LOOKUP_ARG = { search: "query", fetch_url: "url" };
18186
18798
  var MUTATING_TOOLS = /* @__PURE__ */ new Set(["write", "edit"]);
18187
- function willMutate(name, args, cwd) {
18188
- if (MUTATING_TOOLS.has(name)) return true;
18189
- if (name !== "bash") return false;
18190
- return writeTargets(String(args.command ?? ""), cwd).length > 0;
18799
+ var TYPE_INERT_EXTENSIONS = /* @__PURE__ */ new Set([
18800
+ "md",
18801
+ "mdx",
18802
+ "markdown",
18803
+ "txt",
18804
+ "rst",
18805
+ "css",
18806
+ "scss",
18807
+ "sass",
18808
+ "less",
18809
+ "html",
18810
+ "svg",
18811
+ "png",
18812
+ "jpg",
18813
+ "jpeg",
18814
+ "gif",
18815
+ "webp",
18816
+ "ico",
18817
+ "yml",
18818
+ "yaml",
18819
+ "toml"
18820
+ ]);
18821
+ function isTypeInertPath(path) {
18822
+ const base = path.slice(path.lastIndexOf("/") + 1);
18823
+ const dot = base.lastIndexOf(".");
18824
+ return dot > 0 && TYPE_INERT_EXTENSIONS.has(base.slice(dot + 1).toLowerCase());
18825
+ }
18826
+ function typeRelevantTargets(name, args, cwd) {
18827
+ if (MUTATING_TOOLS.has(name)) {
18828
+ const path = typeof args.path === "string" ? args.path : "";
18829
+ return isTypeInertPath(path) ? [] : [path];
18830
+ }
18831
+ if (name !== "bash") return [];
18832
+ return writeTargets(String(args.command ?? ""), cwd).filter((t) => !isTypeInertPath(t));
18833
+ }
18834
+ function mayAffectTypes(name, args, cwd) {
18835
+ return typeRelevantTargets(name, args, cwd).length > 0;
18191
18836
  }
18192
18837
  function typecheckAnchor(name, args, cwd) {
18193
- if (MUTATING_TOOLS.has(name)) return typeof args.path === "string" ? args.path : void 0;
18194
- if (name !== "bash") return void 0;
18195
- return writeTargets(String(args.command ?? ""), cwd)[0];
18838
+ return typeRelevantTargets(name, args, cwd)[0] || void 0;
18196
18839
  }
18197
18840
  function didMutate(name, changes) {
18198
18841
  if (MUTATING_TOOLS.has(name)) return true;
@@ -18446,7 +19089,10 @@ function promptGates(tools, sandbox, unattended) {
18446
19089
  canSubagent: has("subagent"),
18447
19090
  sandbox: sandbox && has("bash") && sandboxExecAvailable(),
18448
19091
  canFetch: has("fetch_url"),
18449
- canSearch: has("search")
19092
+ canSearch: has("search"),
19093
+ canEditByPosition: tools.some(
19094
+ (t) => t.name === "edit" && "insert_after" in (t.parameters.properties ?? {})
19095
+ )
18450
19096
  };
18451
19097
  }
18452
19098
  function buildRoundZeroPrefix(opts) {
@@ -18507,34 +19153,55 @@ function withdrawalRemedy(toolNames) {
18507
19153
  }
18508
19154
  return "Answer from what you already have";
18509
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
+ }
19160
+ function withdrawalReturn(toolNames) {
19161
+ if (toolNames.has("edit") || toolNames.has("write")) {
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.";
19163
+ }
19164
+ if (toolNames.has("bash")) {
19165
+ return "The pause is temporary: reading comes back once a command changes an existing file (a new file does not count), or after a few rounds.";
19166
+ }
19167
+ return "The pause is temporary: reading comes back after a few rounds.";
19168
+ }
18510
19169
  function withdrawnLedgerLines(toolNames) {
18511
19170
  if (toolNames.has("edit") || toolNames.has("write")) {
18512
19171
  return [
18513
19172
  "Reading and searching are now PAUSED. Make the edit the task requires with the edit/write",
18514
19173
  "tools, state specifically what is still blocking you, or \u2014 if the change is already complete \u2014",
18515
- "say so and stop."
19174
+ "say so and stop.",
19175
+ ...positionalPauseHint(toolNames) ? [positionalPauseHint(toolNames)] : [],
19176
+ withdrawalReturn(toolNames)
18516
19177
  ];
18517
19178
  }
18518
19179
  if (toolNames.has("bash")) {
18519
19180
  return [
18520
19181
  "Reading and searching are now PAUSED. Make the change the task requires by running the",
18521
19182
  "command that applies it, state specifically what is still blocking you, or \u2014 if the change",
18522
- "is already complete \u2014 say so and stop."
19183
+ "is already complete \u2014 say so and stop.",
19184
+ withdrawalReturn(toolNames)
18523
19185
  ];
18524
19186
  }
18525
19187
  return [
18526
19188
  "Reading and searching are now PAUSED. Answer from what you already have, state specifically",
18527
- "what is still blocking you, or \u2014 if the change is already complete \u2014 say so and stop."
19189
+ "what is still blocking you, or \u2014 if the change is already complete \u2014 say so and stop.",
19190
+ withdrawalReturn(toolNames)
18528
19191
  ];
18529
19192
  }
18530
19193
  function buildWithdrawalDirective(toolNames) {
18531
- 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)})`;
18532
19195
  }
18533
19196
  function shouldWithdrawInspection(opts) {
18534
19197
  if (opts.loopActiveRounds < LOOP_WITHDRAW_AFTER) return false;
18535
19198
  return !opts.editRecovery;
18536
19199
  }
18537
19200
  var WITHDRAW_HOLD_ROUNDS = 4;
19201
+ function liftsWithdrawal(name, changes) {
19202
+ if (name === "edit") return true;
19203
+ return name === "bash" && !!changes && changes.files.some((f) => f.kind !== "created");
19204
+ }
18538
19205
  function holdWithdrawal(opts) {
18539
19206
  if (opts.since === void 0 || opts.mutated || opts.editRecovery) return false;
18540
19207
  return opts.round - opts.since < WITHDRAW_HOLD_ROUNDS;
@@ -18565,17 +19232,27 @@ function prefixed(ledger) {
18565
19232
  return ledger ? "\n" + ledger : "";
18566
19233
  }
18567
19234
  function droppedPayloadLedgerFor(history, prefixStable) {
18568
- return DROPPED_LEDGER && hasDroppedPayloads(history, prefixStable) ? buildDroppedPayloadLedger() : "";
19235
+ if (!DROPPED_LEDGER) return "";
19236
+ const dropped = droppedPayloadMessages(history, prefixStable);
19237
+ return dropped.length ? buildDroppedPayloadLedger(dropped.map((m) => m.role === "tool" ? m.summary : "")) : "";
18569
19238
  }
19239
+ var DROPPED_LEDGER_MAX_LISTED = 8;
19240
+ var DROPPED_LEDGER_SUMMARY_CHARS = 100;
18570
19241
  var DROPPED_LEDGER_MARKER = "Their output was dropped to make room";
18571
- function buildDroppedPayloadLedger() {
19242
+ function buildDroppedPayloadLedger(summaries) {
19243
+ const newest = summaries.slice(-DROPPED_LEDGER_MAX_LISTED).reverse();
19244
+ const earlier = summaries.length - newest.length;
19245
+ const clip = (s) => s.length > DROPPED_LEDGER_SUMMARY_CHARS ? `${s.slice(0, DROPPED_LEDGER_SUMMARY_CHARS - 1)}\u2026` : s;
18572
19246
  return [
18573
- "--- reika status (auto-generated \u2014 not user input) ---",
18574
- "Some tool results above now show only their summary line (e.g. `Ran: \u2026 (505 bytes output)`)",
18575
- `or a short outline of the output. ${DROPPED_LEDGER_MARKER}; it is not in your context`,
18576
- "any more. That is a context limit, not a failed command, and it does not mean you already",
18577
- "handled the result. If you need what one of them returned, re-run that call \u2014 do not answer",
18578
- "from memory of it."
19247
+ "--- reika status (auto-generated \u2014 not user input; repeated every round, not a new message) ---",
19248
+ "These tool results above now show only their summary line or a short outline.",
19249
+ `${DROPPED_LEDGER_MARKER}; it is not in your context any more:`,
19250
+ ...newest.map((s) => `- ${clip(s)}`),
19251
+ ...earlier > 0 ? [`- and ${earlier} earlier`] : [],
19252
+ "Every other tool result above, including the newest, is still in your context as shown. This is",
19253
+ "a context limit, not a failed command, and it does not mean you already handled those results.",
19254
+ "If you still need what one of them returned, re-run that call \u2014 do not answer from memory of",
19255
+ "it, and do not re-run calls whose output you still have."
18579
19256
  ].join("\n");
18580
19257
  }
18581
19258
  function buildQuestionLedger(answers) {
@@ -18622,6 +19299,10 @@ ${failure.excerpt}
18622
19299
 
18623
19300
  Build your next old_string character-for-character from the text above \u2014 only what follows the \`NNNNN\u2502\` gutter, indentation included. If the change belongs elsewhere, read ${failure.path} instead of guessing again.)`;
18624
19301
  }
19302
+ function formatShedNotice(shed, outputs) {
19303
+ const noun = outputs === 1 ? "tool output is" : "tool outputs are";
19304
+ return `Context trimmed (shed ${shed}) \u2014 ${outputs} older ${noun} now summary-only to the model (still shown here; it re-reads what it needs).`;
19305
+ }
18625
19306
  async function runTurn(opts) {
18626
19307
  if (!opts.manualCompact) {
18627
19308
  const userMsg = {
@@ -18715,10 +19396,11 @@ ${SUBAGENT_REPORT_FRAME}` : promptForMode;
18715
19396
  let planGateRounds = 0;
18716
19397
  const seenReadOnly = /* @__PURE__ */ new Map();
18717
19398
  const seenWebLookups = /* @__PURE__ */ new Set();
18718
- const readTrace = new ReadTrace();
19399
+ const readTrace = new ReadTrace((m) => priorCopyState(m, opts.history, prefixStable) === "yes");
18719
19400
  const lastReadMessage = /* @__PURE__ */ new Map();
18720
19401
  const prevAgedField = (cls, key) => cls === "dup-live" || cls === "dup-aged" ? ` prevAged=${priorCopyState(lastReadMessage.get(key), opts.history, prefixStable)}` : "";
18721
19402
  const readFirst = new ReadFirstGate(opts.bundle.cwd);
19403
+ const refusedArgEchoes = /* @__PURE__ */ new Set();
18722
19404
  const reasoningTrace = new ReasoningTrace();
18723
19405
  let reasoningLoopActive = false;
18724
19406
  let reasoningChannel = "reasoning";
@@ -18796,7 +19478,10 @@ ${SUBAGENT_REPORT_FRAME}` : promptForMode;
18796
19478
  debugLog(`[reika:debug] plan-handoff folded=${folded} reason=${reason}
18797
19479
  `);
18798
19480
  }
18799
- const planSteps = opts.promptMode === "agent" ? seedPlanProgress(opts.history) : null;
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;
18800
19485
  if (planSteps) {
18801
19486
  opts.onPlanProgress?.(planSteps);
18802
19487
  debugLog(
@@ -19043,6 +19728,97 @@ ${SUBAGENT_REPORT_FRAME}` : promptForMode;
19043
19728
  return;
19044
19729
  }
19045
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
+ }
19046
19822
  const suffixParts = [];
19047
19823
  const droppedLedger = droppedPayloadLedgerFor(opts.history, prefixStable);
19048
19824
  if (droppedLedger) suffixParts.push(droppedLedger);
@@ -19305,6 +20081,7 @@ ${COMPACTION_REPORT_RETRY}`, refusedCallTurn(rep));
19305
20081
  }
19306
20082
  }
19307
20083
  let agedThisRound = false;
20084
+ let agedOutputs = 0;
19308
20085
  if (prefixStable && window && !planForceWrite) {
19309
20086
  const aged = batchAgePayloads(
19310
20087
  opts.history,
@@ -19318,9 +20095,10 @@ ${COMPACTION_REPORT_RETRY}`, refusedCallTurn(rep));
19318
20095
  !latchesFor(opts.config).reasoningRoundtrip
19319
20096
  );
19320
20097
  agedThisRound = aged.marked > 0;
20098
+ agedOutputs = aged.bulk + aged.crumbs;
19321
20099
  if (aged.marked > 0) {
19322
20100
  debugLog(
19323
- `[reika:debug] round=${i} prefix-stable batch-age marked=${aged.marked} bulk=${aged.bulk} crumbs=${aged.crumbs} kept=${aged.kept} short=${aged.short}
20101
+ `[reika:debug] round=${i} prefix-stable batch-age marked=${aged.marked} bulk=${aged.bulk} crumbs=${aged.crumbs} args=${aged.args} kept=${aged.kept} short=${aged.short}
19324
20102
  `
19325
20103
  );
19326
20104
  shrink.sheds++;
@@ -19355,6 +20133,14 @@ ${COMPACTION_REPORT_RETRY}`, refusedCallTurn(rep));
19355
20133
  });
19356
20134
  }
19357
20135
  }
20136
+ if (agedOutputs > 0 && lastFoldRemoved === 0) {
20137
+ opts.onMessage({
20138
+ role: "system",
20139
+ tone: "info",
20140
+ emphasis: "line",
20141
+ content: formatShedNotice(shrink.sheds, agedOutputs)
20142
+ });
20143
+ }
19358
20144
  if (opts.manualCompact) {
19359
20145
  if (lastFoldRemoved === 0) {
19360
20146
  opts.onMessage({
@@ -19398,7 +20184,7 @@ ${roundSuffix}` : dropped;
19398
20184
  if (opts.signal.aborted) callAbort.abort();
19399
20185
  else opts.signal.addEventListener("abort", () => callAbort.abort(), { once: true });
19400
20186
  }
19401
- const canAbortVerbatim = VERBATIM_ABORT && (verbatimRecoveries < MAX_VERBATIM_RECOVERIES || steerRetryActive);
20187
+ const canAbortVerbatim = VERBATIM_ABORT && !subagentForceReport && (verbatimRecoveries < MAX_VERBATIM_RECOVERIES || steerRetryActive);
19402
20188
  const trackSpin = !!opts.onReasoningStatus || debugEnabled() || canAbortVerbatim;
19403
20189
  const onReasoningDelta = trackSpin ? (delta) => {
19404
20190
  opts.onReasoningDelta?.(delta);
@@ -19505,10 +20291,10 @@ ${roundSuffix}` : dropped;
19505
20291
  // outline, and how many were small enough that keeping them whole cost less than the marker.
19506
20292
  // Silent when nothing is aged yet, so early rounds add no noise.
19507
20293
  onAgedStats: debugEnabled() ? (a) => {
19508
- const total = a.summary + a.diff + a.outline + a.whole + a.report;
20294
+ const total = a.summary + a.diff + a.outline + a.whole + a.report + a.command;
19509
20295
  if (total === 0) return;
19510
20296
  debugLog(
19511
- `[reika:debug] aged-payload round=${i} aged=${total} summary=${a.summary} diff=${a.diff} outline=${a.outline} whole=${a.whole} report=${a.report}
20297
+ `[reika:debug] aged-payload round=${i} aged=${total} summary=${a.summary} diff=${a.diff} outline=${a.outline} whole=${a.whole} report=${a.report} command=${a.command}
19512
20298
  `
19513
20299
  );
19514
20300
  } : void 0,
@@ -19726,7 +20512,7 @@ ${rsn}` : rsn;
19726
20512
  ${roundText}` : roundText;
19727
20513
  const cutOffMidThought = response.finishReason === "length" && isFinal;
19728
20514
  let continueRound = false;
19729
- if (CONTINUE && cutOffMidThought && carriedBlock.trim()) {
20515
+ if (CONTINUE && cutOffMidThought && carriedBlock.trim() && !subagentForceReport) {
19730
20516
  const gate = continuationGate(carriedBlock);
19731
20517
  const allow = continuation.allow(roundText);
19732
20518
  continueRound = gate.continuable && allow.ok;
@@ -19781,7 +20567,7 @@ ${response.content}`,
19781
20567
  }
19782
20568
  pendingContinuation = "";
19783
20569
  pendingReasoning = "";
19784
- if (shouldRetryTruncated({
20570
+ if (!subagentForceReport && shouldRetryTruncated({
19785
20571
  finishReason: response.finishReason,
19786
20572
  hasToolCalls: !isFinal,
19787
20573
  priorRetries: lengthRetries
@@ -19885,7 +20671,7 @@ ${response.content}`,
19885
20671
  });
19886
20672
  }
19887
20673
  if (isFinal) {
19888
- if (!assistantContent?.trim() && response.finishReason !== "length" && !opts.signal?.aborted) {
20674
+ if (!assistantContent?.trim() && response.finishReason !== "length" && !subagentForceReport && !opts.signal?.aborted) {
19889
20675
  const retry = emptyReplyRetries < MAX_EMPTY_REPLY_RETRIES;
19890
20676
  debugLog(`[reika:debug] round=${i} empty-reply retry=${retry}
19891
20677
  `);
@@ -19900,7 +20686,12 @@ ${response.content}`,
19900
20686
  continue;
19901
20687
  }
19902
20688
  }
19903
- if (typecheckEnabled && typecheckBaseline !== null && !opts.signal?.aborted) {
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) {
19904
20695
  const final = await typecheck();
19905
20696
  const decision = decideTypecheckGate({
19906
20697
  baseline: typecheckBaseline,
@@ -19928,7 +20719,7 @@ ${response.content}`,
19928
20719
  });
19929
20720
  }
19930
20721
  }
19931
- if (PLAN_ALIGN && planSteps && editingStarted && opts.promptMode === "agent" && !opts.signal?.aborted) {
20722
+ if (PLAN_ALIGN && planSteps && editingStarted && !subagentForceReport && opts.promptMode === "agent" && !opts.signal?.aborted) {
19932
20723
  const gate = decidePlanGate({
19933
20724
  steps: planSteps,
19934
20725
  gateRounds: planGateRounds,
@@ -19945,14 +20736,10 @@ ${response.content}`,
19945
20736
  continue;
19946
20737
  }
19947
20738
  if (gate.action === "waive") {
19948
- const waived = waiveUnchecked(planSteps);
20739
+ waiveUnchecked(planSteps);
20740
+ recordPlanSettled(opts.history, planSteps);
19949
20741
  opts.onPlanProgress?.(planSteps);
19950
- opts.onMessage({
19951
- role: "system",
19952
- tone: "warn",
19953
- content: gate.userNotice ?? "",
19954
- planWaived: waived
19955
- });
20742
+ opts.onMessage({ role: "system", tone: "warn", content: gate.userNotice ?? "" });
19956
20743
  }
19957
20744
  }
19958
20745
  if (opts.promptMode === "plan" && opts.allowRefine !== false && parsePlanSteps(assistantContent ?? "").length > 0) {
@@ -19991,15 +20778,19 @@ ${response.content}`,
19991
20778
  const refused = withdrawInspection && (INSPECTION_TOOLS.has(call.name) || refusedBashGrep);
19992
20779
  const heldForSubagent = subagentInRound && !refused && call.name !== "subagent" && (INSPECTION_TOOLS.has(call.name) || refusedBashGrep);
19993
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);
19994
- const provenEdit = READ_FIRST_EXACT && blindEdit && await oldStringProvesBytes(
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(
19995
20783
  opts.bundle.cwd,
19996
20784
  String(call.args.path),
19997
20785
  String(call.args.old_string ?? ""),
19998
20786
  String(call.args.new_string ?? "")
19999
- );
20787
+ ));
20000
20788
  if (provenEdit) debugLog(`[reika:debug] round=${i} read-first proven ${call.args.path}
20001
20789
  `);
20002
20790
  const bouncedBlindEdit = blindEdit && !provenEdit && readFirst.shouldBounce(String(call.args.path), opts.history, prefixStable);
20791
+ const echoKey = `${call.name}\0${JSON.stringify(call.args)}`;
20792
+ const refusedArgEcho = tool !== void 0 && !refused && !bouncedBlindEdit && !heldForSubagent && !refusedArgEchoes.has(echoKey) && agedArgEcho(call.args) && opts.history.some((m) => m.role === "assistant" && m.argsAged);
20793
+ if (refusedArgEcho) refusedArgEchoes.add(echoKey);
20003
20794
  let summary;
20004
20795
  let payload;
20005
20796
  let diff;
@@ -20015,7 +20806,7 @@ ${response.content}`,
20015
20806
  let groundsAuthored = false;
20016
20807
  let traceKey2;
20017
20808
  let planCheckoff;
20018
- if (typecheckEnabled && !typecheckBaselineAttempted && tool && !refused && !bouncedBlindEdit && willMutate(call.name, call.args, opts.bundle.cwd)) {
20809
+ if (typecheckEnabled && !typecheckBaselineAttempted && tool && !refused && !bouncedBlindEdit && !refusedArgEcho && mayAffectTypes(call.name, call.args, opts.bundle.cwd)) {
20019
20810
  typecheckBaselineAttempted = true;
20020
20811
  typecheckTsconfig = await detectTsProject(
20021
20812
  opts.bundle.cwd,
@@ -20041,7 +20832,7 @@ ${response.content}`,
20041
20832
  summary = `edit paused \u2014 read ${blindPath} first, then re-issue the edit`;
20042
20833
  payload = buildReadFirstDirective(blindPath);
20043
20834
  if (debugEnabled()) {
20044
- const probe = await probeWouldLand(
20835
+ const probe = hasPositionArgs(call.args) ? "would-land=no match=position" : await probeWouldLand(
20045
20836
  opts.bundle.cwd,
20046
20837
  blindPath,
20047
20838
  String(call.args.old_string ?? ""),
@@ -20050,6 +20841,11 @@ ${response.content}`,
20050
20841
  debugLog(`[reika:debug] round=${i} read-first bounce ${blindPath} ${probe}
20051
20842
  `);
20052
20843
  }
20844
+ } else if (refusedArgEcho) {
20845
+ summary = `${call.name} not run \u2014 it contains a placeholder for text sent earlier`;
20846
+ payload = AGED_ARG_ECHO_DIRECTIVE;
20847
+ debugLog(`[reika:debug] round=${i} age-args-echo refused tool=${call.name}
20848
+ `);
20053
20849
  } else if (heldForSubagent) {
20054
20850
  const label = refusedBashGrep ? "shell inspection" : call.name;
20055
20851
  summary = `${label} held \u2014 the subagent dispatched this round covers it`;
@@ -20062,6 +20858,10 @@ ${response.content}`,
20062
20858
  if (spillStatsEnabled() && Object.values(call.args).some((v) => typeof v === "string" && referencesSpill(v))) {
20063
20859
  recordFollowed({ by: call.name });
20064
20860
  }
20861
+ if (refusedArgEchoes.has(echoKey)) {
20862
+ debugLog(`[reika:debug] round=${i} age-args-echo resent tool=${call.name}
20863
+ `);
20864
+ }
20065
20865
  opts.onToolStart?.(call.name);
20066
20866
  const callStart = Date.now();
20067
20867
  try {
@@ -20140,6 +20940,7 @@ ${grounding}` : grounding;
20140
20940
  const tracePath = traceReadPath(opts.bundle.cwd, String(call.args.path ?? ""));
20141
20941
  const traceOffset = Number(call.args.offset ?? 1);
20142
20942
  traceKey2 = `${tracePath}\0${traceOffset}`;
20943
+ if (!editingStarted) filesReadBeforeEdit.add(tracePath);
20143
20944
  const { cls, repeats } = readTrace.record(
20144
20945
  tracePath,
20145
20946
  traceOffset,
@@ -20156,6 +20957,7 @@ ${grounding}` : grounding;
20156
20957
  } else if (shellRead) {
20157
20958
  groundsPath = shellRead.path;
20158
20959
  traceKey2 = `${shellRead.path}\0${shellRead.offset}`;
20960
+ if (!editingStarted) filesReadBeforeEdit.add(shellRead.path);
20159
20961
  const { cls, repeats } = readTrace.record(
20160
20962
  shellRead.path,
20161
20963
  shellRead.offset,
@@ -20172,16 +20974,26 @@ ${grounding}` : grounding;
20172
20974
  debugLog(`[reika:debug] tool-call round=${i} ${call.name} ${summary}
20173
20975
  `);
20174
20976
  }
20175
- if (tool && !refused && !bouncedBlindEdit && !heldForSubagent)
20977
+ if (tool && !refused && !bouncedBlindEdit && !heldForSubagent && !refusedArgEcho)
20176
20978
  payload = flagRepeatedCall(seenReadOnly, call.name, call.args, summary, payload);
20177
20979
  if (tool && !refused && payload && WEB_LOOKUP_ARG[call.name]) {
20178
20980
  seenWebLookups.add(`${call.name}\0${String(call.args[WEB_LOOKUP_ARG[call.name]] ?? "")}`);
20179
20981
  }
20180
- if (!bouncedBlindEdit && didMutate(call.name, changes)) {
20982
+ if (!bouncedBlindEdit && !refusedArgEcho && didMutate(call.name, changes)) {
20181
20983
  editingStarted = true;
20182
- mutatedSinceWithdrawal = true;
20984
+ if (!MUTATING_TOOLS.has(call.name) || /^(Edited|Wrote) /.test(summary))
20985
+ readTrace.noteProgress();
20183
20986
  }
20184
- if (!bouncedBlindEdit && MUTATING_TOOLS.has(call.name)) {
20987
+ if (!bouncedBlindEdit && !refusedArgEcho && liftsWithdrawal(call.name, changes))
20988
+ mutatedSinceWithdrawal = true;
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
+ }
20185
20997
  if (summary.startsWith("Edited ") || summary.startsWith("Wrote ")) {
20186
20998
  lastEditFailed = false;
20187
20999
  lastEditFailure = void 0;
@@ -20191,7 +21003,12 @@ ${grounding}` : grounding;
20191
21003
  groundsAuthored = call.name === "write";
20192
21004
  }
20193
21005
  if (planSteps) {
20194
- const match = applyEdit(planSteps, diff?.path ?? summary.split(" ")[1], diff?.text);
21006
+ const match = applyEdit(
21007
+ planSteps,
21008
+ diff?.path ?? summary.split(" ")[1],
21009
+ diff?.text,
21010
+ diff
21011
+ );
20195
21012
  if (match) {
20196
21013
  opts.onPlanProgress?.(planSteps);
20197
21014
  const done = planSteps.filter((s) => s.done).length;
@@ -20206,11 +21023,7 @@ ${grounding}` : grounding;
20206
21023
  }
20207
21024
  }
20208
21025
  if (planSteps && call.name === "bash" && changes) {
20209
- let match = null;
20210
- for (const f of changes.files) {
20211
- const hit = applyEdit(planSteps, f.path, f.hunks.map((hk) => hk.text).join("\n"));
20212
- if (hit) match = hit;
20213
- }
21026
+ const match = applyTreeChanges(planSteps, changes);
20214
21027
  if (match) {
20215
21028
  opts.onPlanProgress?.(planSteps);
20216
21029
  const done = planSteps.filter((s) => s.done).length;
@@ -20242,7 +21055,10 @@ ${grounding}` : grounding;
20242
21055
  };
20243
21056
  opts.history.push(toolMsg);
20244
21057
  opts.onMessage(toolMsg);
20245
- if (traceKey2) lastReadMessage.set(traceKey2, toolMsg);
21058
+ if (traceKey2) {
21059
+ lastReadMessage.set(traceKey2, toolMsg);
21060
+ readTrace.attachMessage(traceKey2.slice(0, traceKey2.indexOf("\0")), toolMsg);
21061
+ }
20246
21062
  if (groundsPath) {
20247
21063
  readFirst.ground(groundsPath, groundsAuthored ? void 0 : opts.history.length - 1);
20248
21064
  }
@@ -21654,14 +22470,14 @@ function truncate2(s, max) {
21654
22470
  }
21655
22471
 
21656
22472
  // src/store/sessions.ts
21657
- import { createHash as createHash6, randomBytes as randomBytes4 } from "node:crypto";
22473
+ import { createHash as createHash7, randomBytes as randomBytes4 } from "node:crypto";
21658
22474
  import { open, mkdir as mkdir3, readdir as readdir8, readFile as readFile15, rename, writeFile as writeFile4 } from "node:fs/promises";
21659
22475
  import { homedir as homedir13 } from "node:os";
21660
22476
  import { basename as basename4, join as join19 } from "node:path";
21661
22477
  var ROOT_HISTORY_DIR = join19(homedir13(), ".config", "reika", "history");
21662
22478
  function projectHistoryDir(cwd, root = ROOT_HISTORY_DIR) {
21663
22479
  const slug2 = basename4(cwd).replace(/[^A-Za-z0-9._-]/g, "_") || "root";
21664
- const hash = createHash6("sha1").update(cwd).digest("hex").slice(0, 8);
22480
+ const hash = createHash7("sha1").update(cwd).digest("hex").slice(0, 8);
21665
22481
  return join19(root, "projects", `${slug2}-${hash}`);
21666
22482
  }
21667
22483
  function newSessionPath(dir, startedAt, stem = sessionStem(startedAt)) {
@@ -21853,8 +22669,8 @@ export {
21853
22669
  modeSide,
21854
22670
  resolveModeCommand,
21855
22671
  latchesFor,
21856
- callModel,
21857
22672
  estimateRequestTokens,
22673
+ callModel,
21858
22674
  HIDDEN_TOOL_ARGS,
21859
22675
  formatElapsed,
21860
22676
  turnEndLabel,