@alexwkleung/reika 0.13.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-KS3VH2ZV.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
@@ -2671,7 +2671,7 @@ var require_emoji_regex = __commonJS({
2671
2671
  }
2672
2672
  });
2673
2673
 
2674
- // src/ui/format.ts
2674
+ // src/display/format.ts
2675
2675
  var HIDDEN_TOOL_ARGS = {
2676
2676
  edit: /* @__PURE__ */ new Set(["old_string", "new_string"]),
2677
2677
  write: /* @__PURE__ */ new Set(["content"])
@@ -2790,6 +2790,20 @@ function changeLabel(f) {
2790
2790
  return `(+${f.added} -${f.removed})`;
2791
2791
  }
2792
2792
  }
2793
+ var TRAILING_STAT = /\((?:(?:new|deleted),\s+)?(?:\+\d+)?(?:\s*-\d+)?\)$/;
2794
+ function diffStatRuns(text) {
2795
+ const m = TRAILING_STAT.exec(text);
2796
+ if (!m || !/[+-]\d/.test(m[0])) return [{ text }];
2797
+ const runs = [{ text: text.slice(0, m.index) }];
2798
+ for (const piece of m[0].split(/([+-]\d+)/)) {
2799
+ if (!piece) continue;
2800
+ const counted = /^[+-]\d+$/.test(piece) && Number(piece.slice(1)) > 0;
2801
+ runs.push(
2802
+ counted ? { text: piece, side: piece[0] === "+" ? "added" : "removed" } : { text: piece }
2803
+ );
2804
+ }
2805
+ return runs.filter((r) => r.text);
2806
+ }
2793
2807
  function formatContext(contextTokens, contextWindow, contextUsable) {
2794
2808
  if (contextTokens == null || contextTokens <= 0) return "";
2795
2809
  if (!contextWindow) return `ctx ${kFormat(contextTokens)}`;
@@ -4178,7 +4192,7 @@ function pasteIsNative(config) {
4178
4192
  return config.vision === "native";
4179
4193
  }
4180
4194
 
4181
- // src/ui/pastes.ts
4195
+ // src/display/pastes.ts
4182
4196
  var PASTE_LINE_THRESHOLD = 12;
4183
4197
  var PASTE_CHAR_THRESHOLD = 1500;
4184
4198
  var MAX_PASTE_STORE_CHARS = 4e6;
@@ -4691,6 +4705,26 @@ var BUDGET_SAFETY = 0.9;
4691
4705
  var CAP_DENSITY_FLOOR = 2.5;
4692
4706
  var SENT_DENSITY_FLOOR = 1;
4693
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
+ }
4694
4728
  var DEDUP_PAYLOAD_STUB = "(reika: identical to an earlier result above \u2014 body omitted, you already have it)";
4695
4729
  var DEDUP_TRAIL_STUB = "(reika: repeat of an earlier identical result \u2014 omitted)";
4696
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;
@@ -4812,7 +4846,14 @@ ${recapText}` : system;
4812
4846
  }
4813
4847
  return capPayload(payload, cap);
4814
4848
  };
4815
- 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
+ };
4816
4857
  const serializeAged = (msg, i) => {
4817
4858
  const { content, kind } = agedToolContent(msg, keptWhole.has(i));
4818
4859
  agedStats[kind]++;
@@ -4841,7 +4882,7 @@ ${recapText}` : system;
4841
4882
  type: "function",
4842
4883
  function: {
4843
4884
  name: tc.name,
4844
- arguments: JSON.stringify(tc.args)
4885
+ arguments: JSON.stringify(msg.argsAged ? stubCallArgs(tc.name, tc.args) : tc.args)
4845
4886
  }
4846
4887
  }));
4847
4888
  }
@@ -4954,14 +4995,14 @@ function newestLiveReadIndex(history, freshFrom, stubbed, prefixStable, rerender
4954
4995
  return -1;
4955
4996
  }
4956
4997
  function droppedPayloadCount(history, prefixStable = false) {
4998
+ return droppedPayloadMessages(history, prefixStable).length;
4999
+ }
5000
+ function droppedPayloadMessages(history, prefixStable = false) {
4957
5001
  const freshFrom = prefixStable ? 0 : findFreshToolBlockStart(history);
4958
5002
  const specIdx = prefixStable ? -1 : taskSpecIndex(history);
4959
5003
  return history.filter(
4960
5004
  (m, i) => m.role === "tool" && m.payload && i !== specIdx ? prefixStable ? !!m.aged : i < freshFrom : false
4961
- ).length;
4962
- }
4963
- function hasDroppedPayloads(history, prefixStable = false) {
4964
- return droppedPayloadCount(history, prefixStable) > 0;
5005
+ );
4965
5006
  }
