@alexwkleung/reika 0.8.0 → 0.10.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.
@@ -1,3 +1,4 @@
1
+ import { isAbsolute, relative } from 'node:path';
1
2
  import { buildSystemPrompt } from './prompt.js';
2
3
  import { callModel } from '../provider/client.js';
3
4
  import { latchesFor } from '../provider/latches.js';
@@ -6,12 +7,13 @@ import { isLocalEngine } from '../provider/templatekwargs.js';
6
7
  import { estimateRequestTokens, estimateTokens } from '../provider/tokens.js';
7
8
  import { computeMaxTokens, NATIVE_IMAGE_TOKEN_ALLOWANCE, shouldRetryTruncated, } from '../provider/budget.js';
8
9
  import { compactHistory, shouldCompact, compactThreshold, gatherPlanFindings, distillPlanHandoff, batchAgePayloads, AGE_LOW_FRACTION, } from './compaction.js';
9
- import { droppedPayloadCount, findFreshToolBlockStart, hasDroppedPayloads, lastUserMessageIndex, taskSpecIndex, toolsToChatTools, } from '../provider/toolcall.js';
10
+ import { droppedPayloadCount, findFreshToolBlockStart, hasDroppedPayloads, lastUserMessageIndex, oversizeOpeningPayloadIndex, taskSpecIndex, toolsToChatTools, } from '../provider/toolcall.js';
10
11
  import { ReadTrace } from './readtrace.js';
11
12
  import { traceBashRead, traceReadPath } from './bashread.js';
12
13
  import { PrefixTrace } from './prefixtrace.js';
13
14
  import { PrefillRate, formatMeasuredPrefill, formatPrefillCost, reprocessedTokens, sampleTokens, } from './prefillcost.js';
14
15
  import { DecodeRate, decodeSample, formatRate } from './decoderate.js';
16
+ import { LiveRound } from './liveusage.js';
15
17
  import { GenReserve, resolveGenReserve, withGenReserve } from './genreserve.js';
16
18
  import { selfRepeatRatio, repeatedSelfShingles, ReasoningTrace, liveSpinSignal, verbatimAbortThreshold, } from './reasoningtrace.js';
17
19
  import { ContinuationGate, continuationGate, continuationTail } from './continuation.js';
@@ -28,7 +30,7 @@ import { writeTargets } from '../tools/_writetargets.js';
28
30
  import { READ_DEFAULT_LIMIT } from '../tools/read.js';
29
31
  import { recordFollowed, spillStatsEnabled } from '../tools/_spillstats.js';
30
32
  import { seedPlanProgress, parsePlanSteps, planChanged, refineTarget, applyEdit as applyPlanEdit, applyCommand as applyPlanCommand, buildPlanProgressLedger, decidePlanGate, waiveUnchecked, ranSuccessfully, MAX_PLAN_GATE_ROUNDS, } from './plantrack.js';
31
- import { ReadFirstGate, buildReadFirstDirective, probeWouldLand } from './readfirst.js';
33
+ import { ReadFirstGate, buildReadFirstDirective, oldStringProvesBytes, probeWouldLand, } from './readfirst.js';
32
34
  import { SUBAGENT_REPORT_DIRECTIVE, SUBAGENT_REPORT_FRAME, SUBAGENT_HOLD_NOTE, MAX_SUBAGENTS_PER_TURN, MAX_SUBAGENTS_PER_ROUND, buildCoverageNote, } from './subagentreport.js';
33
35
  import { COMPACTION_REPORT_RETRY, compactionNotePrefill, notePrefillEnabled, prefilledNoteStream, prefilledReply, refusedCallTurn, buildCompactionReportDirective, clampCompactionNote, compactionNoteContent, compactionReportEnabled, pickCompactionNote, } from './compactionreport.js';
34
36
  import { buildSubagentAffordance, filesInResult, subagentPressureEnabled, underPressure, } from './subagentpressure.js';
@@ -378,6 +380,9 @@ const DROPPED_LEDGER = process.env.REIKA_DROPPED_LEDGER !== '0';
378
380
  // runs as-is), suspended while inspection tools are withdrawn (the directed read would be refused).
379
381
  // The `would-land=` field on the bounce debug line is the measurement. See agent/readfirst.ts.
380
382
  const READ_FIRST = process.env.REIKA_READ_FIRST !== '0';
383
+ // An exact, unique old_string passes the gate (#932, `=0` is the baseline arm for
384
+ // evals/fixtures/22-read-first-exact). See readfirst.ts oldStringProvesBytes.
385
+ const READ_FIRST_EXACT = process.env.REIKA_READ_FIRST_EXACT !== '0';
381
386
  // EXPERIMENT (#867): keep the offered tool list unchanged while inspection is withdrawn, enforcing
382
387
  // the pause at dispatch and through the ledger only. The template renders the tools ahead of the
383
388
  // system prompt, so dropping them makes the withdrawal round and the lift round each a full
@@ -732,6 +737,8 @@ const LOOP_TERMINAL_AFTER = 3;
732
737
  // gives one fix attempt plus a re-check; beyond that, finishing dirty (with a user notice) beats
733
738
  // spiralling. See check/typecheck.ts.
734
739
  const MAX_TYPECHECK_GATE_ROUNDS = 2;
740
+ const MAX_EMPTY_REPLY_RETRIES = 1;
741
+ const EMPTY_REPLY_NUDGE = '(your previous response was empty — no answer and no tool call. Continue the task: call the next tool, or give your answer.)';
735
742
  // Floor on the learned calibration when it drives the COMPACTION decision (not the UI gauge). The
