@alexwkleung/reika 0.14.0 → 0.15.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
@@ -4705,6 +4705,26 @@ var BUDGET_SAFETY = 0.9;
4705
4705
  var CAP_DENSITY_FLOOR = 2.5;
4706
4706
  var SENT_DENSITY_FLOOR = 1;
4707
4707
  var DEDUP_PAYLOADS = process.env.REIKA_DEDUP_PAYLOADS !== "0";
4708
+ var AGE_CALL_ARGS = process.env.REIKA_AGE_ARGS !== "0";
4709
+ var AGED_ARGS_MIN_CHARS = 300;
4710
+ var AGED_ARG_STRING_MIN_CHARS = 120;
4711
+ var AGED_BASH_HEAD_CHARS = 160;
4712
+ var AGED_ARG_STUB_RE = /chars, sent earlier\]/;
4713
+ function agedArgEcho(args) {
4714
+ return AGED_ARG_STUB_RE.test(JSON.stringify(args));
4715
+ }
4716
+ 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.)';
4717
+ function stubCallArgs(name, args) {
4718
+ if (JSON.stringify(args).length < AGED_ARGS_MIN_CHARS) return args;
4719
+ const out = {};
4720
+ for (const [k, v] of Object.entries(args)) {
4721
+ if (typeof v !== "string" || v.length < AGED_ARG_STRING_MIN_CHARS) out[k] = v;
4722
+ else if (name === "bash" && k === "command")
4723
+ out[k] = `${v.split("\n")[0].slice(0, AGED_BASH_HEAD_CHARS)} \u2026[${v.length} chars, sent earlier]`;
4724
+ else out[k] = `[${v.length} chars, sent earlier]`;
4725
+ }
4726
+ return out;
4727
+ }
4708
4728
  var DEDUP_PAYLOAD_STUB = "(reika: identical to an earlier result above \u2014 body omitted, you already have it)";
4709
4729
  var DEDUP_TRAIL_STUB = "(reika: repeat of an earlier identical result \u2014 omitted)";
4710
4730
  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;
@@ -4826,7 +4846,14 @@ ${recapText}` : system;
4826
4846
  }
4827
4847
  return capPayload(payload, cap);
4828
4848
  };
4829
- const agedStats = { summary: 0, diff: 0, outline: 0, whole: 0, report: 0 };
4849
+ const agedStats = {
4850
+ summary: 0,
4851
+ diff: 0,
4852
+ outline: 0,
4853
+ whole: 0,
4854
+ report: 0,
4855
+ command: 0
4856
+ };
4830
4857
  const serializeAged = (msg, i) => {
4831
4858
  const { content, kind } = agedToolContent(msg, keptWhole.has(i));
4832
4859
  agedStats[kind]++;
@@ -4855,7 +4882,7 @@ ${recapText}` : system;
4855
4882
  type: "function",
4856
4883
  function: {
4857
4884
  name: tc.name,
4858
- arguments: JSON.stringify(tc.args)
4885
+ arguments: JSON.stringify(msg.argsAged ? stubCallArgs(tc.name, tc.args) : tc.args)
4859
4886
  }
4860
4887
  }));
4861
4888
  }
@@ -4968,14 +4995,14 @@ function newestLiveReadIndex(history, freshFrom, stubbed, prefixStable, rerender
4968
4995
  return -1;
4969
4996
  }