4966
5007
  function findFreshToolBlockStart(history) {
4967
5008
  for (let i = history.length - 1; i >= 0; i--) {
@@ -5158,6 +5199,23 @@ function reportHead(payload, summary) {
5158
5199
  return `${head}
5159
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.)`;
5160
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
+ }
5161
5219
  function readSkeleton(payload, summary) {
5162
5220
  const lines = payload.split("\n");
5163
5221
  const first = lines[0].match(READ_GUTTER_RE);
@@ -5230,7 +5288,13 @@ ${msg.payload}`, kind: "whole" };
5230
5288
  ${report2}`, kind: "report" };
5231
5289
  const diff = diffSkeleton(msg.payload);
5232
5290
  const skeleton = diff ?? readSkeleton(msg.payload, msg.summary);
5233
- 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
+ }
5234
5298
  if (skeleton.length >= msg.payload.length) {
5235
5299
  return { content: `${msg.summary}
5236
5300
 
@@ -5948,14 +6012,14 @@ function ageLowFraction() {
5948
6012
  return raw;
5949
6013
  }
5950
6014
  var SMALL_PAYLOAD_CHARS = 2e3;
5951
- 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) {
5952
6016
  const threshold = compactThreshold(contextWindow, minGen);
5953
- 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 };
5954
6018
  if (estimate() <= threshold) return none;
5955
6019
  const target = threshold * AGE_LOW_FRACTION;
5956
- const protect = protectedTailStart(history);
6020
+ const protect = Math.min(protectedTailStart(history), protectFrom);
5957
6021
  const specIdx = taskSpecIndex(history);
5958
- 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 };
5959
6023
  const survivingCrumbs = () => {
5960
6024
  let n = 0;
5961
6025
  for (let i = 0; i < protect; i++) {
@@ -5965,7 +6029,7 @@ function batchAgePayloads(history, estimate, contextWindow, minGen = DEFAULT_MIN
5965
6029
  }
5966
6030
  return n;
5967
6031
  };
5968
- const marks = shedOrder(history, protect, specIdx, shedReasoning);
6032
+ const marks = shedOrder(history, protect, specIdx, shedReasoning, shedArgs);
5969
6033
  let applied = 0;
5970
6034
  const applyTo = (k) => {
5971
6035
  while (applied < k) marks[applied++].apply();
@@ -5990,11 +6054,12 @@ function batchAgePayloads(history, estimate, contextWindow, minGen = DEFAULT_MIN
5990
6054
  out.marked++;
5991
6055
  if (marks[i].kind === "bulk") out.bulk++;
5992
6056
  else if (marks[i].kind === "crumb") out.crumbs++;
6057
+ else if (marks[i].kind === "args") out.args++;
5993
6058
  }
5994
6059
  out.kept = survivingCrumbs();
5995
6060
  return out;
5996
6061
  }
5997
- function shedOrder(history, protect, specIdx, shedReasoning) {
6062
+ function shedOrder(history, protect, specIdx, shedReasoning, shedArgs) {
5998
6063
  const marks = [];
5999
6064
  for (let i = 0; i < protect; i++) {
6000
6065
  const m = history[i];
@@ -6042,6 +6107,14 @@ function shedOrder(history, protect, specIdx, shedReasoning) {
6042
6107
  }
6043
6108
  }
6044
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
+ }
6045
6118
  return marks;
6046
6119
  }
6047
6120
  function protectedTailStart(history) {
@@ -6054,7 +6127,9 @@ function msgChars(m) {
6054
6127
  case "user":
6055
6128
  return m.content.length;
6056
6129
  case "assistant":
6057
- 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);
6058
6133
  case "tool":
6059
6134
  return m.aged ? agedContentChars(m) : m.summary.length;
6060
6135
  case "compaction":
@@ -11400,7 +11475,7 @@ var writeTool = {
11400
11475
  // src/tools/bash.ts
11401
11476
  import { spawn as spawn2 } from "node:child_process";
11402
11477
 
11403
- // src/ui/commandtail.ts
11478
+ // src/display/commandtail.ts
11404
11479
  var OUTPUT_TAIL_BYTES = 2 * 1024;
11405
11480
  var OUTPUT_TAIL_LINES = 10;
11406
11481
  function commandTail(retained, omittedEarlier = false) {
@@ -15137,6 +15212,7 @@ var ChromeHost = class {
15137
15212
  this.port = opts.port ?? DEFAULT_PORT;
15138
15213
  this.binary = opts.binary;
15139
15214
  this.profileDir = opts.profileDir ?? join15(homedir10(), ".config", "reika", "chrome");
15215
+ protectLoopbackPort(this.port);
15140
15216
  }
15141
15217
  async newTab() {
15142
15218
  await this.ensure();
@@ -15496,11 +15572,31 @@ async function openSession(wsUrl) {
15496
15572
  };
15497
15573
  }
15498
15574
 
15499
- // src/search/cdp.ts
15500
- var SEARCH_URL = "https://search.brave.com/search?q=";
15501
- 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
15502
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;
15503
- function extractionScript(maxResults) {
15597
+ var MAX_LINKS = 400;
15598
+ var BODY_TEXT_CHARS = 4e3;
15599
+ function collectScript() {
15504
15600
  return `(() => {
15505
15601
  const clean = s => (s || '').replace(/\\s+/g, ' ').trim();
15506
15602
  const visible = el => {
@@ -15508,64 +15604,102 @@ function extractionScript(maxResults) {
15508
15604
  const st = getComputedStyle(el);
15509
15605
  return r.width > 0 && r.height > 0 && st.display !== 'none' && st.visibility !== 'hidden';
15510
15606
  };
15511
- const own = ${OWN_HOSTS.toString()};
15512
- // A result anchor's innerText is "SiteName / breadcrumb \u203A path / actual title" on separate lines.
15513
- // The last line is the title; the earlier ones are chrome that would otherwise be fed to the model
15514
- // as part of it. No class names involved, so a redesign degrades this to "whole text", not to junk.
15515
- const dateLine = ${DATE_LINE.toString()};
15516
- const titleOf = a => {
15517
- const lines = (a.innerText || '').split('\\n').map(clean).filter(Boolean);
15518
- const named = lines.filter(l => !dateLine.test(l));
15519
- return named.length ? named[named.length - 1] : '';
15520
- };
15607
+ const chromeSel = 'header,footer,nav,[role=banner],[role=contentinfo],[role=navigation]';
15521
15608
  // The container repeats the anchor's own text before the description; removing it stops every
15522
15609
  // snippet from opening with a copy of the title it sits under.
15523
- const snippetFor = (a, title) => {
15524
- const anchorText = clean(a.innerText || '');
15610
+ const snippetFor = a => {
15611
+ const own = clean(a.textContent);
15525
15612
  let node = a.parentElement;
15526
15613
  for (let depth = 0; node && depth < 4; depth++, node = node.parentElement) {
15527
15614
  // Stop before climbing into a container that groups several results, or the snippet picks up
15528
15615
  // the *next* result's title. A block holding many links is a group, not one result's body.
15529
15616
  if (node.querySelectorAll('a[href]').length > 3) break;
15530
- const full = clean(node.innerText || '');
15531
- if (full.length <= anchorText.length + 40) continue;
15532
- 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(' '));
15533
15620
  if (body.length >= 20) return body.slice(0, 300);
15534
15621
  }
15535
15622
  return '';
15536
15623
  };
15537
- const seen = new Set();
15538
- 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();
15539
15660
  const results = [];
15540
- for (const a of document.querySelectorAll('a[href]')) {
15541
- if (results.length >= ${maxResults}) break;
15542
- if (!visible(a)) continue;
15543
- 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);
15544
15665
  if (title.length < 8) continue;
15545
- let u;
15546
- try { u = new URL(a.href); } catch { continue; }
15547
- if (!/^https?:$/.test(u.protocol)) continue;
15548
- if (own.test(u.hostname)) continue;
15549
- const key = u.hostname + u.pathname;
15666
+ const url = resultUrl(link.href, engine);
15667
+ if (!url) continue;
15668
+ const key = keyOf(url);
15550
15669
  if (seen.has(key)) continue;
15551
- // A result with a nested sub-link cluster (issues, discussions) contributes a run of tightly
15552
- // packed anchors from one host in DOM order, which crowds out every lower-ranked result. Two
15553
- // per host keeps that from turning eight slots into one site's sitemap.
15554
- const used = perHost.get(u.hostname) || 0;
15670
+ const used = perHost.get(url.hostname) ?? 0;
15555
15671
  if (used >= 2) continue;
15556
- perHost.set(u.hostname, used + 1);
15672
+ perHost.set(url.hostname, used + 1);
15557
15673
  seen.add(key);
15558
- 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) });
15559
15677
  }
15560
- return JSON.stringify({
15561
- results,
15562
- anchors: document.querySelectorAll('a[href]').length,
15563
- blocked: /verifying you|not a bot|unusual traffic|are you a robot|verify you are human|complete the security check|traditional captcha/i
15564
- .test(document.body ? document.body.innerText : ''),
15565
- });
15566
- })()`;
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;
15567
15698
  }
15568
- 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;
15569
15703
  var CHALLENGE_WAIT_MS = 12e4;
15570
15704
  var CHALLENGE_POLL_MS = 1e3;
15571
15705
  var CdpSearchProvider = class {
@@ -15573,26 +15707,63 @@ var CdpSearchProvider = class {
15573
15707
  this.host = host;
15574
15708
  this.waitMs = opts.challengeWaitMs ?? CHALLENGE_WAIT_MS;
15575
15709
  this.pollMs = opts.challengePollMs ?? CHALLENGE_POLL_MS;
15710
+ this.engines = opts.engines ?? ENGINE_ORDER;
15576
15711
  }
15577
15712
  host;
15578
15713
  waitMs;
15579
15714
  pollMs;
15715
+ engines;
15580
15716
  // One challenge at a time. Parallel searches in a turn are all refused together, and the solve
15581
15717
  // is profile-wide: the first to hit it raises its own tab and waits, the rest wait on the same
15582
15718
  // promise and then simply reload — a second raised window would compete for the user's one solve.
15583
15719
  challenge;
15584
15720
  async search(query, opts = {}) {
15585
15721
  const max = opts.maxResults ?? 8;
15586
- 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);
15587
15753
  const tab = await this.host.newTab();
15588
15754
  let holdOpen = false;
15589
15755
  try {
15590
15756
  await tab.navigate(url);
15591
- let data = parseExtraction(await tab.evaluate(extractionScript(max)));
15592
- 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
+ }
15593
15764
  const owner = !this.challenge;
15594
15765
  if (owner) {
15595
- this.challenge = this.awaitSolve(tab, max, opts).finally(() => {
15766
+ this.challenge = this.awaitSolve(tab, engine, max, opts).finally(() => {
15596
15767
  this.challenge = void 0;
15597
15768
  });
15598
15769
  }
@@ -15603,19 +15774,14 @@ var CdpSearchProvider = class {
15603
15774
  throw e;
15604
15775
  }
15605
15776
  await tab.navigate(url);
15606
- data = parseExtraction(await tab.evaluate(extractionScript(max)));
15607
- 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);
15608
15780
  }
15609
- const results = (data.results ?? []).filter((r) => r.url && r.url.trim().length > 0).slice(0, max).map((r) => ({
15610
- title: r.title ?? "",
15611
- url: r.url,
15612
- snippet: r.snippet ?? "",
15613
- source: "brave"
15614
- }));
15615
15781
  debugLog(
15616
- `[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`
15617
15783
  );
15618
- return results;
15784
+ return picked.map((r) => ({ ...r, source: engine.name }));
15619
15785
  } finally {
15620
15786
  if (!holdOpen) await tab.close();
15621
15787
  }
@@ -15624,34 +15790,49 @@ var CdpSearchProvider = class {
15624
15790
  // (the page is mid-navigation after the solve, or the user closed the tab) is not a verdict;
15625
15791
  // the deadline is. The window goes back down only on success: on timeout it stays where the user
15626
15792
  // will find it, with the unsolved check on it.
15627
- async awaitSolve(tab, max, opts) {
15793
+ async awaitSolve(tab, engine, max, opts) {
15628
15794
  await tab.show();
15629
15795
  opts.onChallenge?.("raised");
15630
- debugLog("[cdp] bot check: window raised, waiting for the user");
15796
+ debugLog(`[cdp] ${engine.name} bot check: window raised, waiting for the user`);
15631
15797
  const deadline = Date.now() + this.waitMs;
15632
15798
  let last;
15633
15799
  for (; ; ) {
15634
15800
  await sleep2(this.pollMs);
15635
15801
  try {
15636
- last = parseExtraction(await tab.evaluate(extractionScript(max)));
15637
- if (!interstitial(last)) break;
15802
+ last = parsePage2(await tab.evaluate(collectScript()));
15803
+ if (!interstitial(engine, last, pickResults(last, engine, max).length)) break;
15638
15804
  } catch {
15639
15805
  }
15640
15806
  if (Date.now() >= deadline) {
15641
- debugLog("[cdp] bot check: not completed within the wait");
15642
- throw unavailable(last ?? { blocked: true }, true);
15807
+ debugLog(`[cdp] ${engine.name} bot check: not completed within the wait`);
15808
+ throw unavailable(engine, last, true);
15643
15809
  }
15644
15810
  }
15645
- debugLog("[cdp] bot check cleared");
15811
+ debugLog(`[cdp] ${engine.name} bot check cleared`);
15646
15812
  await tab.hide();
15647
15813
  opts.onChallenge?.("cleared");
15648
15814
  }
15649
15815
  };
15650
- function interstitial(data) {
15651
- return !!data.blocked || (data.results ?? []).length === 0 && (data.anchors ?? 0) < MIN_SERP_ANCHORS;
15652
- }
15653
- function unavailable(data, timedOut = false) {
15654
- 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`;
15655
15836
  return new SearchUnavailableError(
15656
15837
  message,
15657
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
@@ -15660,15 +15841,21 @@ function unavailable(data, timedOut = false) {
15660
15841
  function sleep2(ms) {
15661
15842
  return new Promise((r) => setTimeout(r, ms));
15662
15843
  }
15663
- function parseExtraction(raw) {
15844
+ function parsePage2(raw) {
15664
15845
  if (typeof raw !== "string") {
15665
15846
  throw new Error("the search page returned nothing to extract");
15666
15847
  }
15848
+ let page;
15667
15849
  try {
15668
- return JSON.parse(raw);
15850
+ page = JSON.parse(raw);
15669
15851
  } catch {
15670
15852
  throw new Error("could not parse results from the search page");
15671
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
+ };
15672
15859
  }
15673
15860
 
15674
15861
  // src/tools/index.ts
@@ -16525,14 +16712,25 @@ function observeNoteSlot(obs) {
16525
16712
 
16526
16713
  // src/agent/readtrace.ts
16527
16714
  var FILE_OVERLAP_DEPTH = 4;
16715
+ var DEPTH_WITHOUT_PROGRESS = 5;
16528
16716
  var MAX_NARROWINGS = 3;
16529
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;
16530
16724
  // Keyed (path, offset), limit-normalized — matches the loop's repeatKey. A model re-reading the
16531
16725
  // same start line with a different window is the same re-read, not forward paging to a new region.
16532
16726
  // The window is still carried in the entry (not the key) for the narrowing carve-out below, which
16533
16727
  // needs to compare against the previous request rather than fork a new region for every window.
16534
16728
  seen = /* @__PURE__ */ new Map();
16535
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;
16536
16734
  counts = {
16537
16735
  unique: 0,
16538
16736
  changed: 0,
@@ -16570,7 +16768,8 @@ var ReadTrace = class {
16570
16768
  repeats = 1;
16571
16769
  narrowings = prior.narrowings + 1;
16572
16770
  } else {
16573
- repeats = prior.repeats + 1;
16771
+ const priorGone = !!prior.msg && this.isGone(prior.msg);
16772
+ repeats = priorGone ? prior.repeats : prior.repeats + 1;
16574
16773
  cls = round - prior.round <= 1 ? "dup-live" : "dup-aged";
16575
16774
  narrowings = prior.narrowings;
16576
16775
  }
@@ -16584,6 +16783,7 @@ var ReadTrace = class {
16584
16783
  narrowings,
16585
16784
  lastLive: cls === "dup-live"
16586
16785
  });
16786
+ this.lastKey.set(path, key);
16587
16787
  this.counts[cls]++;
16588
16788
  this.recordFile(path, offset, window, hash, round, cls, via);
16589
16789
  return { cls, repeats };
@@ -16600,15 +16800,35 @@ var ReadTrace = class {
16600
16800
  const hi = window === Infinity ? Infinity : lo + window - 1;
16601
16801
  let f = this.files.get(path);
16602
16802
  if (!f || f.hash !== hash) {
16603
- 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
+ };
16604
16812
  this.files.set(path, f);
16605
16813
  }
16606
16814
  f.lastVia = via;
16607
16815
  if (cls !== "narrowed" && cls !== "regrounded") {
16608
- 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)];
16609
16829
  let depth = 1;
16610
16830
  for (const p of points) {
16611
- 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;
16612
16832
  if (stacked > depth) depth = stacked;
16613
16833
  }
16614
16834
  if (depth > f.depth) {
@@ -16618,7 +16838,20 @@ var ReadTrace = class {
16618
16838
  f.lastRound = round;
16619
16839
  }
16620
16840
  }
16621
- 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;
16622
16855
  }
16623
16856
  // Regions the model is looping on, re-read within the last `recentWithin` rounds of
16624
16857
  // `currentRound`. Two-tier threshold: a dup-live region (content still in context — re-reading it
@@ -16639,9 +16872,10 @@ var ReadTrace = class {
16639
16872
  const named = new Set(out.map((l) => l.path));
16640
16873
  for (const [path, f] of this.files) {
16641
16874
  if (named.has(path)) continue;
16642
- if (currentRound - f.lastRound > recentWithin) continue;
16643
- if (f.depth >= FILE_OVERLAP_DEPTH) {
16875
+ if (f.depth >= FILE_OVERLAP_DEPTH && currentRound - f.lastRound <= recentWithin) {
16644
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 });
16645
16879
  }
16646
16880
  }
16647
16881
  return out;
@@ -16659,8 +16893,12 @@ var ReadTrace = class {
16659
16893
  if (e.repeats >= 3) looped++;
16660
16894
  }
16661
16895
  let overlapped = 0;
16662
- for (const f of this.files.values()) if (f.depth >= FILE_OVERLAP_DEPTH) overlapped++;
16663
- 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}`;
16664
16902
  }
16665
16903
  };
16666
16904
  function priorCopyState(prior, history, prefixStable) {
@@ -17222,6 +17460,42 @@ var ReasoningTrace = class {
17222
17460
  }
17223
17461
  };
17224
17462
 
17463
+ // src/agent/contentspin.ts
17464
+ var CONTENT_SPIN_MIN_CHARS = 16e3;
17465
+ var CONTENT_SPIN_RATIO = 0.8;
17466
+ var CONTENT_SPIN_DEBOUNCE = 2e3;
17467
+ var CONTENT_SPIN_WINDOWS = [CONTENT_SPIN_MIN_CHARS, 32e3, 64e3];
17468
+ function fenceOpenAtTail(text) {
17469
+ let open2 = null;
17470
+ for (const m of text.matchAll(/^ {0,3}(`{3,}|~{3,})(.*)$/gm)) {
17471
+ const fence = m[1];
17472
+ if (!open2) open2 = fence;
17473
+ else if (fence[0] === open2[0] && fence.length >= open2.length && !m[2].trim()) open2 = null;
17474
+ }
17475
+ return open2 !== null;
17476
+ }
17477
+ function contentSpinSignal(content) {
17478
+ const chars = content.length;
17479
+ if (chars < CONTENT_SPIN_MIN_CHARS)
17480
+ return { spinning: false, ratio: 0, window: 0, chars, fence: false };
17481
+ let ratio = 0;
17482
+ let window = 0;
17483
+ for (const w of CONTENT_SPIN_WINDOWS) {
17484
+ const r = selfRepeatRatio(content.slice(-w));
17485
+ if (r > ratio) {
17486
+ ratio = r;
17487
+ window = Math.min(w, chars);
17488
+ }
17489
+ }
17490
+ return {
17491
+ spinning: ratio >= CONTENT_SPIN_RATIO,
17492
+ ratio,
17493
+ window,
17494
+ chars,
17495
+ fence: fenceOpenAtTail(content)
17496
+ };
17497
+ }
17498
+
17225
17499
  // src/agent/continuation.ts