736
743
  // calibration = real-tokens / char-4-estimate; a prose-heavy session drives it below 1 (~0.9), which
737
744
  // makes the trigger assume content is even sparser than the char/4 baseline. That optimism is what let
@@ -806,12 +813,12 @@ function withdrawnLedgerLines(toolNames) {
806
813
  // Returned in place of a withdrawn inspection call. No content, so it can't re-fuel the loop or
807
814
  // inflate context; it just states the rule and the way out. Built per turn rather than held as a
808
815
  // const because both halves — what is paused, and what to do instead — depend on the tool list.
816
+ // "now" is load-bearing: the hold lifts on its own, so a bare "gets this same reply" would be false.
809
817
  export function buildWithdrawalDirective(toolNames) {
810
- return (`(reika: ${withdrawnToolsPhrase(toolNames)} are paused because you have repeated the same ` +
811
- 'reads or searches without making progress. You already have what you need. ' +
812
- `${withdrawalRemedy(toolNames)}, state what is specifically blocking you, or — if the change ` +
813
- 'is already complete — say so and stop. Reading and searching are unavailable until you make ' +
814
- 'progress.)');
818
+ return (`(reika: this is deliberate, not a fault. ${withdrawnToolsPhrase(toolNames)} are paused ` +
819
+ 'because the work has repeated without making progress. Sending this call again now gets ' +
820
+ `this same reply, so do not retry it. ${withdrawalRemedy(toolNames)}, state what is ` +
821
+ 'specifically blocking you, or — if the change is already complete — say so and stop.)');
815
822
  }
816
823
  // Whether to escalate from the loop ledger to withdrawing the inspection tools. Fires once a loop has
817
824
  // stayed active LOOP_WITHDRAW_AFTER rounds (the ledger got its shot first), with exactly one
@@ -844,7 +851,7 @@ export function shouldWithdrawInspection(opts) {
844
851
  // without inspection, then the cycle again, each switch of the tool list a full re-prefill (~22 in
845
852
  // one 163-round run). Held until the tree changes instead, capped so a model that has declared
846
853
  // itself stuck gets reads back.
847
- export const WITHDRAW_HOLD_ROUNDS = 5;
854
+ export const WITHDRAW_HOLD_ROUNDS = 4;
848
855
  // Whether a withdrawal already in force stays on this round although the loop no longer reads as
849
856
  // active. `since` is the round it began; `mutated` is whether the tree has changed since then.
850
857
  export function holdWithdrawal(opts) {
@@ -973,6 +980,22 @@ export function buildEditRecoveryLedger(failure) {
973
980
  'here after all, say so and stop instead of retrying.',
974
981
  ].join('\n');
975
982
  }
983
+ // The edit-recovery dead-end's report. A `diverged` failure names the line that differs: the
984
+ // target is there, so "the plan may reference code that doesn't exist" would send the user hunting
985
+ // for a problem the file does not have.
986
+ export function buildEditRecoveryStopMessage(failure) {
987
+ const file = failure ? `\`${failure.path}\`` : 'the file';
988
+ if (failure?.kind === 'diverged') {
989
+ return (`My edit to ${file} didn't apply: line ${failure.divergentLine} differs from the text I ` +
990
+ `expected (expected \`${failure.expected}\`, the file has \`${failure.actual}\`). I've ` +
991
+ `stopped instead of looping. Ask me to continue and I'll re-read that part of the file and ` +
992
+ `retry the edit from its current text.`);
993
+ }
994
+ return (`I kept trying to edit ${file} but the text I expected isn't in the file, so the change can't ` +
995
+ `be applied as planned — the plan may reference code that doesn't exist there. I've stopped ` +
996
+ `instead of looping. Please confirm the change belongs in that file, or point me at the right ` +
997
+ `location.`);
998
+ }
976
999
  // Payload attached to an `absent` edit failure when the file's bytes are not in the model's context
977
1000
  // (see the call site). Rides the tool result rather than the system suffix: unlike the diverged
978
1001
  // recovery ledger — which must survive several rounds to reach a period-2 loop — this is consumed by
@@ -1184,6 +1207,8 @@ export async function runTurn(opts) {
1184
1207
  // line off) gets exactly ONE round with the divergence lifted into the system suffix before the
1185
1208
  // dead-end stop — the same "each tier gets one round" discipline as the rumination ladder. Set when
1186
1209
  // that round fires so a still-looping turn falls through to the stop instead of grounding forever.
1210
+ // Per failure, not per turn: a landed edit clears it, so a later failure on other code gets its own
1211
+ // round (a turn-wide guard stopped a second, unrelated failure on its first attempt).
1187
1212
  let editRecoveryGroundingTried = false;
1188
1213
  // One-shot guard for the Tier 2 logit-recovery round (REIKA_LOGIT_RECOVERY): the rumination
1189
1214
  // dead-end gets exactly ONE biased round before the terminal stop. Set when it fires so a
@@ -1213,6 +1238,7 @@ export async function runTurn(opts) {
1213
1238
  let typecheckTsconfig;
1214
1239
  // Consecutive done-gate send-backs this turn. Bounds the fix loop at MAX_TYPECHECK_GATE_ROUNDS.
1215
1240
  let typecheckGateRounds = 0;
1241
+ let emptyReplyRetries = 0;
1216
1242
  // Consecutive plan done-gate send-backs this turn. Bounds the plan gate at MAX_PLAN_GATE_ROUNDS.
1217
1243
  let planGateRounds = 0;
1218
1244
  // Per-turn memory of read-only calls already made, keyed by tool + result summary, so the
@@ -1295,6 +1321,29 @@ export async function runTurn(opts) {
1295
1321
  latches: latchesFor(opts.config),
1296
1322
  trailingNote: roundSuffix,
1297
1323
  });
1324
+ // A stream cut short never reaches its final usage chunk, but a hosted API has still billed it
1325
+ // (#906), so a cut round is counted from what streamed. A cut before any output counts nothing:
1326
+ // no decode happened. Goes to onUsage only, never onto the response: calibration, the decode rate
1327
+ // and the reserve read `response.usage`, and a learned value must not be fitted to our own guess.
1328
+ const reportUsage = (response, cut, promptEstimate) => {
1329
+ opts.onLiveUsage?.(undefined);
1330
+ if (response.usage) {
1331
+ opts.onUsage?.(response.usage);
1332
+ return;
1333
+ }
1334
+ const output = (response.reasoning ?? '') + (response.content ?? '');
1335
+ if (!cut || !output)
1336
+ return;
1337
+ opts.onUsage?.({
1338
+ promptTokens: Math.round(promptEstimate() * calibration),
1339
+ completionTokens: Math.round(estimateTokens(output) * Math.max(calibration, COMPACTION_CALIBRATION_FLOOR)),
1340
+ estimated: true,
1341
+ });
1342
+ };
1343
+ // Same densities as a cut round above, so the live figure and the one a cut leaves behind agree.
1344
+ const startLiveRound = (promptEstimate) => opts.onLiveUsage
1345
+ ? new LiveRound(Math.round(promptEstimate() * calibration), Math.max(calibration, COMPACTION_CALIBRATION_FLOOR), opts.onLiveUsage)
1346
+ : undefined;
1298
1347
  // Run a typecheck while pulsing the UI indicator around it (and clearing on any exit). The
1299
1348
  // pulse is human-only; the CheckOutcome flows to the gate logic, never to the model.
1300
1349
  const typecheck = async () => {
@@ -1614,11 +1663,8 @@ export async function runTurn(opts) {
1614
1663
  debugLog(`[reika:debug] round=${i} edit-recovery-stuck file=${file ?? '?'}\n`);
1615
1664
  const stuck = {
1616
1665
  role: 'assistant',
1617
- content: `I kept trying to edit ${file ? `\`${file}\`` : 'the file'} but the text I expected ` +
1618
- `isn't in the file, so the change can't be applied as planned — the plan may reference ` +
1619
- `code that doesn't exist there. I've stopped instead of looping. Please confirm the ` +
1620
- `change belongs in that file, or point me at the right location.` +
1621
- (await reportTypecheckAtStop()),
1666
+ content: buildEditRecoveryStopMessage(lastEditFailure) + (await reportTypecheckAtStop()),
1667
+ harnessStop: 'edit',
1622
1668
  durationMs: Date.now() - turnStart,
1623
1669
  ...(fetchedUrls.size > 0 ? { sources: [...fetchedUrls] } : {}),
1624
1670
  };
@@ -1811,12 +1857,17 @@ export async function runTurn(opts) {
1811
1857
  // task conflation, so it is greppable rather than something to re-derive from the history.
1812
1858
  const specIdx = taskSpecIndex(opts.history);
1813
1859
  const spec = specIdx >= 0 ? opts.history[specIdx] : undefined;
1860
+ const refused = opts.history[oversizeOpeningPayloadIndex(opts.history)];
1814
1861
  debugLog(specIdx >= 0 && spec?.role === 'tool'
1815
1862
  ? `[reika:debug] round=${i} spec-pin idx=${specIdx} chars=${spec.payload?.length ?? 0} ` +
1816
1863
  `holding=${specIdx < findFreshToolBlockStart(opts.history)} ` +
1817
1864
  `stale=${specIdx < lastUserMessageIndex(opts.history)} ` +
1818
1865
  `summary=${JSON.stringify(spec.summary.slice(0, 60))}\n`
1819
- : `[reika:debug] round=${i} spec-pin none\n`);
1866
+ : refused?.role === 'tool'
1867
+ ? `[reika:debug] round=${i} spec-pin none reason=oversize ` +
1868
+ `chars=${refused.payload?.length ?? 0} ` +
1869
+ `summary=${JSON.stringify(refused.summary.slice(0, 60))}\n`
1870
+ : `[reika:debug] round=${i} spec-pin none\n`);
1820
1871
  // Dropped-payload ledger (#227). Read off the COMPOSED request — the notice reaches the model
1821
1872
  // through the system block or the trailing note depending on mode and REIKA_PREFIX_STABLE,
1822
1873
  // and this block runs after both are final — so `active` is what actually shipped, not a
@@ -1860,6 +1911,17 @@ export async function runTurn(opts) {
1860
1911
  // REIKA_COMPACTION_REPORT=0 is the ledger-only baseline arm; /compact honors it too, and then
1861
1912
  // folds without a note exactly as an automatic fold would.
1862
1913
  const reportEnabled = compactionReportEnabled();
1914
+ // The note is written from the unfolded history, which a resumed session (folds are not
1915
+ // restored) or a /model switch to a smaller window can leave over the window: the engine
1916
+ // refuses the request and its retries, or one that truncates spends a whole window of prefill
1917
+ // on the backstop's 256 tokens. Last in the gate, so only a fold that is really due logs it.
1918
+ const noteFitsWindow = (contextWindow) => {
1919
+ const promptTokens = Math.round(rawEstimate() * compactCalibration);
1920
+ if (promptTokens < contextWindow)
1921
+ return true;
1922
+ debugLog(`[reika:debug] round=${i} compaction-report skipped prompt=${promptTokens} window=${contextWindow}\n`);
1923
+ return false;
1924
+ };
1863
1925
  const autoReport = !manualRound &&
1864
1926
  reportEnabled &&
1865
1927
  !!window &&
@@ -1876,7 +1938,8 @@ export async function runTurn(opts) {
1876
1938
  ? foldAfterShed(opts.history, h => rawEstimate(h) * compactCalibration, window, compactCalibration, minGen(), !latchesFor(opts.config).reasoningRoundtrip,
1877
1939
  // The manual trigger's only question is "would the fold remove anything" (#481).
1878
1940
  !manualRound)
1879
- : wouldFold(opts.history, window, compactCalibration, minGen()))) {
1941
+ : wouldFold(opts.history, window, compactCalibration, minGen())) &&
1942
+ noteFitsWindow(window)) {
1880
1943
  const n = shrink.folds + 1;
1881
1944
  const directive = buildCompactionReportDirective(n);
1882
1945
  // Notice first, so the barred note block that follows reads as a deliberate side
@@ -1917,69 +1980,75 @@ export async function runTurn(opts) {
1917
1980
  ? compactionNotePrefill(n)
1918
1981
  : undefined;
1919
1982
  try {
1920
- const send = (suffix, appended, assistantPrefill) => callModel({
1921
- system: prefixStable ? baseSystem : directiveAsTail ? system : system + '\n\n' + suffix,
1922
- history: appended.length ? [...opts.history, ...appended] : opts.history,
1923
- // The same tools the round would send, with calls forbidden by `tool_choice` (#426).
1924
- // Sending none rendered a different system turn: on the measured 24k runs the note
1925
- // round re-prefilled the entire request (~7–11k tokens) immediately before the fold
1926
- // re-prefilled it again — two full prefills per fold, one of them for nothing.
1927
- tools: noteTools,
1928
- toolChoice: 'none',
1929
- assistantPrefill,
1930
- config: withGenReserve(opts.config, genReserve),
1931
- // Streamed through the reading the finished reply gets, or the thinking and call
1932
- // after the note draw and then vanish (#819).
1933
- onContentDelta: assistantPrefill && opts.onContentDelta
1934
- ? prefilledNoteStream(assistantPrefill, opts.onContentDelta)
1935
- : opts.onContentDelta,
1936
- onReasoningDelta: opts.onReasoningDelta,
1937
- signal: opts.signal,
1938
- calibration,
1939
- maxTokens: computeMaxTokens({
1940
- contextWindow: window,
1941
- promptTokens: Math.round(rawEstimate() * calibration),
1942
- userMaxTokens: opts.config.maxTokens,
1943
- modelMaxOutput: opts.config.maxOutputTokens,
1944
- }),
1945
- prefixStable,
1946
- // Do not freeze this round's fresh payloads at the note request's render. Pre-shed the
1947
- // fit-to-window cap has the least room it will have all event, so the bytes stamped
1948
- // here would be the most truncated ones — and the real request after the fold would
1949
- // reuse them. Left unstamped, the real request renders them with the post-fold room
1950
- // and stamps those. Free for the cache: the fold (or the shed, if no fold) already
1951
- // diverges the real request before the fresh block, so the differing bytes cost nothing
1952
- // they were not paying.
1953
- stampRenders: false,
1954
- // The note round reads the same history as any other round, so it sees the same image:
1955
- // withholding it would have the model write a handoff about a screenshot it can't see.
1956
- nativeImages: opts.nativeImages,
1957
- trailingNote: prefixStable
1958
- ? roundSuffix
1959
- ? `${roundSuffix}\n\n${suffix}`
1960
- : suffix
1961
- : directiveAsTail
1962
- ? suffix
1983
+ const send = (suffix, appended, assistantPrefill) => {
1984
+ const live = startLiveRound(() => rawEstimate(opts.history, noteTools));
1985
+ return callModel({
1986
+ system: prefixStable ? baseSystem : directiveAsTail ? system : system + '\n\n' + suffix,
1987
+ history: appended.length ? [...opts.history, ...appended] : opts.history,
1988
+ // The same tools the round would send, with calls forbidden by `tool_choice` (#426).
1989
+ // Sending none rendered a different system turn: on the measured 24k runs the note
1990
+ // round re-prefilled the entire request (~7–11k tokens) immediately before the fold
1991
+ // re-prefilled it again — two full prefills per fold, one of them for nothing.
1992
+ tools: noteTools,
1993
+ toolChoice: 'none',
1994
+ assistantPrefill,
1995
+ config: withGenReserve(opts.config, genReserve),
1996
+ // Streamed through the reading the finished reply gets, or the thinking and call
1997
+ // after the note draw and then vanish (#819).
1998
+ onContentDelta: assistantPrefill && opts.onContentDelta
1999
+ ? prefilledNoteStream(assistantPrefill, opts.onContentDelta)
2000
+ : opts.onContentDelta,
2001
+ onReasoningDelta: opts.onReasoningDelta,
2002
+ onOutputDelta: live && (text => live.add(text)),
2003
+ onEngineTimings: live && ((timings, prompt) => live.engine(timings, prompt)),
2004
+ onPromptProgress: opts.onPromptProgress,
2005
+ signal: opts.signal,
2006
+ calibration,
2007
+ maxTokens: computeMaxTokens({
2008
+ contextWindow: window,
2009
+ promptTokens: Math.round(rawEstimate() * calibration),
2010
+ userMaxTokens: opts.config.maxTokens,
2011
+ modelMaxOutput: opts.config.maxOutputTokens,
2012
+ }),
2013
+ prefixStable,
2014
+ // Do not freeze this round's fresh payloads at the note request's render. Pre-shed the
2015
+ // fit-to-window cap has the least room it will have all event, so the bytes stamped
2016
+ // here would be the most truncated ones — and the real request after the fold would
2017
+ // reuse them. Left unstamped, the real request renders them with the post-fold room
2018
+ // and stamps those. Free for the cache: the fold (or the shed, if no fold) already
2019
+ // diverges the real request before the fresh block, so the differing bytes cost nothing
2020
+ // they were not paying.
2021
+ stampRenders: false,
2022
+ // The note round reads the same history as any other round, so it sees the same image:
2023
+ // withholding it would have the model write a handoff about a screenshot it can't see.
2024
+ nativeImages: opts.nativeImages,
2025
+ trailingNote: prefixStable
2026
+ ? roundSuffix
2027
+ ? `${roundSuffix}\n\n${suffix}`
2028
+ : suffix
2029
+ : directiveAsTail
2030
+ ? suffix
2031
+ : undefined,
2032
+ // The note round is a request like any other, so it gets its own prefix-cache line:
2033
+ // before #426 it was the one request the trace never saw, and the fold's line that
2034
+ // followed compared against the round before it.
2035
+ onRequest: debugEnabled()
2036
+ ? msgs => {
2037
+ const d = prefixTrace.record(msgs, {
2038
+ trailingNote: directiveAsTail,
2039
+ tools: toolsToChatTools(noteTools),
2040
+ });
2041
+ const pct = d.totalChars > 0 ? Math.round((d.stableChars / d.totalChars) * 100) : 100;
2042
+ const tok = reprocessedTokens(d, Math.round(rawEstimate(opts.history, noteTools) * calibration));
2043
+ debugLog(`[reika:debug] prefix-cache round=${i} phase=report cause=${d.cause} ` +
2044
+ `stable=${d.stableChars}/${d.totalChars}c (${pct}%) ` +
2045
+ `msgs=${d.stableMessages}/${d.totalMessages}` +
2046
+ (d.changedRole ? ` firstChanged=${d.changedRole}` : '') +
2047
+ ` ${formatPrefillCost(tok, prefillRate.get(), false)}\n`);
2048
+ }
1963
2049
  : undefined,
1964
- // The note round is a request like any other, so it gets its own prefix-cache line:
1965
- // before #426 it was the one request the trace never saw, and the fold's line that
1966
- // followed compared against the round before it.
1967
- onRequest: debugEnabled()
1968
- ? msgs => {
1969
- const d = prefixTrace.record(msgs, {
1970
- trailingNote: directiveAsTail,
1971
- tools: toolsToChatTools(noteTools),
1972
- });
1973
- const pct = d.totalChars > 0 ? Math.round((d.stableChars / d.totalChars) * 100) : 100;
1974
- const tok = reprocessedTokens(d, Math.round(rawEstimate(opts.history, noteTools) * calibration));
1975
- debugLog(`[reika:debug] prefix-cache round=${i} phase=report cause=${d.cause} ` +
1976
- `stable=${d.stableChars}/${d.totalChars}c (${pct}%) ` +
1977
- `msgs=${d.stableMessages}/${d.totalMessages}` +
1978
- (d.changedRole ? ` firstChanged=${d.changedRole}` : '') +
1979
- ` ${formatPrefillCost(tok, prefillRate.get(), false)}\n`);
1980
- }
1981
- : undefined,
1982
- });
2050
+ });
2051
+ };
1983
2052
  // A failed prefilled request is asked again the plain way, and the prefill is latched off for
1984
2053
  // the endpoint only if that one succeeds: a 400 the plain request shares (an over-long
1985
2054
  // prompt) is not the prefill's, and latching on it would cost every later fold its note.
@@ -1998,9 +2067,9 @@ export async function runTurn(opts) {
1998
2067
  return plain;
1999
2068
  }
2000
2069
  };
2070
+ const notePrompt = () => rawEstimate(opts.history, noteTools);
2001
2071
  const rep = await report(directive);
2002
- if (rep.usage)
2003
- opts.onUsage?.(rep.usage);
2072
+ reportUsage(rep, !!opts.signal?.aborted, notePrompt);
2004
2073
  // callModel returns what streamed before a ctrl-c rather than throwing, so an aborted note
2005
2074
  // is a cut-off fragment — never a note, and not a reason to fold.
2006
2075
  if (opts.signal?.aborted) {
@@ -2016,9 +2085,17 @@ export async function runTurn(opts) {
2016
2085
  if (!compactionNoteContent(rep) && !opts.signal?.aborted) {
2017
2086
  debugLog(`[reika:debug] round=${i} compaction-report n=${n} no-note ${describe(rep)}; retrying\n`);
2018
2087
  opts.onReasoningReset?.();
2088
+ // The reset freezes the failed attempt in place, so without a line it reads as a first
2089
+ // note that went wrong rather than one the harness set aside.
2090
+ opts.onMessage({
2091
+ role: 'system',
2092
+ tone: 'info',
2093
+ content: rep.toolCalls?.length
2094
+ ? 'The model made a tool call instead of writing the note — asking again.'
2095
+ : 'That reply carried no note — asking again.',
2096
+ });
2019
2097
  retry = await report(`${directive}\n\n${COMPACTION_REPORT_RETRY}`, refusedCallTurn(rep));
2020
- if (retry.usage)
2021
- opts.onUsage?.(retry.usage);
2098
+ reportUsage(retry, !!opts.signal?.aborted, notePrompt);
2022
2099
  if (opts.signal?.aborted) {
2023
2100
  commitNoteRoundAbort();
2024
2101
  return;
@@ -2050,10 +2127,11 @@ export async function runTurn(opts) {
2050
2127
  debugLog(`[reika:debug] round=${i} compaction-report failed err=${String(err)}\n`);
2051
2128
  }
2052
2129
  finally {
2053
- opts.onCompactionNote?.(false);
2054
2130
  // The live region held the note; if the reply was empty no assistant commit cleared it,
2055
- // so the UI is told explicitly before the round's real reply streams.
2131
+ // so the UI is told explicitly before the round's real reply streams. Ahead of the note
2132
+ // flag, so the UI still knows the stream it is ending was a note's.
2056
2133
  opts.onReasoningReset?.();
2134
+ opts.onCompactionNote?.(false);
2057
2135
  }
2058
2136
  }
2059
2137
  // Prefix-stable shrink event: payloads stay live (byte-frozen) across rounds, so shed them in
@@ -2155,6 +2233,16 @@ export async function runTurn(opts) {
2155
2233
  opts.onContextEstimate?.(Math.round(rawEstimate() * calibration));
2156
2234
  return;
2157
2235
  }
2236
+ // The suffix was composed before the shed above, so without this the request that first shows
2237
+ // a payload as summary-only is the one request whose note cannot say so.
2238
+ if (agedThisRound && !roundSuffix?.includes(DROPPED_LEDGER_MARKER)) {
2239
+ const dropped = droppedPayloadLedgerFor(opts.history, prefixStable);
2240
+ if (dropped) {
2241
+ roundSuffix = roundSuffix ? `${dropped}\n\n${roundSuffix}` : dropped;
2242
+ debugLog(`[reika:debug] round=${i} dropped-ledger active=true ` +
2243
+ `payloads=${droppedPayloadCount(opts.history, prefixStable)} via=tail after-shed=true\n`);
2244
+ }
2245
+ }
2158
2246
  const sentTools = subagentForceReport && lastSentTools ? lastSentTools : callTools;
2159
2247
  lastSentTools = sentTools;
2160
2248
  const sentEstimate = rawEstimate(callHistory, sentTools);
@@ -2229,6 +2317,7 @@ export async function runTurn(opts) {
2229
2317
  }
2230
2318
  }
2231
2319
  : opts.onReasoningDelta;
2320
+ const live = startLiveRound(() => sentEstimate);
2232
2321
  const response = await callModel({
2233
2322
  system,
2234
2323
  history: callHistory,
@@ -2236,6 +2325,9 @@ export async function runTurn(opts) {
2236
2325
  config: withGenReserve(opts.config, genReserve),
2237
2326
  onContentDelta: opts.onContentDelta,
2238
2327
  onReasoningDelta,
2328
+ onOutputDelta: live && (text => live.add(text)),
2329
+ onEngineTimings: live && ((timings, prompt) => live.engine(timings, prompt)),
2330
+ onPromptProgress: opts.onPromptProgress,
2239
2331
  signal: callAbort.signal,
2240
2332
  calibration,
2241
2333
  // Per-turn backstop: cap generation to the room actually left in the window so a
@@ -2319,8 +2411,7 @@ export async function runTurn(opts) {
2319
2411
  opts.onReasoningStatus?.(false);
2320
2412
  debugLog(`[reika:debug] reasoning-spin off round=${i} (block ended while flagged)\n`);
2321
2413
  }
2322
- if (response.usage)
2323
- opts.onUsage?.(response.usage);
2414
+ reportUsage(response, callAbort.signal.aborted, () => sentEstimate);
2324
2415
  // Recalibrate from what the provider actually counted vs. what we estimated for the
2325
2416
  // request we just sent. Clamped to a sane band to ignore one-off outliers.
2326
2417
  if (response.usage?.promptTokens && sentEstimate > 0) {
@@ -2840,6 +2931,28 @@ export async function runTurn(opts) {
2840
2931
  });
2841
2932
  }
2842
2933
  if (isFinal) {
2934
+ // A reply with no text and no call ends the turn with nothing on screen to say so, which reads
2935
+ // as an abort. Ask once; a second empty reply gets the notice, since a stop this turn cannot
2936
+ // recover from is still one the user has to see.
2937
+ if (!assistantContent?.trim() &&
2938
+ response.finishReason !== 'length' &&
2939
+ !opts.signal?.aborted) {
2940
+ const retry = emptyReplyRetries < MAX_EMPTY_REPLY_RETRIES;
2941
+ debugLog(`[reika:debug] round=${i} empty-reply retry=${retry}\n`);
2942
+ opts.onMessage({
2943
+ role: 'system',
2944
+ tone: 'warn',
2945
+ content: retry
2946
+ ? 'The model stopped without replying — asking it to continue.'
2947
+ : 'The model stopped again without replying. Send a prompt to continue.',
2948
+ });
2949
+ if (retry) {
2950
+ emptyReplyRetries++;
2951
+ // Same `harness` reasoning as the typecheck send-back below (#287).
2952
+ opts.history.push({ role: 'user', content: EMPTY_REPLY_NUDGE, harness: true });
2953
+ continue;
2954
+ }
2955
+ }
2843
2956
  // Post-edit typecheck gate. If this turn edited (baseline captured) and a final check shows
2844
2957
  // the edits introduced new type errors, send the model back to fix them instead of letting it
2845
2958
  // finish on broken code — the harness verifies so the weak model doesn't have to. The model's
@@ -3003,12 +3116,20 @@ export async function runTurn(opts) {
3003
3116
  // equipped to make. Now that shouldBounce asks the real question (are those bytes in the
3004
3117
  // request the model just answered — see readfirst.ts isLive), the proxy only loses coverage:
3005
3118
  // the long unplanned turn is exactly where reads age out beneath the model.
3006
- const bouncedBlindEdit = READ_FIRST &&
3119
+ const blindEdit = READ_FIRST &&
3007
3120
  !withdrawInspection &&
3008
3121
  call.name === 'edit' &&
3009
3122
  tool !== undefined &&
3010
3123
  typeof call.args.path === 'string' &&
3011
- readFirst.shouldBounce(call.args.path, opts.history, prefixStable);
3124
+ readFirst.wouldBounce(call.args.path, opts.history, prefixStable);
3125
+ const provenEdit = READ_FIRST_EXACT &&
3126
+ blindEdit &&
3127
+ (await oldStringProvesBytes(opts.bundle.cwd, String(call.args.path), String(call.args.old_string ?? ''), String(call.args.new_string ?? '')));
3128
+ if (provenEdit)
3129
+ debugLog(`[reika:debug] round=${i} read-first proven ${call.args.path}\n`);
3130
+ const bouncedBlindEdit = blindEdit &&
3131
+ !provenEdit &&
3132
+ readFirst.shouldBounce(String(call.args.path), opts.history, prefixStable);
3012
3133
  let summary;
3013
3134
  let payload;
3014
3135
  let diff;
@@ -3254,6 +3375,7 @@ export async function runTurn(opts) {
3254
3375
  if (summary.startsWith('Edited ') || summary.startsWith('Wrote ')) {
3255
3376
  lastEditFailed = false;
3256
3377
  lastEditFailure = undefined;
3378
+ editRecoveryGroundingTried = false;
3257
3379
  // Read-first (#72): a successful edit/write grounds its path, but by different routes. An
3258
3380
  // edit grounds only through the post-edit echo it hands back (tools/edit.ts refreshedFile),
3259
3381
  // which is size-capped and absent on a large file — so it keys on the message index and
@@ -3402,6 +3524,7 @@ export async function runTurn(opts) {
3402
3524
  role: 'assistant',
3403
3525
  content: `(reached max turns of ${opts.config.maxTurns}; ask me to continue or raise the turn limit)` +
3404
3526
  (await reportTypecheckAtStop()),
3527
+ harnessStop: 'max-turns',
3405
3528
  durationMs: Date.now() - turnStart,
3406
3529
  ...(fetchedUrls.size > 0 ? { sources: [...fetchedUrls] } : {}),
3407
3530
  };
@@ -3435,6 +3558,17 @@ function commitAborted(opts, partial, partialReasoning, turnStart, fetchedUrls)
3435
3558
  opts.history.push(m);
3436
3559
  opts.onMessage(m);
3437
3560
  }
3561
+ // The files a stop message names, as inline code and project-relative: an edit's `path` arg is
3562
+ // often absolute, and a bare `/Users/…/src/a.ts, …` list read as prose and wrapped mid-path.
3563
+ function stopFileList(files, cwd, max) {
3564
+ return [...files]
3565
+ .slice(0, max)
3566
+ .map(f => {
3567
+ const rel = isAbsolute(f) ? relative(cwd, f) : f;
3568
+ return `\`${rel && !rel.startsWith('..') && !isAbsolute(rel) ? rel : f}\``;
3569
+ })
3570
+ .join(', ');
3571
+ }
3438
3572
  // Honest terminal stop when reasoning keeps spiraling even through recovery (the force-write looped,
3439
3573
  // or the recovery budget is spent). Better than committing spiral garbage as a "plan" or running to
3440
3574
  // the token wall. Names the files examined so the user has a handle on what was done. Deliberately
@@ -3454,7 +3588,7 @@ reason = 'loop') {
3454
3588
  files.add(tc.args.path);
3455
3589
  }
3456
3590
  }