4970
4997
  function droppedPayloadCount(history, prefixStable = false) {
4998
+ return droppedPayloadMessages(history, prefixStable).length;
4999
+ }
5000
+ function droppedPayloadMessages(history, prefixStable = false) {
4971
5001
  const freshFrom = prefixStable ? 0 : findFreshToolBlockStart(history);
4972
5002
  const specIdx = prefixStable ? -1 : taskSpecIndex(history);
4973
5003
  return history.filter(
4974
5004
  (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;
5005
+ );
4979
5006
  }
4980
5007
  function findFreshToolBlockStart(history) {
4981
5008
  for (let i = history.length - 1; i >= 0; i--) {
@@ -5172,6 +5199,23 @@ function reportHead(payload, summary) {
5172
5199
  return `${head}
5173
5200
  (\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
5201
  }
5202
+ var AGED_COMMAND_TAIL_LINES = 3;
5203
+ var AGED_COMMAND_TAIL_LINE_CHARS = 200;
5204
+ var SPILL_LOCATOR_RE = / saved to (\S+) — read that path/;
5205
+ function agedCommandResidue(msg) {
5206
+ if (!msg.summary.startsWith("Ran: ") || !msg.payload) return null;
5207
+ const locator = msg.payload.match(SPILL_LOCATOR_RE)?.[1];
5208
+ const failed = msg.exitCode !== void 0 && msg.exitCode !== 0;
5209
+ const tail = failed ? (msg.command?.outputTail ?? "").split("\n").filter((l) => l.trim()).slice(-AGED_COMMAND_TAIL_LINES).map(
5210
+ (l) => l.length > AGED_COMMAND_TAIL_LINE_CHARS ? `${l.slice(0, AGED_COMMAND_TAIL_LINE_CHARS)}\u2026` : l
5211
+ ) : [];
5212
+ if (!locator && tail.length === 0) return null;
5213
+ const parts = [
5214
+ `[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.` : "") + "]"
5215
+ ];
5216
+ if (tail.length > 0) parts.push(tail.join("\n"));
5217
+ return parts.join("\n\n");
5218
+ }
5175
5219
  function readSkeleton(payload, summary) {
5176
5220
  const lines = payload.split("\n");
5177
5221
  const first = lines[0].match(READ_GUTTER_RE);
@@ -5244,7 +5288,13 @@ ${msg.payload}`, kind: "whole" };
5244
5288
  ${report2}`, kind: "report" };
5245
5289
  const diff = diffSkeleton(msg.payload);
5246
5290
  const skeleton = diff ?? readSkeleton(msg.payload, msg.summary);
5247
- if (!skeleton) return { content: msg.summary, kind: "summary" };
5291
+ if (!skeleton) {
5292
+ const residue = agedCommandResidue(msg);
5293
+ if (residue) return { content: `${msg.summary}
5294
+
5295
+ ${residue}`, kind: "command" };
5296
+ return { content: msg.summary, kind: "summary" };
5297
+ }
5248
5298
  if (skeleton.length >= msg.payload.length) {
5249
5299
  return { content: `${msg.summary}
5250
5300
 
@@ -5962,14 +6012,14 @@ function ageLowFraction() {
5962
6012
  return raw;
5963
6013
  }
5964
6014
  var SMALL_PAYLOAD_CHARS = 2e3;
5965
- function batchAgePayloads(history, estimate, contextWindow, minGen = DEFAULT_MIN_GEN_TOKENS, shedReasoning = true) {
6015
+ function batchAgePayloads(history, estimate, contextWindow, minGen = DEFAULT_MIN_GEN_TOKENS, shedReasoning = true, shedArgs = AGE_CALL_ARGS, protectFrom = Infinity) {
5966
6016
  const threshold = compactThreshold(contextWindow, minGen);
5967
- const none = { marked: 0, bulk: 0, crumbs: 0, kept: 0, short: 0 };
6017
+ const none = { marked: 0, bulk: 0, crumbs: 0, args: 0, kept: 0, short: 0 };
5968
6018
  if (estimate() <= threshold) return none;
5969
6019
  const target = threshold * AGE_LOW_FRACTION;
5970
- const protect = protectedTailStart(history);
6020
+ const protect = Math.min(protectedTailStart(history), protectFrom);
5971
6021
  const specIdx = taskSpecIndex(history);
5972
- const out = { marked: 0, bulk: 0, crumbs: 0, kept: 0, short: 0 };
6022
+ const out = { marked: 0, bulk: 0, crumbs: 0, args: 0, kept: 0, short: 0 };
5973
6023
  const survivingCrumbs = () => {
5974
6024
  let n = 0;
5975
6025
  for (let i = 0; i < protect; i++) {
@@ -5979,7 +6029,7 @@ function batchAgePayloads(history, estimate, contextWindow, minGen = DEFAULT_MIN
5979
6029
  }
5980
6030
  return n;
5981
6031
  };
5982
- const marks = shedOrder(history, protect, specIdx, shedReasoning);
6032
+ const marks = shedOrder(history, protect, specIdx, shedReasoning, shedArgs);
5983
6033
  let applied = 0;
5984
6034
  const applyTo = (k) => {
5985
6035
  while (applied < k) marks[applied++].apply();
@@ -6004,11 +6054,12 @@ function batchAgePayloads(history, estimate, contextWindow, minGen = DEFAULT_MIN
6004
6054
  out.marked++;
6005
6055
  if (marks[i].kind === "bulk") out.bulk++;
6006
6056
  else if (marks[i].kind === "crumb") out.crumbs++;
6057
+ else if (marks[i].kind === "args") out.args++;
6007
6058
  }
6008
6059
  out.kept = survivingCrumbs();
6009
6060
  return out;
6010
6061
  }
6011
- function shedOrder(history, protect, specIdx, shedReasoning) {
6062
+ function shedOrder(history, protect, specIdx, shedReasoning, shedArgs) {
6012
6063
  const marks = [];
6013
6064
  for (let i = 0; i < protect; i++) {
6014
6065
  const m = history[i];
@@ -6056,6 +6107,14 @@ function shedOrder(history, protect, specIdx, shedReasoning) {
6056
6107
  }
6057
6108
  }
6058
6109
  }
6110
+ if (shedArgs) {
6111
+ for (let i = 0; i < protect; i++) {
6112
+ const m = history[i];
6113
+ if (m.role !== "assistant" || m.argsAged || !m.toolCalls) continue;
6114
+ if (!m.toolCalls.some((tc) => JSON.stringify(tc.args).length >= AGED_ARGS_MIN_CHARS)) continue;
6115
+ marks.push({ kind: "args", apply: () => m.argsAged = true, undo: () => delete m.argsAged });
6116
+ }
6117
+ }
6059
6118
  return marks;
6060
6119
  }
6061
6120
  function protectedTailStart(history) {
@@ -6068,7 +6127,9 @@ function msgChars(m) {
6068
6127
  case "user":
6069
6128
  return m.content.length;
6070
6129
  case "assistant":
6071
- return (m.content?.length ?? 0) + (m.reasoning?.length ?? 0) + (m.toolCalls ? JSON.stringify(m.toolCalls).length : 0);
6130
+ return (m.content?.length ?? 0) + (m.reasoning?.length ?? 0) + (m.toolCalls ? JSON.stringify(
6131
+ m.argsAged ? m.toolCalls.map((tc) => ({ ...tc, args: stubCallArgs(tc.name, tc.args) })) : m.toolCalls
6132
+ ).length : 0);
6072
6133
  case "tool":
6073
6134
  return m.aged ? agedContentChars(m) : m.summary.length;
6074
6135
  case "compaction":
@@ -15151,6 +15212,7 @@ var ChromeHost = class {
15151
15212
  this.port = opts.port ?? DEFAULT_PORT;
15152
15213
  this.binary = opts.binary;
15153
15214
  this.profileDir = opts.profileDir ?? join15(homedir10(), ".config", "reika", "chrome");
15215
+ protectLoopbackPort(this.port);
15154
15216
  }
15155
15217
  async newTab() {
15156
15218
  await this.ensure();
@@ -15510,11 +15572,31 @@ async function openSession(wsUrl) {
15510
15572
  };
15511
15573
  }
15512
15574
 
15513
- // src/search/cdp.ts
15514
- var SEARCH_URL = "https://search.brave.com/search?q=";
15515
- var OWN_HOSTS = /(^|\.)(brave\.com|search\.brave\.com)$/;
15575
+ // src/search/engines.ts
15576
+ var DUCKDUCKGO = {
15577
+ name: "duckduckgo",
15578
+ // The HTML version: no script-built page to wait for, real titles in the link text, and every
15579
+ // result's address in the `uddg` parameter of its link.
15580
+ searchUrl: (q) => `https://html.duckduckgo.com/html/?q=${encodeURIComponent(q)}`,
15581
+ ownHosts: /(^|\.)(duckduckgo\.com|duck\.com|duck\.ai)$/,
15582
+ unwrap: (u) => /(^|\.)duckduckgo\.com$/.test(u.hostname) && u.pathname === "/l/" ? u.searchParams.get("uddg") ?? void 0 : void 0,
15583
+ challengeText: /bots use duckduckgo|confirm this search was made by a human|select all squares/i,
15584
+ minAnchors: 10
15585
+ };
15586
+ var BRAVE = {
15587
+ name: "brave",
15588
+ searchUrl: (q) => `https://search.brave.com/search?q=${encodeURIComponent(q)}`,
15589
+ ownHosts: /(^|\.)(brave\.com|brave\.app)$/,
15590
+ challengeText: /verifying you|traditional captcha/i,
15591
+ minAnchors: 10
15592
+ };
15593
+ var ENGINE_ORDER = [DUCKDUCKGO, BRAVE];
15594
+
15595
+ // src/search/extract.ts
15516
15596
  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) {
15597
+ var MAX_LINKS = 400;
15598
+ var BODY_TEXT_CHARS = 4e3;
15599
+ function collectScript() {
15518
15600
  return `(() => {
15519
15601
  const clean = s => (s || '').replace(/\\s+/g, ' ').trim();
15520
15602
  const visible = el => {
@@ -15522,64 +15604,102 @@ function extractionScript(maxResults) {
15522
15604
  const st = getComputedStyle(el);
15523
15605
  return r.width > 0 && r.height > 0 && st.display !== 'none' && st.visibility !== 'hidden';
15524
15606
  };
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
- };
15607
+ const chromeSel = 'header,footer,nav,[role=banner],[role=contentinfo],[role=navigation]';
15535
15608
  // The container repeats the anchor's own text before the description; removing it stops every
15536
15609
  // snippet from opening with a copy of the title it sits under.
15537
- const snippetFor = (a, title) => {
15538
- const anchorText = clean(a.innerText || '');
15610
+ const snippetFor = a => {
15611
+ const own = clean(a.textContent);
15539
15612
  let node = a.parentElement;
15540
15613
  for (let depth = 0; node && depth < 4; depth++, node = node.parentElement) {
15541
15614
  // Stop before climbing into a container that groups several results, or the snippet picks up
15542
15615
  // the *next* result's title. A block holding many links is a group, not one result's body.
15543
15616
  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(' '));
15617
+ const full = clean(node.textContent);
15618
+ if (full.length <= own.length + 40) continue;
15619
+ const body = clean(full.split(own).join(' '));
15547
15620
  if (body.length >= 20) return body.slice(0, 300);
15548
15621
  }
15549
15622
  return '';
15550
15623
  };
15551
- const seen = new Set();
15552
- const perHost = new Map();
15624
+ const all = document.querySelectorAll('a[href]');
15625
+ const links = [];
15626
+ for (const a of all) {
15627
+ if (links.length >= ${MAX_LINKS}) break;
15628
+ links.push({
15629
+ href: a.href,
15630
+ inner: a.innerText || '',
15631
+ text: clean(a.textContent),
15632
+ visible: visible(a),
15633
+ chrome: !!a.closest(chromeSel),
15634
+ snippet: snippetFor(a),
15635
+ });
15636
+ }
15637
+ const body = document.body ? document.body.innerText || document.body.textContent || '' : '';
15638
+ return JSON.stringify({ links, anchors: all.length, bodyText: body.slice(0, ${BODY_TEXT_CHARS}) });
15639
+ })()`;
15640
+ }
15641
+ var clean = (s) => s.replace(/\s+/g, " ").trim();
15642
+ function titleOf(link) {
15643
+ const lines = link.inner.split("\n").map(clean).filter(Boolean);
15644
+ const named = lines.filter((l) => !DATE_LINE.test(l));
15645
+ return named.length ? named[named.length - 1] : link.text;
15646
+ }
15647
+ var keyOf = (url) => url.hostname + url.pathname;
15648
+ var looksLikeProse = (s) => (s.match(/ /g) ?? []).length >= 4;
15649
+ function pickResults(page, engine, max) {
15650
+ const descriptions = /* @__PURE__ */ new Map();
15651
+ for (const link of page.links) {
15652
+ if (!link.visible || link.chrome || !looksLikeProse(link.text)) continue;
15653
+ const url = resultUrl(link.href, engine);
15654
+ if (!url) continue;
15655
+ const key = keyOf(url);
15656
+ if (link.text.length > (descriptions.get(key)?.length ?? 0)) descriptions.set(key, link.text);
15657
+ }
15658
+ const seen = /* @__PURE__ */ new Set();
15659
+ const perHost = /* @__PURE__ */ new Map();
15553
15660
  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);
15661
+ for (const link of page.links) {
15662
+ if (results.length >= max) break;
15663
+ if (!link.visible || link.chrome) continue;
15664
+ const title = titleOf(link);
15558
15665
  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;
15666
+ const url = resultUrl(link.href, engine);
15667
+ if (!url) continue;
15668
+ const key = keyOf(url);
15564
15669
  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;
15670
+ const used = perHost.get(url.hostname) ?? 0;
15569
15671
  if (used >= 2) continue;
15570
- perHost.set(u.hostname, used + 1);
15672
+ perHost.set(url.hostname, used + 1);
15571
15673
  seen.add(key);
15572
- results.push({ title: title.slice(0, 180), url: u.href, snippet: snippetFor(a, title) });
15674
+ const description = descriptions.get(key);
15675
+ const snippet = link.snippet || (description && description.length > title.length ? description : "");
15676
+ results.push({ title: title.slice(0, 180), url: url.href, snippet: snippet.slice(0, 300) });
15573
15677
  }
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
- })()`;
15678
+ return results;
15679
+ }
15680
+ function resultUrl(href, engine) {
15681
+ let u;
15682
+ try {
15683
+ u = new URL(href);
15684
+ } catch {
15685
+ return void 0;
15686
+ }
15687
+ const unwrapped = engine.unwrap?.(u);
15688
+ if (unwrapped !== void 0) {
15689
+ try {
15690
+ u = new URL(unwrapped);
15691
+ } catch {
15692
+ return void 0;
15693
+ }
15694
+ }
15695
+ if (!/^https?:$/.test(u.protocol)) return void 0;
15696
+ if (engine.ownHosts.test(u.hostname)) return void 0;
15697
+ return u;
15581
15698
  }
15582
- var MIN_SERP_ANCHORS = 10;
15699
+
15700
+ // src/search/cdp.ts
15701
+ var SHARED_CHALLENGE_TEXT = /not a bot|unusual traffic|are you a robot|verify you are human|complete the security check/i;
15702
+ var MIN_USABLE_RESULTS = 3;
15583
15703
  var CHALLENGE_WAIT_MS = 12e4;
15584
15704
  var CHALLENGE_POLL_MS = 1e3;
15585
15705
  var CdpSearchProvider = class {
@@ -15587,26 +15707,63 @@ var CdpSearchProvider = class {
15587
15707
  this.host = host;
15588
15708
  this.waitMs = opts.challengeWaitMs ?? CHALLENGE_WAIT_MS;
15589
15709
  this.pollMs = opts.challengePollMs ?? CHALLENGE_POLL_MS;
15710
+ this.engines = opts.engines ?? ENGINE_ORDER;
15590
15711
  }
15591
15712
  host;
15592
15713
  waitMs;
15593
15714
  pollMs;
15715
+ engines;
15594
15716
  // One challenge at a time. Parallel searches in a turn are all refused together, and the solve
15595
15717
  // is profile-wide: the first to hit it raises its own tab and waits, the rest wait on the same
15596
15718
  // promise and then simply reload — a second raised window would compete for the user's one solve.
15597
15719
  challenge;
15598
15720
  async search(query, opts = {}) {
15599
15721
  const max = opts.maxResults ?? 8;
15600
- const url = SEARCH_URL + encodeURIComponent(query);
15722
+ const enough = Math.min(max, MIN_USABLE_RESULTS);
15723
+ let results = [];
15724
+ let challenged;
15725
+ let failure;
15726
+ for (const engine of this.engines) {
15727
+ try {
15728
+ const answer = await this.searchEngine(engine, query, max, opts, false);
15729
+ if (answer === "challenged") challenged ??= engine;
15730
+ else results = mergeResults(results, answer, max);
15731
+ } catch (e) {
15732
+ failure ??= e;
15733
+ }
15734
+ if (results.length >= enough) return results;
15735
+ }
15736
+ if (challenged) {
15737
+ try {
15738
+ const answer = await this.searchEngine(challenged, query, max, opts, true);
15739
+ if (answer !== "challenged") results = mergeResults(answer, results, max);
15740
+ } catch (e) {
15741
+ if (results.length === 0) throw e;
15742
+ debugLog(
15743
+ `[cdp] ${challenged.name}: check not completed, keeping the other engines' results`
15744
+ );
15745
+ }
15746
+ return results;
15747
+ }
15748
+ if (results.length === 0 && failure) throw failure;
15749
+ return results;
15750
+ }
15751
+ async searchEngine(engine, query, max, opts, allowChallenge) {
15752
+ const url = engine.searchUrl(query);
15601
15753
  const tab = await this.host.newTab();
15602
15754
  let holdOpen = false;
15603
15755
  try {
15604
15756
  await tab.navigate(url);
15605
- let data = parseExtraction(await tab.evaluate(extractionScript(max)));
15606
- if (interstitial(data)) {
15757
+ let page = parsePage2(await tab.evaluate(collectScript()));
15758
+ let picked = pickResults(page, engine, max);
15759
+ if (interstitial(engine, page, picked.length)) {
15760
+ if (!allowChallenge) {
15761
+ debugLog(`[cdp] ${engine.name} "${query}" -> challenge, trying the next engine`);
15762
+ return "challenged";
15763
+ }
15607
15764
  const owner = !this.challenge;
15608
15765
  if (owner) {
15609
- this.challenge = this.awaitSolve(tab, max, opts).finally(() => {
15766
+ this.challenge = this.awaitSolve(tab, engine, max, opts).finally(() => {
15610
15767
  this.challenge = void 0;
15611
15768
  });
15612
15769
  }
@@ -15617,19 +15774,14 @@ var CdpSearchProvider = class {
15617
15774
  throw e;
15618
15775
  }
15619
15776
  await tab.navigate(url);
15620
- data = parseExtraction(await tab.evaluate(extractionScript(max)));
15621
- if (interstitial(data)) throw unavailable(data);
15777
+ page = parsePage2(await tab.evaluate(collectScript()));
15778
+ picked = pickResults(page, engine, max);
15779
+ if (interstitial(engine, page, picked.length)) throw unavailable(engine, page);
15622
15780
  }
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
15781
  debugLog(
15630
- `[cdp] "${query}" -> ${results.length} result(s), ${data.anchors ?? 0} links on page`
15782
+ `[cdp] ${engine.name} "${query}" -> ${picked.length} result(s), ${page.anchors} links on page`
15631
15783
  );
15632
- return results;
15784
+ return picked.map((r) => ({ ...r, source: engine.name }));
15633
15785
  } finally {
15634
15786
  if (!holdOpen) await tab.close();
15635
15787
  }
@@ -15638,34 +15790,49 @@ var CdpSearchProvider = class {
15638
15790
  // (the page is mid-navigation after the solve, or the user closed the tab) is not a verdict;
15639
15791
  // the deadline is. The window goes back down only on success: on timeout it stays where the user
15640
15792
  // will find it, with the unsolved check on it.
15641
- async awaitSolve(tab, max, opts) {
15793
+ async awaitSolve(tab, engine, max, opts) {
15642
15794
  await tab.show();
15643
15795
  opts.onChallenge?.("raised");
15644
- debugLog("[cdp] bot check: window raised, waiting for the user");
15796
+ debugLog(`[cdp] ${engine.name} bot check: window raised, waiting for the user`);
15645
15797
  const deadline = Date.now() + this.waitMs;
15646
15798
  let last;
15647
15799
  for (; ; ) {
15648
15800
  await sleep2(this.pollMs);
15649
15801
  try {
15650
- last = parseExtraction(await tab.evaluate(extractionScript(max)));
15651
- if (!interstitial(last)) break;
15802
+ last = parsePage2(await tab.evaluate(collectScript()));
15803
+ if (!interstitial(engine, last, pickResults(last, engine, max).length)) break;
15652
15804
  } catch {
15653
15805
  }
15654
15806
  if (Date.now() >= deadline) {
15655
- debugLog("[cdp] bot check: not completed within the wait");
15656
- throw unavailable(last ?? { blocked: true }, true);
15807
+ debugLog(`[cdp] ${engine.name} bot check: not completed within the wait`);
15808
+ throw unavailable(engine, last, true);
15657
15809
  }
15658
15810
  }
15659
- debugLog("[cdp] bot check cleared");
15811
+ debugLog(`[cdp] ${engine.name} bot check cleared`);
15660
15812
  await tab.hide();
15661
15813
  opts.onChallenge?.("cleared");
15662
15814
  }
15663
15815
  };
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`;
15816
+ function mergeResults(first, then, max) {
15817
+ const seen = new Set(first.map((r) => r.url));
15818
+ const out = [...first];
15819
+ for (const r of then) {
15820
+ if (out.length >= max) break;
15821
+ if (seen.has(r.url)) continue;
15822
+ seen.add(r.url);
15823
+ out.push(r);
15824
+ }
15825
+ return out.slice(0, max);
15826
+ }
15827
+ function challengeText(engine, page) {
15828
+ return SHARED_CHALLENGE_TEXT.test(page.bodyText) || engine.challengeText.test(page.bodyText);
15829
+ }
15830
+ function interstitial(engine, page, picked) {
15831
+ if (picked > 0) return false;
15832
+ return challengeText(engine, page) || page.anchors < engine.minAnchors;
15833
+ }
15834
+ function unavailable(engine, page, timedOut = false) {
15835
+ 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
15836
  return new SearchUnavailableError(
15670
15837
  message,
15671
15838
  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 +15841,21 @@ function unavailable(data, timedOut = false) {
15674
15841
  function sleep2(ms) {
15675
15842
  return new Promise((r) => setTimeout(r, ms));
15676
15843
  }
15677
- function parseExtraction(raw) {
15844
+ function parsePage2(raw) {
15678
15845
  if (typeof raw !== "string") {
15679
15846
  throw new Error("the search page returned nothing to extract");
15680
15847
  }
15848
+ let page;
15681
15849
  try {
15682
- return JSON.parse(raw);
15850
+ page = JSON.parse(raw);
15683
15851
  } catch {
15684
15852
  throw new Error("could not parse results from the search page");
15685
15853
  }
15854
+ return {
15855
+ links: Array.isArray(page.links) ? page.links : [],
15856
+ anchors: typeof page.anchors === "number" ? page.anchors : 0,
15857
+ bodyText: typeof page.bodyText === "string" ? page.bodyText : ""
15858
+ };
15686
15859
  }
15687
15860
 
15688
15861
  // src/tools/index.ts
@@ -16539,14 +16712,25 @@ function observeNoteSlot(obs) {
16539
16712
 
16540
16713
  // src/agent/readtrace.ts
16541
16714
  var FILE_OVERLAP_DEPTH = 4;
16715
+ var DEPTH_WITHOUT_PROGRESS = 5;
16542
16716
  var MAX_NARROWINGS = 3;
16543
16717
  var ReadTrace = class {
16718
+ // Whether the tool message that carried an earlier fetch is gone from the request (shed or
16719
+ // folded). Without one, every earlier fetch stacks, as it did before.
16720
+ constructor(isGone = () => false) {
16721
+ this.isGone = isGone;
16722
+ }
16723
+ isGone;
16544
16724
  // Keyed (path, offset), limit-normalized — matches the loop's repeatKey. A model re-reading the
16545
16725
  // same start line with a different window is the same re-read, not forward paging to a new region.
16546
16726
  // The window is still carried in the entry (not the key) for the narrowing carve-out below, which
16547
16727
  // needs to compare against the previous request rather than fork a new region for every window.
16548
16728
  seen = /* @__PURE__ */ new Map();
16549
16729
  files = /* @__PURE__ */ new Map();
16730
+ // The region key of each file's latest fetch, so attachMessage can link that region too.
16731
+ lastKey = /* @__PURE__ */ new Map();
16732
+ // Bumped by each landed edit; a fetch is "since progress" while its epoch is the current one.
16733
+ epoch = 0;
16550
16734
  counts = {
16551
16735
  unique: 0,
16552
16736
  changed: 0,
@@ -16584,7 +16768,8 @@ var ReadTrace = class {
16584
16768
  repeats = 1;
16585
16769
  narrowings = prior.narrowings + 1;
16586
16770
  } else {
16587
- repeats = prior.repeats + 1;
16771
+ const priorGone = !!prior.msg && this.isGone(prior.msg);
16772
+ repeats = priorGone ? prior.repeats : prior.repeats + 1;
16588
16773
  cls = round - prior.round <= 1 ? "dup-live" : "dup-aged";
16589
16774
  narrowings = prior.narrowings;
16590
16775
  }
@@ -16598,6 +16783,7 @@ var ReadTrace = class {
16598
16783
  narrowings,
16599
16784
  lastLive: cls === "dup-live"
16600
16785
  });
16786
+ this.lastKey.set(path, key);
16601
16787
  this.counts[cls]++;
16602
16788
  this.recordFile(path, offset, window, hash, round, cls, via);
16603
16789
  return { cls, repeats };
@@ -16614,15 +16800,35 @@ var ReadTrace = class {
16614
16800
  const hi = window === Infinity ? Infinity : lo + window - 1;
16615
16801
  let f = this.files.get(path);
16616
16802
  if (!f || f.hash !== hash) {
16617
- f = { hash, ranges: [], depth: 0, lastRound: round, lastVia: via };
16803
+ f = {
16804
+ hash,
16805
+ ranges: [],
16806
+ depth: 0,
16807
+ lastRound: round,
16808
+ lastVia: via,
16809
+ depthSinceProgress: 0,
16810
+ lastProgressRound: round
16811
+ };
16618
16812
  this.files.set(path, f);
16619
16813
  }
16620
16814
  f.lastVia = via;
16621
16815
  if (cls !== "narrowed" && cls !== "regrounded") {
16622
- const points = [lo, ...f.ranges.map(([a]) => a).filter((a) => a >= lo && a <= hi)];
16816
+ const since = f.ranges.filter((r) => r.epoch === this.epoch);
16817
+ const sincePoints = [lo, ...since.map((r) => r.lo).filter((a) => a >= lo && a <= hi)];
16818
+ let sinceDepth = 1;
16819
+ for (const p of sincePoints) {
16820
+ const stacked = 1 + since.filter((r) => p >= r.lo && p <= r.hi).length;
16821
+ if (stacked > sinceDepth) sinceDepth = stacked;
16822
+ }
16823
+ if (sinceDepth >= f.depthSinceProgress || sinceDepth >= DEPTH_WITHOUT_PROGRESS) {
16824
+ f.depthSinceProgress = Math.max(f.depthSinceProgress, sinceDepth);
16825
+ f.lastProgressRound = round;
16826
+ }
16827
+ const held = f.ranges.filter((r) => !r.msg || !this.isGone(r.msg));
16828
+ const points = [lo, ...held.map((r) => r.lo).filter((a) => a >= lo && a <= hi)];
16623
16829
  let depth = 1;
16624
16830
  for (const p of points) {
16625
- const stacked = 1 + f.ranges.filter(([a, b]) => p >= a && p <= b).length;
16831
+ const stacked = 1 + held.filter((r) => p >= r.lo && p <= r.hi).length;
16626
16832
  if (stacked > depth) depth = stacked;
16627
16833
  }
16628
16834
  if (depth > f.depth) {
@@ -16632,7 +16838,20 @@ var ReadTrace = class {
16632
16838
  f.lastRound = round;
16633
16839
  }
16634
16840
  }
16635
- f.ranges.push([lo, hi]);
16841
+ f.ranges.push({ lo, hi, epoch: this.epoch });
16842
+ }
16843
+ // An edit, a write or a command that changed the tree landed: re-reads before it led somewhere.
16844
+ noteProgress() {
16845
+ this.epoch++;
16846
+ for (const f of this.files.values()) f.depthSinceProgress = 0;
16847
+ }
16848
+ // Links the latest fetch of `path` to the tool message that carried it, once that message exists.
16849
+ attachMessage(path, msg) {
16850
+ const last = this.files.get(path)?.ranges.at(-1);
16851
+ if (last && !last.msg) last.msg = msg;
16852
+ const key = this.lastKey.get(path);
16853
+ const entry = key === void 0 ? void 0 : this.seen.get(key);
16854
+ if (entry && !entry.msg) entry.msg = msg;
16636
16855
  }
16637
16856
  // Regions the model is looping on, re-read within the last `recentWithin` rounds of
16638
16857
  // `currentRound`. Two-tier threshold: a dup-live region (content still in context — re-reading it
@@ -16653,9 +16872,10 @@ var ReadTrace = class {
16653
16872
  const named = new Set(out.map((l) => l.path));
16654
16873
  for (const [path, f] of this.files) {
16655
16874
  if (named.has(path)) continue;
16656
- if (currentRound - f.lastRound > recentWithin) continue;
16657
- if (f.depth >= FILE_OVERLAP_DEPTH) {
16875
+ if (f.depth >= FILE_OVERLAP_DEPTH && currentRound - f.lastRound <= recentWithin) {
16658
16876
  out.push({ path, offset: 1, repeats: f.depth });
16877
+ } else if (f.depthSinceProgress >= DEPTH_WITHOUT_PROGRESS && currentRound - f.lastProgressRound <= recentWithin) {
16878
+ out.push({ path, offset: 1, repeats: f.depthSinceProgress });
16659
16879
  }
16660
16880
  }
16661
16881
  return out;
@@ -16673,8 +16893,12 @@ var ReadTrace = class {
16673
16893
  if (e.repeats >= 3) looped++;
16674
16894
  }
16675
16895
  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}`;
16896
+ let refetched = 0;
16897
+ for (const f of this.files.values()) {
16898
+ if (f.depth >= FILE_OVERLAP_DEPTH) overlapped++;
16899
+ if (f.depthSinceProgress >= DEPTH_WITHOUT_PROGRESS) refetched++;
16900
+ }
16901
+ 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
16902
  }
16679
16903
  };
16680
16904
  function priorCopyState(prior, history, prefixStable) {
@@ -18184,15 +18408,46 @@ function runTscProcess(bin, args, cwd, timeoutMs, signal, viaSandboxWrapper = fa
18184
18408
  var TRACKED_TOOLS = /* @__PURE__ */ new Set(["read", "grep", "list", "glob", "bash"]);
18185
18409
  var WEB_LOOKUP_ARG = { search: "query", fetch_url: "url" };
18186
18410
  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;
18411
+ var TYPE_INERT_EXTENSIONS = /* @__PURE__ */ new Set([
18412
+ "md",
18413
+ "mdx",
18414
+ "markdown",
18415
+ "txt",
18416
+ "rst",
18417
+ "css",
18418
+ "scss",
18419
+ "sass",
18420
+ "less",
18421
+ "html",
18422
+ "svg",
18423
+ "png",
18424
+ "jpg",
18425
+ "jpeg",
18426
+ "gif",
18427
+ "webp",
18428
+ "ico",
18429
+ "yml",
18430
+ "yaml",
18431
+ "toml"
18432
+ ]);
18433
+ function isTypeInertPath(path) {
18434
+ const base = path.slice(path.lastIndexOf("/") + 1);
18435
+ const dot = base.lastIndexOf(".");
18436
+ return dot > 0 && TYPE_INERT_EXTENSIONS.has(base.slice(dot + 1).toLowerCase());
18437
+ }
18438
+ function typeRelevantTargets(name, args, cwd) {
18439
+ if (MUTATING_TOOLS.has(name)) {
18440
+ const path = typeof args.path === "string" ? args.path : "";
18441
+ return isTypeInertPath(path) ? [] : [path];
18442
+ }
18443
+ if (name !== "bash") return [];
18444
+ return writeTargets(String(args.command ?? ""), cwd).filter((t) => !isTypeInertPath(t));
18445
+ }
18446
+ function mayAffectTypes(name, args, cwd) {
18447
+ return typeRelevantTargets(name, args, cwd).length > 0;
18191
18448
  }
18192
18449
  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];
18450
+ return typeRelevantTargets(name, args, cwd)[0] || void 0;
18196
18451
  }
18197
18452
  function didMutate(name, changes) {
18198
18453
  if (MUTATING_TOOLS.has(name)) return true;
@@ -18507,34 +18762,50 @@ function withdrawalRemedy(toolNames) {
18507
18762
  }
18508
18763
  return "Answer from what you already have";
18509
18764
  }
18765
+ function withdrawalReturn(toolNames) {
18766
+ if (toolNames.has("edit") || toolNames.has("write")) {
18767
+ 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.";
18768
+ }
18769
+ if (toolNames.has("bash")) {
18770
+ 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.";
18771
+ }
18772
+ return "The pause is temporary: reading comes back after a few rounds.";
18773
+ }
18510
18774
  function withdrawnLedgerLines(toolNames) {
18511
18775
  if (toolNames.has("edit") || toolNames.has("write")) {
18512
18776
  return [
18513
18777
  "Reading and searching are now PAUSED. Make the edit the task requires with the edit/write",
18514
18778
  "tools, state specifically what is still blocking you, or \u2014 if the change is already complete \u2014",
18515
- "say so and stop."
18779
+ "say so and stop.",
18780
+ withdrawalReturn(toolNames)
18516
18781
  ];
18517
18782
  }
18518
18783
  if (toolNames.has("bash")) {
18519
18784
  return [
18520
18785
  "Reading and searching are now PAUSED. Make the change the task requires by running the",
18521
18786
  "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."
18787
+ "is already complete \u2014 say so and stop.",
18788
+ withdrawalReturn(toolNames)
18523
18789
  ];
18524
18790
  }
18525
18791
  return [
18526
18792
  "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."
18793
+ "what is still blocking you, or \u2014 if the change is already complete \u2014 say so and stop.",
18794
+ withdrawalReturn(toolNames)
18528
18795
  ];
18529
18796
  }
18530
18797
  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.)`;
18798
+ return `(reika: this is deliberate, not a fault. ${withdrawnToolsPhrase(toolNames)} are paused because the work has repeated without making progress. Sending this call again now gets this same reply, so do not retry it. ${withdrawalRemedy(toolNames)}, state what is specifically blocking you, or \u2014 if the change is already complete \u2014 say so and stop. ${withdrawalReturn(toolNames)})`;
18532
18799
  }
18533
18800
  function shouldWithdrawInspection(opts) {
18534
18801
  if (opts.loopActiveRounds < LOOP_WITHDRAW_AFTER) return false;
18535
18802
  return !opts.editRecovery;
18536
18803
  }
18537
18804
  var WITHDRAW_HOLD_ROUNDS = 4;
18805
+ function liftsWithdrawal(name, changes) {
18806
+ if (name === "edit") return true;
18807
+ return name === "bash" && !!changes && changes.files.some((f) => f.kind !== "created");
18808
+ }
18538
18809
  function holdWithdrawal(opts) {
18539
18810
  if (opts.since === void 0 || opts.mutated || opts.editRecovery) return false;
18540
18811
  return opts.round - opts.since < WITHDRAW_HOLD_ROUNDS;
@@ -18565,17 +18836,27 @@ function prefixed(ledger) {
18565
18836
  return ledger ? "\n" + ledger : "";
18566
18837
  }
18567
18838
  function droppedPayloadLedgerFor(history, prefixStable) {
18568
- return DROPPED_LEDGER && hasDroppedPayloads(history, prefixStable) ? buildDroppedPayloadLedger() : "";
18839
+ if (!DROPPED_LEDGER) return "";
18840
+ const dropped = droppedPayloadMessages(history, prefixStable);
18841
+ return dropped.length ? buildDroppedPayloadLedger(dropped.map((m) => m.role === "tool" ? m.summary : "")) : "";
18569
18842
  }
18843
+ var DROPPED_LEDGER_MAX_LISTED = 8;
18844
+ var DROPPED_LEDGER_SUMMARY_CHARS = 100;
18570
18845
  var DROPPED_LEDGER_MARKER = "Their output was dropped to make room";
18571
- function buildDroppedPayloadLedger() {
18846
+ function buildDroppedPayloadLedger(summaries) {
18847
+ const newest = summaries.slice(-DROPPED_LEDGER_MAX_LISTED).reverse();
18848
+ const earlier = summaries.length - newest.length;
18849
+ const clip = (s) => s.length > DROPPED_LEDGER_SUMMARY_CHARS ? `${s.slice(0, DROPPED_LEDGER_SUMMARY_CHARS - 1)}\u2026` : s;
18572
18850
  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."
18851
+ "--- reika status (auto-generated \u2014 not user input; repeated every round, not a new message) ---",
18852
+ "These tool results above now show only their summary line or a short outline.",
18853
+ `${DROPPED_LEDGER_MARKER}; it is not in your context any more:`,
18854
+ ...newest.map((s) => `- ${clip(s)}`),
18855
+ ...earlier > 0 ? [`- and ${earlier} earlier`] : [],
18856
+ "Every other tool result above, including the newest, is still in your context as shown. This is",
18857
+ "a context limit, not a failed command, and it does not mean you already handled those results.",
18858
+ "If you still need what one of them returned, re-run that call \u2014 do not answer from memory of",
18859
+ "it, and do not re-run calls whose output you still have."
18579
18860
  ].join("\n");
18580
18861
  }
18581
18862
  function buildQuestionLedger(answers) {
@@ -18622,6 +18903,10 @@ ${failure.excerpt}
18622
18903
 
18623
18904
  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
18905
  }
18906
+ function formatShedNotice(shed, outputs) {
18907
+ const noun = outputs === 1 ? "tool output is" : "tool outputs are";
18908
+ return `Context trimmed (shed ${shed}) \u2014 ${outputs} older ${noun} now summary-only to the model (still shown here; it re-reads what it needs).`;
18909
+ }
18625
18910
  async function runTurn(opts) {
18626
18911
  if (!opts.manualCompact) {
18627
18912
  const userMsg = {
@@ -18715,10 +19000,11 @@ ${SUBAGENT_REPORT_FRAME}` : promptForMode;
18715
19000
  let planGateRounds = 0;
18716
19001
  const seenReadOnly = /* @__PURE__ */ new Map();
18717
19002
  const seenWebLookups = /* @__PURE__ */ new Set();
18718
- const readTrace = new ReadTrace();
19003
+ const readTrace = new ReadTrace((m) => priorCopyState(m, opts.history, prefixStable) === "yes");
18719
19004
  const lastReadMessage = /* @__PURE__ */ new Map();
18720
19005
  const prevAgedField = (cls, key) => cls === "dup-live" || cls === "dup-aged" ? ` prevAged=${priorCopyState(lastReadMessage.get(key), opts.history, prefixStable)}` : "";
18721
19006
  const readFirst = new ReadFirstGate(opts.bundle.cwd);
19007
+ const refusedArgEchoes = /* @__PURE__ */ new Set();
18722
19008
  const reasoningTrace = new ReasoningTrace();
18723
19009
  let reasoningLoopActive = false;
18724
19010
  let reasoningChannel = "reasoning";
@@ -19305,6 +19591,7 @@ ${COMPACTION_REPORT_RETRY}`, refusedCallTurn(rep));
19305
19591
  }
19306
19592
  }
19307
19593
  let agedThisRound = false;
19594
+ let agedOutputs = 0;
19308
19595
  if (prefixStable && window && !planForceWrite) {
19309
19596
  const aged = batchAgePayloads(
19310
19597
  opts.history,
@@ -19318,9 +19605,10 @@ ${COMPACTION_REPORT_RETRY}`, refusedCallTurn(rep));
19318
19605
  !latchesFor(opts.config).reasoningRoundtrip
19319
19606
  );
19320
19607
  agedThisRound = aged.marked > 0;
19608
+ agedOutputs = aged.bulk + aged.crumbs;
19321
19609
  if (aged.marked > 0) {
19322
19610
  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}
19611
+ `[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
19612
  `
19325
19613
  );
19326
19614
  shrink.sheds++;
@@ -19355,6 +19643,14 @@ ${COMPACTION_REPORT_RETRY}`, refusedCallTurn(rep));
19355
19643
  });
19356
19644
  }
19357
19645
  }
19646
+ if (agedOutputs > 0 && lastFoldRemoved === 0) {
19647
+ opts.onMessage({
19648
+ role: "system",
19649
+ tone: "info",
19650
+ emphasis: "line",
19651
+ content: formatShedNotice(shrink.sheds, agedOutputs)
19652
+ });
19653
+ }
19358
19654
  if (opts.manualCompact) {
19359
19655
  if (lastFoldRemoved === 0) {
19360
19656
  opts.onMessage({
@@ -19398,7 +19694,7 @@ ${roundSuffix}` : dropped;
19398
19694
  if (opts.signal.aborted) callAbort.abort();
19399
19695
  else opts.signal.addEventListener("abort", () => callAbort.abort(), { once: true });
19400
19696
  }
19401
- const canAbortVerbatim = VERBATIM_ABORT && (verbatimRecoveries < MAX_VERBATIM_RECOVERIES || steerRetryActive);
19697
+ const canAbortVerbatim = VERBATIM_ABORT && !subagentForceReport && (verbatimRecoveries < MAX_VERBATIM_RECOVERIES || steerRetryActive);
19402
19698
  const trackSpin = !!opts.onReasoningStatus || debugEnabled() || canAbortVerbatim;
19403
19699
  const onReasoningDelta = trackSpin ? (delta) => {
19404
19700
  opts.onReasoningDelta?.(delta);
@@ -19505,10 +19801,10 @@ ${roundSuffix}` : dropped;
19505
19801
  // outline, and how many were small enough that keeping them whole cost less than the marker.
19506
19802
  // Silent when nothing is aged yet, so early rounds add no noise.
19507
19803
  onAgedStats: debugEnabled() ? (a) => {
19508
- const total = a.summary + a.diff + a.outline + a.whole + a.report;
19804
+ const total = a.summary + a.diff + a.outline + a.whole + a.report + a.command;
19509
19805
  if (total === 0) return;
19510
19806
  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}
19807
+ `[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
19808
  `
19513
19809
  );
19514
19810
  } : void 0,
@@ -19726,7 +20022,7 @@ ${rsn}` : rsn;
19726
20022
  ${roundText}` : roundText;
19727
20023
  const cutOffMidThought = response.finishReason === "length" && isFinal;
19728
20024
  let continueRound = false;
19729
- if (CONTINUE && cutOffMidThought && carriedBlock.trim()) {
20025
+ if (CONTINUE && cutOffMidThought && carriedBlock.trim() && !subagentForceReport) {
19730
20026
  const gate = continuationGate(carriedBlock);
19731
20027
  const allow = continuation.allow(roundText);
19732
20028
  continueRound = gate.continuable && allow.ok;
@@ -19781,7 +20077,7 @@ ${response.content}`,
19781
20077
  }
19782
20078
  pendingContinuation = "";
19783
20079
  pendingReasoning = "";
19784
- if (shouldRetryTruncated({
20080
+ if (!subagentForceReport && shouldRetryTruncated({
19785
20081
  finishReason: response.finishReason,
19786
20082
  hasToolCalls: !isFinal,
19787
20083
  priorRetries: lengthRetries
@@ -20000,6 +20296,9 @@ ${response.content}`,
20000
20296
  if (provenEdit) debugLog(`[reika:debug] round=${i} read-first proven ${call.args.path}
20001
20297
  `);
20002
20298
  const bouncedBlindEdit = blindEdit && !provenEdit && readFirst.shouldBounce(String(call.args.path), opts.history, prefixStable);
20299
+ const echoKey = `${call.name}\0${JSON.stringify(call.args)}`;
20300
+ const refusedArgEcho = tool !== void 0 && !refused && !bouncedBlindEdit && !heldForSubagent && !refusedArgEchoes.has(echoKey) && agedArgEcho(call.args) && opts.history.some((m) => m.role === "assistant" && m.argsAged);
20301
+ if (refusedArgEcho) refusedArgEchoes.add(echoKey);
20003
20302
  let summary;
20004
20303
  let payload;
20005
20304
  let diff;
@@ -20015,7 +20314,7 @@ ${response.content}`,
20015
20314
  let groundsAuthored = false;
20016
20315
  let traceKey2;
20017
20316
  let planCheckoff;
20018
- if (typecheckEnabled && !typecheckBaselineAttempted && tool && !refused && !bouncedBlindEdit && willMutate(call.name, call.args, opts.bundle.cwd)) {
20317
+ if (typecheckEnabled && !typecheckBaselineAttempted && tool && !refused && !bouncedBlindEdit && !refusedArgEcho && mayAffectTypes(call.name, call.args, opts.bundle.cwd)) {
20019
20318
  typecheckBaselineAttempted = true;
20020
20319
  typecheckTsconfig = await detectTsProject(
20021
20320
  opts.bundle.cwd,
@@ -20050,6 +20349,11 @@ ${response.content}`,
20050
20349
  debugLog(`[reika:debug] round=${i} read-first bounce ${blindPath} ${probe}
20051
20350
  `);
20052
20351
  }
20352
+ } else if (refusedArgEcho) {
20353
+ summary = `${call.name} not run \u2014 it contains a placeholder for text sent earlier`;
20354
+ payload = AGED_ARG_ECHO_DIRECTIVE;
20355
+ debugLog(`[reika:debug] round=${i} age-args-echo refused tool=${call.name}
20356
+ `);
20053
20357
  } else if (heldForSubagent) {
20054
20358
  const label = refusedBashGrep ? "shell inspection" : call.name;
20055
20359
  summary = `${label} held \u2014 the subagent dispatched this round covers it`;
@@ -20062,6 +20366,10 @@ ${response.content}`,
20062
20366
  if (spillStatsEnabled() && Object.values(call.args).some((v) => typeof v === "string" && referencesSpill(v))) {
20063
20367
  recordFollowed({ by: call.name });
20064
20368
  }
20369
+ if (refusedArgEchoes.has(echoKey)) {
20370
+ debugLog(`[reika:debug] round=${i} age-args-echo resent tool=${call.name}
20371
+ `);
20372
+ }
20065
20373
  opts.onToolStart?.(call.name);
20066
20374
  const callStart = Date.now();
20067
20375
  try {
@@ -20172,16 +20480,19 @@ ${grounding}` : grounding;
20172
20480
  debugLog(`[reika:debug] tool-call round=${i} ${call.name} ${summary}
20173
20481
  `);
20174
20482
  }
20175
- if (tool && !refused && !bouncedBlindEdit && !heldForSubagent)
20483
+ if (tool && !refused && !bouncedBlindEdit && !heldForSubagent && !refusedArgEcho)
20176
20484
  payload = flagRepeatedCall(seenReadOnly, call.name, call.args, summary, payload);
20177
20485
  if (tool && !refused && payload && WEB_LOOKUP_ARG[call.name]) {
20178
20486
  seenWebLookups.add(`${call.name}\0${String(call.args[WEB_LOOKUP_ARG[call.name]] ?? "")}`);
20179
20487
  }
20180
- if (!bouncedBlindEdit && didMutate(call.name, changes)) {
20488
+ if (!bouncedBlindEdit && !refusedArgEcho && didMutate(call.name, changes)) {
20181
20489
  editingStarted = true;
20182
- mutatedSinceWithdrawal = true;
20490
+ if (!MUTATING_TOOLS.has(call.name) || /^(Edited|Wrote) /.test(summary))
20491
+ readTrace.noteProgress();
20183
20492
  }
20184
- if (!bouncedBlindEdit && MUTATING_TOOLS.has(call.name)) {
20493
+ if (!bouncedBlindEdit && !refusedArgEcho && liftsWithdrawal(call.name, changes))
20494
+ mutatedSinceWithdrawal = true;
20495
+ if (!bouncedBlindEdit && !refusedArgEcho && MUTATING_TOOLS.has(call.name)) {
20185
20496
  if (summary.startsWith("Edited ") || summary.startsWith("Wrote ")) {
20186
20497
  lastEditFailed = false;
20187
20498
  lastEditFailure = void 0;
@@ -20242,7 +20553,10 @@ ${grounding}` : grounding;
20242
20553
  };
20243
20554
  opts.history.push(toolMsg);
20244
20555
  opts.onMessage(toolMsg);
20245
- if (traceKey2) lastReadMessage.set(traceKey2, toolMsg);
20556
+ if (traceKey2) {
20557
+ lastReadMessage.set(traceKey2, toolMsg);
20558
+ readTrace.attachMessage(traceKey2.slice(0, traceKey2.indexOf("\0")), toolMsg);
20559
+ }
20246
20560
  if (groundsPath) {
20247
20561
  readFirst.ground(groundsPath, groundsAuthored ? void 0 : opts.history.length - 1);
20248
20562
  }