17226
17500
  var CONTINUATION_TAIL_CHARS = envInt("REIKA_CONTINUE_TAIL_CHARS", 6e3);
17227
17501
  var BOUNDARY_SEARCH_FRACTION = 0.25;
@@ -18134,15 +18408,46 @@ function runTscProcess(bin, args, cwd, timeoutMs, signal, viaSandboxWrapper = fa
18134
18408
  var TRACKED_TOOLS = /* @__PURE__ */ new Set(["read", "grep", "list", "glob", "bash"]);
18135
18409
  var WEB_LOOKUP_ARG = { search: "query", fetch_url: "url" };
18136
18410
  var MUTATING_TOOLS = /* @__PURE__ */ new Set(["write", "edit"]);
18137
- function willMutate(name, args, cwd) {
18138
- if (MUTATING_TOOLS.has(name)) return true;
18139
- if (name !== "bash") return false;
18140
- 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;
18141
18448
  }
18142
18449
  function typecheckAnchor(name, args, cwd) {
18143
- if (MUTATING_TOOLS.has(name)) return typeof args.path === "string" ? args.path : void 0;
18144
- if (name !== "bash") return void 0;
18145
- return writeTargets(String(args.command ?? ""), cwd)[0];
18450
+ return typeRelevantTargets(name, args, cwd)[0] || void 0;
18146
18451
  }
18147
18452
  function didMutate(name, changes) {
18148
18453
  if (MUTATING_TOOLS.has(name)) return true;
@@ -18213,6 +18518,8 @@ var MAX_VERBATIM_RECOVERIES = 2;
18213
18518
  var REASONING_HARD_CEIL = ceilFromEnv("REIKA_REASONING_CEIL", 32e3);
18214
18519
  var FORCE_WRITE_REASONING_CEIL = 12e3;
18215
18520
  var VERBATIM_ABORT = process.env.REIKA_VERBATIM_ABORT !== "0";
18521
+ var CONTENT_SPIN = process.env.REIKA_CONTENT_SPIN !== "0";
18522
+ var MAX_CONTENT_SPIN_RECOVERIES = 1;
18216
18523
  var CONTINUE = process.env.REIKA_CONTINUE !== "0";
18217
18524
  var CONTINUE_NUDGE = "(your previous response was cut off at the token limit. the text above is your own work \u2014 it ends mid-thought. continue from that exact point. any earlier part was trimmed to fit; what remains is your most recent working. do not start over, and do not re-run tools you have already called \u2014 their results are above.)";
18218
18525
  var PLAN_WRITE_CONTINUE_NUDGE = "(your plan write was cut off at the reasoning length limit. the text above is your own work \u2014 it ends mid-thought. continue from that exact point and then write the numbered plan. any earlier part was trimmed to fit; what remains is your most recent working. do not start over.)";
@@ -18455,34 +18762,50 @@ function withdrawalRemedy(toolNames) {
18455
18762
  }
18456
18763
  return "Answer from what you already have";
18457
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
+ }
18458
18774
  function withdrawnLedgerLines(toolNames) {
18459
18775
  if (toolNames.has("edit") || toolNames.has("write")) {
18460
18776
  return [
18461
18777
  "Reading and searching are now PAUSED. Make the edit the task requires with the edit/write",
18462
18778
  "tools, state specifically what is still blocking you, or \u2014 if the change is already complete \u2014",
18463
- "say so and stop."
18779
+ "say so and stop.",
18780
+ withdrawalReturn(toolNames)
18464
18781
  ];
18465
18782
  }
18466
18783
  if (toolNames.has("bash")) {
18467
18784
  return [
18468
18785
  "Reading and searching are now PAUSED. Make the change the task requires by running the",
18469
18786
  "command that applies it, state specifically what is still blocking you, or \u2014 if the change",
18470
- "is already complete \u2014 say so and stop."
18787
+ "is already complete \u2014 say so and stop.",
18788
+ withdrawalReturn(toolNames)
18471
18789
  ];
18472
18790
  }
18473
18791
  return [
18474
18792
  "Reading and searching are now PAUSED. Answer from what you already have, state specifically",
18475
- "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)
18476
18795
  ];
18477
18796
  }
18478
18797
  function buildWithdrawalDirective(toolNames) {
18479
- 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)})`;
18480
18799
  }
18481
18800
  function shouldWithdrawInspection(opts) {
18482
18801
  if (opts.loopActiveRounds < LOOP_WITHDRAW_AFTER) return false;
18483
18802
  return !opts.editRecovery;
18484
18803
  }
18485
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
+ }
18486
18809
  function holdWithdrawal(opts) {
18487
18810
  if (opts.since === void 0 || opts.mutated || opts.editRecovery) return false;
18488
18811
  return opts.round - opts.since < WITHDRAW_HOLD_ROUNDS;
@@ -18513,17 +18836,27 @@ function prefixed(ledger) {
18513
18836
  return ledger ? "\n" + ledger : "";
18514
18837
  }
18515
18838
  function droppedPayloadLedgerFor(history, prefixStable) {
18516
- 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 : "")) : "";
18517
18842
  }
18843
+ var DROPPED_LEDGER_MAX_LISTED = 8;
18844
+ var DROPPED_LEDGER_SUMMARY_CHARS = 100;
18518
18845
  var DROPPED_LEDGER_MARKER = "Their output was dropped to make room";
18519
- 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;
18520
18850
  return [
18521
- "--- reika status (auto-generated \u2014 not user input) ---",
18522
- "Some tool results above now show only their summary line (e.g. `Ran: \u2026 (505 bytes output)`)",
18523
- `or a short outline of the output. ${DROPPED_LEDGER_MARKER}; it is not in your context`,
18524
- "any more. That is a context limit, not a failed command, and it does not mean you already",
18525
- "handled the result. If you need what one of them returned, re-run that call \u2014 do not answer",
18526
- "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."
18527
18860
  ].join("\n");
18528
18861
  }
18529
18862
  function buildQuestionLedger(answers) {
@@ -18570,6 +18903,10 @@ ${failure.excerpt}
18570
18903
 
18571
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.)`;
18572
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
+ }
18573
18910
  async function runTurn(opts) {
18574
18911
  if (!opts.manualCompact) {
18575
18912
  const userMsg = {
@@ -18623,6 +18960,7 @@ ${SUBAGENT_REPORT_FRAME}` : promptForMode;
18623
18960
  } : void 0;
18624
18961
  const shrink = { ...opts.priorShrink ?? { sheds: 0, folds: 0 } };
18625
18962
  let lengthRetries = 0;
18963
+ let contentSpinRecoveries = 0;
18626
18964
  const continuation = new ContinuationGate();
18627
18965
  let pendingContinuation = "";
18628
18966
  let pendingReasoning = "";
@@ -18662,10 +19000,11 @@ ${SUBAGENT_REPORT_FRAME}` : promptForMode;
18662
19000
  let planGateRounds = 0;
18663
19001
  const seenReadOnly = /* @__PURE__ */ new Map();
18664
19002
  const seenWebLookups = /* @__PURE__ */ new Set();
18665
- const readTrace = new ReadTrace();
19003
+ const readTrace = new ReadTrace((m) => priorCopyState(m, opts.history, prefixStable) === "yes");
18666
19004
  const lastReadMessage = /* @__PURE__ */ new Map();
18667
19005
  const prevAgedField = (cls, key) => cls === "dup-live" || cls === "dup-aged" ? ` prevAged=${priorCopyState(lastReadMessage.get(key), opts.history, prefixStable)}` : "";
18668
19006
  const readFirst = new ReadFirstGate(opts.bundle.cwd);
19007
+ const refusedArgEchoes = /* @__PURE__ */ new Set();
18669
19008
  const reasoningTrace = new ReasoningTrace();
18670
19009
  let reasoningLoopActive = false;
18671
19010
  let reasoningChannel = "reasoning";
@@ -19252,6 +19591,7 @@ ${COMPACTION_REPORT_RETRY}`, refusedCallTurn(rep));
19252
19591
  }
19253
19592
  }
19254
19593
  let agedThisRound = false;
19594
+ let agedOutputs = 0;
19255
19595
  if (prefixStable && window && !planForceWrite) {
19256
19596
  const aged = batchAgePayloads(
19257
19597
  opts.history,
@@ -19265,9 +19605,10 @@ ${COMPACTION_REPORT_RETRY}`, refusedCallTurn(rep));
19265
19605
  !latchesFor(opts.config).reasoningRoundtrip
19266
19606
  );
19267
19607
  agedThisRound = aged.marked > 0;
19608
+ agedOutputs = aged.bulk + aged.crumbs;
19268
19609
  if (aged.marked > 0) {
19269
19610
  debugLog(
19270
- `[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}
19271
19612
  `
19272
19613
  );
19273
19614
  shrink.sheds++;
@@ -19302,6 +19643,14 @@ ${COMPACTION_REPORT_RETRY}`, refusedCallTurn(rep));
19302
19643
  });
19303
19644
  }
19304
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
+ }
19305
19654
  if (opts.manualCompact) {
19306
19655
  if (lastFoldRemoved === 0) {
19307
19656
  opts.onMessage({
@@ -19345,7 +19694,7 @@ ${roundSuffix}` : dropped;
19345
19694
  if (opts.signal.aborted) callAbort.abort();
19346
19695
  else opts.signal.addEventListener("abort", () => callAbort.abort(), { once: true });
19347
19696
  }
19348
- const canAbortVerbatim = VERBATIM_ABORT && (verbatimRecoveries < MAX_VERBATIM_RECOVERIES || steerRetryActive);
19697
+ const canAbortVerbatim = VERBATIM_ABORT && !subagentForceReport && (verbatimRecoveries < MAX_VERBATIM_RECOVERIES || steerRetryActive);
19349
19698
  const trackSpin = !!opts.onReasoningStatus || debugEnabled() || canAbortVerbatim;
19350
19699
  const onReasoningDelta = trackSpin ? (delta) => {
19351
19700
  opts.onReasoningDelta?.(delta);
@@ -19374,13 +19723,40 @@ ${roundSuffix}` : dropped;
19374
19723
  callAbort.abort();
19375
19724
  }
19376
19725
  } : opts.onReasoningDelta;
19726
+ let roundContent = "";
19727
+ let contentCheckedAt = 0;
19728
+ let contentSpinCut = false;
19729
+ const contentSpinExempt = i >= opts.config.maxTurns - 1 || planForceWrite || convergeSteerNow || !!logitBias;
19730
+ const contentSpinBudgetLeft = contentSpinRecoveries < MAX_CONTENT_SPIN_RECOVERIES;
19731
+ const canCutContentSpin = CONTENT_SPIN && contentSpinBudgetLeft && !contentSpinExempt;
19732
+ const onContentDelta = canCutContentSpin || debugEnabled() ? (delta) => {
19733
+ opts.onContentDelta?.(delta);
19734
+ roundContent += delta;
19735
+ if (contentSpinCut) return;
19736
+ if (roundContent.length - contentCheckedAt < CONTENT_SPIN_DEBOUNCE) return;
19737
+ contentCheckedAt = roundContent.length;
19738
+ const reading = contentSpinSignal(roundContent);
19739
+ if (reading.chars < CONTENT_SPIN_MIN_CHARS) return;
19740
+ const cut = canCutContentSpin && reading.spinning;
19741
+ const gate = cut ? "cut" : !reading.spinning ? "measure" : !CONTENT_SPIN ? "off" : contentSpinExempt ? "exempt" : "spent";
19742
+ if (debugEnabled()) {
19743
+ debugLog(
19744
+ `[reika:debug] content-spin round=${i} ratio=${reading.ratio.toFixed(2)} window=${reading.window} chars=${reading.chars} fence=${reading.fence ? "yes" : "no"} gate=${gate}
19745
+ `
19746
+ );
19747
+ }
19748
+ if (cut) {
19749
+ contentSpinCut = true;
19750
+ callAbort.abort();
19751
+ }
19752
+ } : opts.onContentDelta;
19377
19753
  const live = startLiveRound(() => sentEstimate);
19378
19754
  const response = await callModel({
19379
19755
  system,
19380
19756
  history: callHistory,
19381
19757
  tools: sentTools,
19382
19758
  config: withGenReserve(opts.config, genReserve),
19383
- onContentDelta: opts.onContentDelta,
19759
+ onContentDelta,
19384
19760
  onReasoningDelta,
19385
19761
  onOutputDelta: live && ((text) => live.add(text)),
19386
19762
  onEngineTimings: live && ((timings, prompt) => live.engine(timings, prompt)),
@@ -19425,10 +19801,10 @@ ${roundSuffix}` : dropped;
19425
19801
  // outline, and how many were small enough that keeping them whole cost less than the marker.
19426
19802
  // Silent when nothing is aged yet, so early rounds add no noise.
19427
19803
  onAgedStats: debugEnabled() ? (a) => {
19428
- 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;
19429
19805
  if (total === 0) return;
19430
19806
  debugLog(
19431
- `[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}
19432
19808
  `
19433
19809
  );
19434
19810
  } : void 0,
@@ -19617,6 +19993,25 @@ ${roundReasoning}` : roundReasoning;
19617
19993
  );
19618
19994
  return;
19619
19995
  }
19996
+ if (contentSpinCut) {
19997
+ contentSpinRecoveries++;
19998
+ pendingContinuation = "";
19999
+ pendingReasoning = "";
20000
+ opts.onReasoningReset?.();
20001
+ opts.onMessage({
20002
+ role: "system",
20003
+ tone: "warn",
20004
+ content: "Output was repeating itself \u2014 stopped it and retrying."
20005
+ });
20006
+ opts.history.push({
20007
+ role: "user",
20008
+ content: "(your previous response was repeating the same text over and over and was stopped. answer the question or call a tool directly, without repeating yourself)",
20009
+ // Not a turn boundary (#287), for the same reason the truncation nudge isn't: this fires on
20010
+ // rounds where the task spec matters most, and re-electing the pin costs the model a re-fetch.
20011
+ harness: true
20012
+ });
20013
+ continue;
20014
+ }
19620
20015
  const toolCalls = planForceWrite || subagentForceReport ? [] : response.toolCalls ?? [];
19621
20016
  const isFinal = toolCalls.length === 0;
19622
20017
  const rsn = response.reasoning ?? "";
@@ -19627,7 +20022,7 @@ ${rsn}` : rsn;
19627
20022
  ${roundText}` : roundText;
19628
20023
  const cutOffMidThought = response.finishReason === "length" && isFinal;
19629
20024
  let continueRound = false;
19630
- if (CONTINUE && cutOffMidThought && carriedBlock.trim()) {
20025
+ if (CONTINUE && cutOffMidThought && carriedBlock.trim() && !subagentForceReport) {
19631
20026
  const gate = continuationGate(carriedBlock);
19632
20027
  const allow = continuation.allow(roundText);
19633
20028
  continueRound = gate.continuable && allow.ok;
@@ -19682,7 +20077,7 @@ ${response.content}`,
19682
20077
  }
19683
20078
  pendingContinuation = "";
19684
20079
  pendingReasoning = "";
19685
- if (shouldRetryTruncated({
20080
+ if (!subagentForceReport && shouldRetryTruncated({
19686
20081
  finishReason: response.finishReason,
19687
20082
  hasToolCalls: !isFinal,
19688
20083
  priorRetries: lengthRetries
@@ -19901,6 +20296,9 @@ ${response.content}`,
19901
20296
  if (provenEdit) debugLog(`[reika:debug] round=${i} read-first proven ${call.args.path}
19902
20297
  `);
19903
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);
19904
20302
  let summary;
19905
20303
  let payload;
19906
20304
  let diff;
@@ -19916,7 +20314,7 @@ ${response.content}`,
19916
20314
  let groundsAuthored = false;
19917
20315
  let traceKey2;
19918
20316
  let planCheckoff;
19919
- 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)) {
19920
20318
  typecheckBaselineAttempted = true;
19921
20319
  typecheckTsconfig = await detectTsProject(
19922
20320
  opts.bundle.cwd,
@@ -19951,6 +20349,11 @@ ${response.content}`,
19951
20349
  debugLog(`[reika:debug] round=${i} read-first bounce ${blindPath} ${probe}
19952
20350
  `);
19953
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
+ `);
19954
20357
  } else if (heldForSubagent) {
19955
20358
  const label = refusedBashGrep ? "shell inspection" : call.name;
19956
20359
  summary = `${label} held \u2014 the subagent dispatched this round covers it`;
@@ -19963,6 +20366,10 @@ ${response.content}`,
19963
20366
  if (spillStatsEnabled() && Object.values(call.args).some((v) => typeof v === "string" && referencesSpill(v))) {
19964
20367
  recordFollowed({ by: call.name });
19965
20368
  }
20369
+ if (refusedArgEchoes.has(echoKey)) {
20370
+ debugLog(`[reika:debug] round=${i} age-args-echo resent tool=${call.name}
20371
+ `);
20372
+ }
19966
20373
  opts.onToolStart?.(call.name);
19967
20374
  const callStart = Date.now();
19968
20375
  try {
@@ -20073,16 +20480,19 @@ ${grounding}` : grounding;
20073
20480
  debugLog(`[reika:debug] tool-call round=${i} ${call.name} ${summary}
20074
20481
  `);
20075
20482
  }
20076
- if (tool && !refused && !bouncedBlindEdit && !heldForSubagent)
20483
+ if (tool && !refused && !bouncedBlindEdit && !heldForSubagent && !refusedArgEcho)
20077
20484
  payload = flagRepeatedCall(seenReadOnly, call.name, call.args, summary, payload);
20078
20485
  if (tool && !refused && payload && WEB_LOOKUP_ARG[call.name]) {
20079
20486
  seenWebLookups.add(`${call.name}\0${String(call.args[WEB_LOOKUP_ARG[call.name]] ?? "")}`);
20080
20487
  }
20081
- if (!bouncedBlindEdit && didMutate(call.name, changes)) {
20488
+ if (!bouncedBlindEdit && !refusedArgEcho && didMutate(call.name, changes)) {
20082
20489
  editingStarted = true;
20083
- mutatedSinceWithdrawal = true;
20490
+ if (!MUTATING_TOOLS.has(call.name) || /^(Edited|Wrote) /.test(summary))
20491
+ readTrace.noteProgress();
20084
20492
  }
20085
- 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)) {
20086
20496
  if (summary.startsWith("Edited ") || summary.startsWith("Wrote ")) {
20087
20497
  lastEditFailed = false;
20088
20498
  lastEditFailure = void 0;
@@ -20143,7 +20553,10 @@ ${grounding}` : grounding;
20143
20553
  };
20144
20554
  opts.history.push(toolMsg);
20145
20555
  opts.onMessage(toolMsg);
20146
- 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
+ }
20147
20560
  if (groundsPath) {
20148
20561
  readFirst.ground(groundsPath, groundsAuthored ? void 0 : opts.history.length - 1);
20149
20562
  }
@@ -21218,7 +21631,7 @@ function scrubLines(s) {
21218
21631
  return s.split("\n").map((line) => scrubDisplay(line)).join("\n");
21219
21632
  }
21220
21633
 
21221
- // src/ui/harnessecho.ts
21634
+ // src/display/harnessecho.ts
21222
21635
  var HARNESS_ECHO_LINE = /^\s*(?:\[reika:[^\]\n]*\]|\(reika:[^)\n]*\)|\[tool (?:result|output)[^\]\n]*\])\s*$/;
21223
21636
  function stripHarnessEcho(content) {
21224
21637
  let rest = content;
@@ -21232,7 +21645,7 @@ function stripHarnessEcho(content) {
21232
21645
  return rest === content ? content : rest.trimStart();
21233
21646
  }
21234
21647
 
21235
- // src/ui/reasoningfold.ts
21648
+ // src/display/reasoningfold.ts
21236
21649
  var RUN_DELIMITERS = ["`", "'", '"'];
21237
21650
  function countChar(line, ch) {
21238
21651
  let n = 0;
@@ -21770,6 +22183,7 @@ export {
21770
22183
  toolVerb,
21771
22184
  toolTimer,
21772
22185
  changeLabel,
22186
+ diffStatRuns,
21773
22187
  formatContext,
21774
22188
  formatCache,
21775
22189
  autoApproves,