3457
- const examined = files.size > 0 ? ` Files I examined: ${[...files].slice(0, 12).join(', ')}.` : '';
3591
+ const examined = files.size > 0 ? ` Files I examined: ${stopFileList(files, opts.bundle.cwd, 12)}.` : '';
3458
3592
  const m = {
3459
3593
  role: 'assistant',
3460
3594
  content: reason === 'length'
@@ -3464,6 +3598,7 @@ reason = 'loop') {
3464
3598
  : `I couldn't converge — the reasoning kept looping and was stopped to avoid running ` +
3465
3599
  `indefinitely.${examined} This looks like a request the model is getting stuck on; try ` +
3466
3600
  `rephrasing or narrowing it, or use a stronger model.`,
3601
+ harnessStop: reason,
3467
3602
  durationMs: Date.now() - turnStart,
3468
3603
  ...(fetchedUrls.size > 0 ? { sources: [...fetchedUrls] } : {}),
3469
3604
  };
@@ -3494,7 +3629,7 @@ function commitAgentLoopStop(opts, turnStart, fetchedUrls, edited, typecheckAdde
3494
3629
  }
3495
3630
  }
3496
3631
  }
3497
- const fileList = files.size > 0 ? ` to ${[...files].slice(0, 8).join(', ')}` : '';
3632
+ const fileList = files.size > 0 ? ` to ${stopFileList(files, opts.bundle.cwd, 8)}` : '';
3498
3633
  const content = edited
3499
3634
  ? `I made changes${fileList} but then kept repeating the same checks without making progress, so ` +
3500
3635
  `I've stopped to avoid looping. The edits are saved — review them and ask me to continue if ` +
@@ -3505,6 +3640,7 @@ function commitAgentLoopStop(opts, turnStart, fetchedUrls, edited, typecheckAdde
3505
3640
  const m = {
3506
3641
  role: 'assistant',
3507
3642
  content,
3643
+ harnessStop: 'loop',
3508
3644
  durationMs: Date.now() - turnStart,
3509
3645
  ...(fetchedUrls.size > 0 ? { sources: [...fetchedUrls] } : {}),
3510
3646
  };
@@ -3567,6 +3703,7 @@ function makeSpawnSubagent(parent, budget, parentDecodeRate, parentGenReserve) {
3567
3703
  requestApproval: parent.requestApproval,
3568
3704
  isUnattended: parent.isUnattended,
3569
3705
  onUsage: parent.onUsage,
3706
+ onLiveUsage: parent.onLiveUsage,
3570
3707
  priorDecodeRate: sameEngine ? parentDecodeRate.get() : undefined,
3571
3708
  genReserve: sameEngine ? parentGenReserve : undefined,
3572
3709
  onDecodeRate: rate => {
@@ -3583,6 +3720,7 @@ function makeSpawnSubagent(parent, budget, parentDecodeRate, parentGenReserve) {
3583
3720
  // them nested via onSubagent.
3584
3721
  onContentDelta: parent.onContentDelta,
3585
3722
  onReasoningDelta: parent.onReasoningDelta,
3723
+ onPromptProgress: parent.onPromptProgress,
3586
3724
  onToolProgress: parent.onToolProgress,
3587
3725
  // `onToolStart` is the one callback deliberately NOT forwarded (#509). The parent's live row
3588
3726
  // is a single slot keyed to its own round: forwarding a nested start would overwrite the
@@ -89,6 +89,14 @@ export class ReadFirstGate {
89
89
  // True exactly once per ungrounded path per turn — and recording the bounce here (a side effect)
90
90
  // is what guarantees the once: every later call for the path, grounded or not, passes.
91
91
  shouldBounce(path, history, prefixStable = false) {
92
+ if (!this.wouldBounce(path, history, prefixStable))
93
+ return false;
94
+ this.bounced.add(this.norm(path));
95
+ return true;
96
+ }
97
+ // shouldBounce's question without spending the bounce (#932): an edit that proves its bytes must
98
+ // leave the path's one bounce for a later edit that does not.
99
+ wouldBounce(path, history, prefixStable = false) {
92
100
  // Never bounce a path outside the project (#216). The bounce is a directive to `read` the file,
93
101
  // and `read` applies no boundary of its own — so bouncing here is the harness walking the model
94
102
  // around the gate `write`/`edit` just applied to that same path (#175, tools/_paths.ts). This
@@ -100,17 +108,11 @@ export class ReadFirstGate {
100
108
  // resolve() would read it as a literal `~` directory inside cwd — in-project, and unbounced for
101
109
  // the wrong reason. A test pins that distinction.
102
110
  //
103
- // Returning before the `bounced` bookkeeping is tidiness, not policy: nothing reads that set
104
- // for a path this branch rejects, so recording it would be equally correct.
105
111
  if (escapesProject(this.cwd, resolveUserPath(this.cwd, path)))
106
112
  return false;
107
- const p = this.norm(path);
108
- if (this.bounced.has(p))
113
+ if (this.bounced.has(this.norm(path)))
109
114
  return false;
110
- if (this.isGrounded(path, history, prefixStable))
111
- return false;
112
- this.bounced.add(p);
113
- return true;
115
+ return !this.isGrounded(path, history, prefixStable);
114
116
  }
115
117
  }
116
118
  // Longest line of a gutter-numbered excerpt, stripped of its `NNNNN│` prefix — the needle for asking
@@ -179,6 +181,26 @@ export async function probeWouldLand(cwd, path, oldStr, newStr) {
179
181
  const lands = kind === 'exact' || kind === 'fuzzy';
180
182
  return `would-land=${lands ? 'yes' : 'no'} match=${kind}`;
181
183
  }
184
+ // Below this an exact match proves little: `return null;` can be unique in a small file. Trimmed,
185
+ // because indentation is not evidence. Over 157 saved bounces, 24 kept 100 of the 101 that were
186
+ // re-issued unchanged and landed.
187
+ const MIN_PROVEN_OLD_STRING_CHARS = 24;
188
+ // An old_string that matches the file exactly and uniquely is not a guess, however the model got
189
+ // the bytes (grep context, a pipeline, a subagent report), so bouncing it only costs a round (#932).
190
+ // Exact only: a fuzzy match is the model's approximation of the bytes. Unreadable reads as unproven,
191
+ // which keeps today's bounce. The caller must have ruled out a path outside the project, since this
192
+ // reads the file before any approval (see shouldBounce).
193
+ export async function oldStringProvesBytes(cwd, path, oldStr, newStr) {
194
+ if (oldStr === newStr || oldStr.trim().length < MIN_PROVEN_OLD_STRING_CHARS)
195
+ return false;
196
+ try {
197
+ const text = await readFile(resolveUserPath(cwd, path), 'utf8');
198
+ return classifyEditMatch(text, oldStr, newStr) === 'exact';
199
+ }
200
+ catch {
201
+ return false;
202
+ }
203
+ }
182
204
  export function buildReadFirstDirective(path) {
183
205
  return (`(reika: this edit was NOT applied. The current contents of ${path} are not in your context — ` +
184
206
  'either you have not read it, or the read has since aged out — so your old_string is a guess ' +