@alexwkleung/reika 0.9.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.
- package/dist/agent/compaction.js +9 -4
- package/dist/agent/liveusage.js +58 -0
- package/dist/agent/loop.js +155 -73
- package/dist/agent/readfirst.js +30 -8
- package/dist/cli.js +3 -3
- package/dist/headless/headless.js +65 -6
- package/dist/headless/headlessargs.js +1 -1
- package/dist/headless/headlessprompt.js +2 -1
- package/dist/provider/client.js +65 -5
- package/dist/provider/latches.js +2 -0
- package/dist/provider/toolcall.js +29 -7
- package/dist/search/_chrome.js +38 -0
- package/dist/tools/_readonly.js +17 -1
- package/dist/tools/_sandbox.js +139 -20
- package/dist/ui/App.js +73 -34
- package/dist/ui/Approval.js +1 -6
- package/dist/ui/Scrollback.js +11 -3
- package/dist/ui/Working.js +18 -7
- package/dist/ui/format.js +23 -0
- package/dist/ui/layout.js +6 -0
- package/dist/ui/markdown.js +30 -2
- package/dist/ui/termtext.js +11 -0
- package/dist/ui/theme.js +5 -1
- package/package.json +1 -1
package/dist/agent/compaction.js
CHANGED
|
@@ -130,7 +130,7 @@ export function compactHistory(history, contextWindow, calibration = 1, minGen =
|
|
|
130
130
|
// lead a request, its assistant parent may have issued sibling calls whose responses are being
|
|
131
131
|
// folded, and an unmatched tool_call is an API error. Text has none of those failure modes.
|
|
132
132
|
//
|
|
133
|
-
// No extra bound needed — every candidate is capped
|
|
133
|
+
// No extra bound needed — every candidate is capped by taskSpecIndex, so this is a few KB at
|
|
134
134
|
// most. Note the elected spec stops being findable by taskSpecIndex afterwards (that looks for a
|
|
135
135
|
// `tool` message), so `spec-pin none` after a compaction is expected, not a regression: the
|
|
136
136
|
// content is in the recap, and the next turn's opening call becomes the new pin.
|
|
@@ -140,8 +140,13 @@ export function compactHistory(history, contextWindow, calibration = 1, minGen =
|
|
|
140
140
|
// whatever small tool result had arrived since (a 13-line file read, then a grep of AGENTS.md)
|
|
141
141
|
// under a header asserting it is the task. The first fold is also the only one whose ballot still
|
|
142
142
|
// held the real spec, so its answer is the one to keep.
|
|
143
|
+
//
|
|
144
|
+
// Only a recap written since the newest user message is this turn's. One from before it holds an
|
|
145
|
+
// earlier task, and carrying it would present that task as this one under the header above.
|
|
143
146
|
const span = history.slice(recapStart, keepFrom);
|
|
144
|
-
const
|
|
147
|
+
const turnStart = Math.max(recapStart, lastUserMessageIndex(history) + 1);
|
|
148
|
+
const preserved = carriedSpecBlock(history.slice(turnStart, keepFrom)) ??
|
|
149
|
+
electSpecBlock(history, recapStart, keepFrom);
|
|
145
150
|
const recap = buildRecap(span, avail, calib, note);
|
|
146
151
|
history.splice(recapStart, keepFrom - recapStart, {
|
|
147
152
|
role: 'compaction',
|
|
@@ -350,7 +355,7 @@ function protectedTailStart(history) {
|
|
|
350
355
|
}
|
|
351
356
|
// Approximate the characters a message contributes to a request (at rest: tool payloads
|
|
352
357
|
// are already summarized by aging, so only the summary counts). The one message this under-prices
|
|
353
|
-
// is the pinned task spec (#227), which still carries its payload; bounded by
|
|
358
|
+
// is the pinned task spec (#227), which still carries its payload; bounded by taskSpecIndex,
|
|
354
359
|
// so the keep-budget walk stays close enough.
|
|
355
360
|
function msgChars(m) {
|
|
356
361
|
switch (m.role) {
|
|
@@ -404,7 +409,7 @@ function stripOmissionNote(content) {
|
|
|
404
409
|
}
|
|
405
410
|
// The preserved task definition that leads a recap (#251), and the closing line that bounds it so a
|
|
406
411
|
// later fold can find the whole block and carry it forward instead of electing a second one (#275).
|
|
407
|
-
// One block per recap, always at the front, always
|
|
412
|
+
// One block per recap, always at the front, always within taskSpecIndex's cap.
|
|
408
413
|
const SPEC_BLOCK_END = '(End of the preserved task definition; the recap of earlier work follows.)';
|
|
409
414
|
// The three things the block can hold, most trustworthy first. Only the first two make the strong
|
|
410
415
|
// claim, and both have earned it: a skill mandates its opening call (`/issue`, `/review` both fetch
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { estimateTokens } from '../provider/tokens.js';
|
|
2
|
+
import { derivedDecodeRate, engineDecodeRate } from './decoderate.js';
|
|
3
|
+
// Estimates from stream text rather than stream events, since a hosted API may batch tokens into
|
|
4
|
+
// one event. The first engine report ends the estimating for the round: the two disagree, so
|
|
5
|
+
// alternating between them would make the chips jump.
|
|
6
|
+
export class LiveRound {
|
|
7
|
+
promptTokens;
|
|
8
|
+
density;
|
|
9
|
+
report;
|
|
10
|
+
now;
|
|
11
|
+
output = '';
|
|
12
|
+
firstOutputAt;
|
|
13
|
+
engineReported = false;
|
|
14
|
+
constructor(promptTokens, density, report, now = Date.now) {
|
|
15
|
+
this.promptTokens = promptTokens;
|
|
16
|
+
this.density = density;
|
|
17
|
+
this.report = report;
|
|
18
|
+
this.now = now;
|
|
19
|
+
report({ promptTokens, completionTokens: 0 });
|
|
20
|
+
}
|
|
21
|
+
add(text) {
|
|
22
|
+
if (this.engineReported)
|
|
23
|
+
return;
|
|
24
|
+
this.output += text;
|
|
25
|
+
const at = this.now();
|
|
26
|
+
this.firstOutputAt ??= at;
|
|
27
|
+
const completionTokens = Math.round(estimateTokens(this.output) * this.density);
|
|
28
|
+
// The chip's own sample bounds apply, so a first burst can't print a wild rate.
|
|
29
|
+
const rate = derivedDecodeRate({ promptTokens: 0, completionTokens }, { ttftMs: 0, totalMs: at - this.firstOutputAt });
|
|
30
|
+
this.report({
|
|
31
|
+
promptTokens: this.promptTokens,
|
|
32
|
+
completionTokens,
|
|
33
|
+
...(rate != null ? { rate } : {}),
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
engine(timings, prompt) {
|
|
37
|
+
this.engineReported = true;
|
|
38
|
+
// Both halves or neither: `prompt_n` alone is only what the cache could not serve.
|
|
39
|
+
const promptReported = prompt?.promptN != null && prompt.cacheN != null;
|
|
40
|
+
const rate = engineDecodeRate(timings);
|
|
41
|
+
this.report({
|
|
42
|
+
promptTokens: promptReported ? prompt.promptN + prompt.cacheN : this.promptTokens,
|
|
43
|
+
completionTokens: timings.predictedN,
|
|
44
|
+
...(rate != null ? { rate } : {}),
|
|
45
|
+
...(promptReported ? { exact: true } : {}),
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
export function withLiveUsage(total, live) {
|
|
50
|
+
if (!live)
|
|
51
|
+
return total;
|
|
52
|
+
return {
|
|
53
|
+
...total,
|
|
54
|
+
promptTokens: total.promptTokens + live.promptTokens,
|
|
55
|
+
completionTokens: total.completionTokens + live.completionTokens,
|
|
56
|
+
...(live.exact ? {} : { estimated: true }),
|
|
57
|
+
};
|
|
58
|
+
}
|
package/dist/agent/loop.js
CHANGED
|
@@ -7,12 +7,13 @@ import { isLocalEngine } from '../provider/templatekwargs.js';
|
|
|
7
7
|
import { estimateRequestTokens, estimateTokens } from '../provider/tokens.js';
|
|
8
8
|
import { computeMaxTokens, NATIVE_IMAGE_TOKEN_ALLOWANCE, shouldRetryTruncated, } from '../provider/budget.js';
|
|
9
9
|
import { compactHistory, shouldCompact, compactThreshold, gatherPlanFindings, distillPlanHandoff, batchAgePayloads, AGE_LOW_FRACTION, } from './compaction.js';
|
|
10
|
-
import { droppedPayloadCount, findFreshToolBlockStart, hasDroppedPayloads, lastUserMessageIndex, taskSpecIndex, toolsToChatTools, } from '../provider/toolcall.js';
|
|
10
|
+
import { droppedPayloadCount, findFreshToolBlockStart, hasDroppedPayloads, lastUserMessageIndex, oversizeOpeningPayloadIndex, taskSpecIndex, toolsToChatTools, } from '../provider/toolcall.js';
|
|
11
11
|
import { ReadTrace } from './readtrace.js';
|
|
12
12
|
import { traceBashRead, traceReadPath } from './bashread.js';
|
|
13
13
|
import { PrefixTrace } from './prefixtrace.js';
|
|
14
14
|
import { PrefillRate, formatMeasuredPrefill, formatPrefillCost, reprocessedTokens, sampleTokens, } from './prefillcost.js';
|
|
15
15
|
import { DecodeRate, decodeSample, formatRate } from './decoderate.js';
|
|
16
|
+
import { LiveRound } from './liveusage.js';
|
|
16
17
|
import { GenReserve, resolveGenReserve, withGenReserve } from './genreserve.js';
|
|
17
18
|
import { selfRepeatRatio, repeatedSelfShingles, ReasoningTrace, liveSpinSignal, verbatimAbortThreshold, } from './reasoningtrace.js';
|
|
18
19
|
import { ContinuationGate, continuationGate, continuationTail } from './continuation.js';
|
|
@@ -29,7 +30,7 @@ import { writeTargets } from '../tools/_writetargets.js';
|
|
|
29
30
|
import { READ_DEFAULT_LIMIT } from '../tools/read.js';
|
|
30
31
|
import { recordFollowed, spillStatsEnabled } from '../tools/_spillstats.js';
|
|
31
32
|
import { seedPlanProgress, parsePlanSteps, planChanged, refineTarget, applyEdit as applyPlanEdit, applyCommand as applyPlanCommand, buildPlanProgressLedger, decidePlanGate, waiveUnchecked, ranSuccessfully, MAX_PLAN_GATE_ROUNDS, } from './plantrack.js';
|
|
32
|
-
import { ReadFirstGate, buildReadFirstDirective, probeWouldLand } from './readfirst.js';
|
|
33
|
+
import { ReadFirstGate, buildReadFirstDirective, oldStringProvesBytes, probeWouldLand, } from './readfirst.js';
|
|
33
34
|
import { SUBAGENT_REPORT_DIRECTIVE, SUBAGENT_REPORT_FRAME, SUBAGENT_HOLD_NOTE, MAX_SUBAGENTS_PER_TURN, MAX_SUBAGENTS_PER_ROUND, buildCoverageNote, } from './subagentreport.js';
|
|
34
35
|
import { COMPACTION_REPORT_RETRY, compactionNotePrefill, notePrefillEnabled, prefilledNoteStream, prefilledReply, refusedCallTurn, buildCompactionReportDirective, clampCompactionNote, compactionNoteContent, compactionReportEnabled, pickCompactionNote, } from './compactionreport.js';
|
|
35
36
|
import { buildSubagentAffordance, filesInResult, subagentPressureEnabled, underPressure, } from './subagentpressure.js';
|
|
@@ -379,6 +380,9 @@ const DROPPED_LEDGER = process.env.REIKA_DROPPED_LEDGER !== '0';
|
|
|
379
380
|
// runs as-is), suspended while inspection tools are withdrawn (the directed read would be refused).
|
|
380
381
|
// The `would-land=` field on the bounce debug line is the measurement. See agent/readfirst.ts.
|
|
381
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';
|
|
382
386
|
// EXPERIMENT (#867): keep the offered tool list unchanged while inspection is withdrawn, enforcing
|
|
383
387
|
// the pause at dispatch and through the ledger only. The template renders the tools ahead of the
|
|
384
388
|
// system prompt, so dropping them makes the withdrawal round and the lift round each a full
|
|
@@ -733,6 +737,8 @@ const LOOP_TERMINAL_AFTER = 3;
|
|
|
733
737
|
// gives one fix attempt plus a re-check; beyond that, finishing dirty (with a user notice) beats
|
|
734
738
|
// spiralling. See check/typecheck.ts.
|
|
735
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.)';
|
|
736
742
|
// Floor on the learned calibration when it drives the COMPACTION decision (not the UI gauge). The
|
|
737
743
|
// calibration = real-tokens / char-4-estimate; a prose-heavy session drives it below 1 (~0.9), which
|
|
738
744
|
// makes the trigger assume content is even sparser than the char/4 baseline. That optimism is what let
|
|
@@ -807,12 +813,12 @@ function withdrawnLedgerLines(toolNames) {
|
|
|
807
813
|
// Returned in place of a withdrawn inspection call. No content, so it can't re-fuel the loop or
|
|
808
814
|
// inflate context; it just states the rule and the way out. Built per turn rather than held as a
|
|
809
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.
|
|
810
817
|
export function buildWithdrawalDirective(toolNames) {
|
|
811
|
-
return (`(reika: ${withdrawnToolsPhrase(toolNames)} are paused
|
|
812
|
-
'
|
|
813
|
-
|
|
814
|
-
'is already complete — say so and stop.
|
|
815
|
-
'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.)');
|
|
816
822
|
}
|
|
817
823
|
// Whether to escalate from the loop ledger to withdrawing the inspection tools. Fires once a loop has
|
|
818
824
|
// stayed active LOOP_WITHDRAW_AFTER rounds (the ledger got its shot first), with exactly one
|
|
@@ -845,7 +851,7 @@ export function shouldWithdrawInspection(opts) {
|
|
|
845
851
|
// without inspection, then the cycle again, each switch of the tool list a full re-prefill (~22 in
|
|
846
852
|
// one 163-round run). Held until the tree changes instead, capped so a model that has declared
|
|
847
853
|
// itself stuck gets reads back.
|
|
848
|
-
export const WITHDRAW_HOLD_ROUNDS =
|
|
854
|
+
export const WITHDRAW_HOLD_ROUNDS = 4;
|
|
849
855
|
// Whether a withdrawal already in force stays on this round although the loop no longer reads as
|
|
850
856
|
// active. `since` is the round it began; `mutated` is whether the tree has changed since then.
|
|
851
857
|
export function holdWithdrawal(opts) {
|
|
@@ -1232,6 +1238,7 @@ export async function runTurn(opts) {
|
|
|
1232
1238
|
let typecheckTsconfig;
|
|
1233
1239
|
// Consecutive done-gate send-backs this turn. Bounds the fix loop at MAX_TYPECHECK_GATE_ROUNDS.
|
|
1234
1240
|
let typecheckGateRounds = 0;
|
|
1241
|
+
let emptyReplyRetries = 0;
|
|
1235
1242
|
// Consecutive plan done-gate send-backs this turn. Bounds the plan gate at MAX_PLAN_GATE_ROUNDS.
|
|
1236
1243
|
let planGateRounds = 0;
|
|
1237
1244
|
// Per-turn memory of read-only calls already made, keyed by tool + result summary, so the
|
|
@@ -1319,6 +1326,7 @@ export async function runTurn(opts) {
|
|
|
1319
1326
|
// no decode happened. Goes to onUsage only, never onto the response: calibration, the decode rate
|
|
1320
1327
|
// and the reserve read `response.usage`, and a learned value must not be fitted to our own guess.
|
|
1321
1328
|
const reportUsage = (response, cut, promptEstimate) => {
|
|
1329
|
+
opts.onLiveUsage?.(undefined);
|
|
1322
1330
|
if (response.usage) {
|
|
1323
1331
|
opts.onUsage?.(response.usage);
|
|
1324
1332
|
return;
|
|
@@ -1332,6 +1340,10 @@ export async function runTurn(opts) {
|
|
|
1332
1340
|
estimated: true,
|
|
1333
1341
|
});
|
|
1334
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;
|
|
1335
1347
|
// Run a typecheck while pulsing the UI indicator around it (and clearing on any exit). The
|
|
1336
1348
|
// pulse is human-only; the CheckOutcome flows to the gate logic, never to the model.
|
|
1337
1349
|
const typecheck = async () => {
|
|
@@ -1652,6 +1664,7 @@ export async function runTurn(opts) {
|
|
|
1652
1664
|
const stuck = {
|
|
1653
1665
|
role: 'assistant',
|
|
1654
1666
|
content: buildEditRecoveryStopMessage(lastEditFailure) + (await reportTypecheckAtStop()),
|
|
1667
|
+
harnessStop: 'edit',
|
|
1655
1668
|
durationMs: Date.now() - turnStart,
|
|
1656
1669
|
...(fetchedUrls.size > 0 ? { sources: [...fetchedUrls] } : {}),
|
|
1657
1670
|
};
|
|
@@ -1844,12 +1857,17 @@ export async function runTurn(opts) {
|
|
|
1844
1857
|
// task conflation, so it is greppable rather than something to re-derive from the history.
|
|
1845
1858
|
const specIdx = taskSpecIndex(opts.history);
|
|
1846
1859
|
const spec = specIdx >= 0 ? opts.history[specIdx] : undefined;
|
|
1860
|
+
const refused = opts.history[oversizeOpeningPayloadIndex(opts.history)];
|
|
1847
1861
|
debugLog(specIdx >= 0 && spec?.role === 'tool'
|
|
1848
1862
|
? `[reika:debug] round=${i} spec-pin idx=${specIdx} chars=${spec.payload?.length ?? 0} ` +
|
|
1849
1863
|
`holding=${specIdx < findFreshToolBlockStart(opts.history)} ` +
|
|
1850
1864
|
`stale=${specIdx < lastUserMessageIndex(opts.history)} ` +
|
|
1851
1865
|
`summary=${JSON.stringify(spec.summary.slice(0, 60))}\n`
|
|
1852
|
-
:
|
|
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`);
|
|
1853
1871
|
// Dropped-payload ledger (#227). Read off the COMPOSED request — the notice reaches the model
|
|
1854
1872
|
// through the system block or the trailing note depending on mode and REIKA_PREFIX_STABLE,
|
|
1855
1873
|
// and this block runs after both are final — so `active` is what actually shipped, not a
|
|
@@ -1962,69 +1980,75 @@ export async function runTurn(opts) {
|
|
|
1962
1980
|
? compactionNotePrefill(n)
|
|
1963
1981
|
: undefined;
|
|
1964
1982
|
try {
|
|
1965
|
-
const send = (suffix, appended, assistantPrefill) =>
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
: opts.onContentDelta
|
|
1981
|
-
|
|
1982
|
-
|
|
1983
|
-
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
|
|
1987
|
-
|
|
1988
|
-
|
|
1989
|
-
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
|
|
1997
|
-
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
:
|
|
2007
|
-
|
|
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
|
+
}
|
|
2008
2049
|
: undefined,
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
// followed compared against the round before it.
|
|
2012
|
-
onRequest: debugEnabled()
|
|
2013
|
-
? msgs => {
|
|
2014
|
-
const d = prefixTrace.record(msgs, {
|
|
2015
|
-
trailingNote: directiveAsTail,
|
|
2016
|
-
tools: toolsToChatTools(noteTools),
|
|
2017
|
-
});
|
|
2018
|
-
const pct = d.totalChars > 0 ? Math.round((d.stableChars / d.totalChars) * 100) : 100;
|
|
2019
|
-
const tok = reprocessedTokens(d, Math.round(rawEstimate(opts.history, noteTools) * calibration));
|
|
2020
|
-
debugLog(`[reika:debug] prefix-cache round=${i} phase=report cause=${d.cause} ` +
|
|
2021
|
-
`stable=${d.stableChars}/${d.totalChars}c (${pct}%) ` +
|
|
2022
|
-
`msgs=${d.stableMessages}/${d.totalMessages}` +
|
|
2023
|
-
(d.changedRole ? ` firstChanged=${d.changedRole}` : '') +
|
|
2024
|
-
` ${formatPrefillCost(tok, prefillRate.get(), false)}\n`);
|
|
2025
|
-
}
|
|
2026
|
-
: undefined,
|
|
2027
|
-
});
|
|
2050
|
+
});
|
|
2051
|
+
};
|
|
2028
2052
|
// A failed prefilled request is asked again the plain way, and the prefill is latched off for
|
|
2029
2053
|
// the endpoint only if that one succeeds: a 400 the plain request shares (an over-long
|
|
2030
2054
|
// prompt) is not the prefill's, and latching on it would cost every later fold its note.
|
|
@@ -2061,6 +2085,15 @@ export async function runTurn(opts) {
|
|
|
2061
2085
|
if (!compactionNoteContent(rep) && !opts.signal?.aborted) {
|
|
2062
2086
|
debugLog(`[reika:debug] round=${i} compaction-report n=${n} no-note ${describe(rep)}; retrying\n`);
|
|
2063
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
|
+
});
|
|
2064
2097
|
retry = await report(`${directive}\n\n${COMPACTION_REPORT_RETRY}`, refusedCallTurn(rep));
|
|
2065
2098
|
reportUsage(retry, !!opts.signal?.aborted, notePrompt);
|
|
2066
2099
|
if (opts.signal?.aborted) {
|
|
@@ -2200,6 +2233,16 @@ export async function runTurn(opts) {
|
|
|
2200
2233
|
opts.onContextEstimate?.(Math.round(rawEstimate() * calibration));
|
|
2201
2234
|
return;
|
|
2202
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
|
+
}
|
|
2203
2246
|
const sentTools = subagentForceReport && lastSentTools ? lastSentTools : callTools;
|
|
2204
2247
|
lastSentTools = sentTools;
|
|
2205
2248
|
const sentEstimate = rawEstimate(callHistory, sentTools);
|
|
@@ -2274,6 +2317,7 @@ export async function runTurn(opts) {
|
|
|
2274
2317
|
}
|
|
2275
2318
|
}
|
|
2276
2319
|
: opts.onReasoningDelta;
|
|
2320
|
+
const live = startLiveRound(() => sentEstimate);
|
|
2277
2321
|
const response = await callModel({
|
|
2278
2322
|
system,
|
|
2279
2323
|
history: callHistory,
|
|
@@ -2281,6 +2325,9 @@ export async function runTurn(opts) {
|
|
|
2281
2325
|
config: withGenReserve(opts.config, genReserve),
|
|
2282
2326
|
onContentDelta: opts.onContentDelta,
|
|
2283
2327
|
onReasoningDelta,
|
|
2328
|
+
onOutputDelta: live && (text => live.add(text)),
|
|
2329
|
+
onEngineTimings: live && ((timings, prompt) => live.engine(timings, prompt)),
|
|
2330
|
+
onPromptProgress: opts.onPromptProgress,
|
|
2284
2331
|
signal: callAbort.signal,
|
|
2285
2332
|
calibration,
|
|
2286
2333
|
// Per-turn backstop: cap generation to the room actually left in the window so a
|
|
@@ -2884,6 +2931,28 @@ export async function runTurn(opts) {
|
|
|
2884
2931
|
});
|
|
2885
2932
|
}
|
|
2886
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
|
+
}
|
|
2887
2956
|
// Post-edit typecheck gate. If this turn edited (baseline captured) and a final check shows
|
|
2888
2957
|
// the edits introduced new type errors, send the model back to fix them instead of letting it
|
|
2889
2958
|
// finish on broken code — the harness verifies so the weak model doesn't have to. The model's
|
|
@@ -3047,12 +3116,20 @@ export async function runTurn(opts) {
|
|
|
3047
3116
|
// equipped to make. Now that shouldBounce asks the real question (are those bytes in the
|
|
3048
3117
|
// request the model just answered — see readfirst.ts isLive), the proxy only loses coverage:
|
|
3049
3118
|
// the long unplanned turn is exactly where reads age out beneath the model.
|
|
3050
|
-
const
|
|
3119
|
+
const blindEdit = READ_FIRST &&
|
|
3051
3120
|
!withdrawInspection &&
|
|
3052
3121
|
call.name === 'edit' &&
|
|
3053
3122
|
tool !== undefined &&
|
|
3054
3123
|
typeof call.args.path === 'string' &&
|
|
3055
|
-
readFirst.
|
|
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);
|
|
3056
3133
|
let summary;
|
|
3057
3134
|
let payload;
|
|
3058
3135
|
let diff;
|
|
@@ -3447,6 +3524,7 @@ export async function runTurn(opts) {
|
|
|
3447
3524
|
role: 'assistant',
|
|
3448
3525
|
content: `(reached max turns of ${opts.config.maxTurns}; ask me to continue or raise the turn limit)` +
|
|
3449
3526
|
(await reportTypecheckAtStop()),
|
|
3527
|
+
harnessStop: 'max-turns',
|
|
3450
3528
|
durationMs: Date.now() - turnStart,
|
|
3451
3529
|
...(fetchedUrls.size > 0 ? { sources: [...fetchedUrls] } : {}),
|
|
3452
3530
|
};
|
|
@@ -3520,6 +3598,7 @@ reason = 'loop') {
|
|
|
3520
3598
|
: `I couldn't converge — the reasoning kept looping and was stopped to avoid running ` +
|
|
3521
3599
|
`indefinitely.${examined} This looks like a request the model is getting stuck on; try ` +
|
|
3522
3600
|
`rephrasing or narrowing it, or use a stronger model.`,
|
|
3601
|
+
harnessStop: reason,
|
|
3523
3602
|
durationMs: Date.now() - turnStart,
|
|
3524
3603
|
...(fetchedUrls.size > 0 ? { sources: [...fetchedUrls] } : {}),
|
|
3525
3604
|
};
|
|
@@ -3561,6 +3640,7 @@ function commitAgentLoopStop(opts, turnStart, fetchedUrls, edited, typecheckAdde
|
|
|
3561
3640
|
const m = {
|
|
3562
3641
|
role: 'assistant',
|
|
3563
3642
|
content,
|
|
3643
|
+
harnessStop: 'loop',
|
|
3564
3644
|
durationMs: Date.now() - turnStart,
|
|
3565
3645
|
...(fetchedUrls.size > 0 ? { sources: [...fetchedUrls] } : {}),
|
|
3566
3646
|
};
|
|
@@ -3623,6 +3703,7 @@ function makeSpawnSubagent(parent, budget, parentDecodeRate, parentGenReserve) {
|
|
|
3623
3703
|
requestApproval: parent.requestApproval,
|
|
3624
3704
|
isUnattended: parent.isUnattended,
|
|
3625
3705
|
onUsage: parent.onUsage,
|
|
3706
|
+
onLiveUsage: parent.onLiveUsage,
|
|
3626
3707
|
priorDecodeRate: sameEngine ? parentDecodeRate.get() : undefined,
|
|
3627
3708
|
genReserve: sameEngine ? parentGenReserve : undefined,
|
|
3628
3709
|
onDecodeRate: rate => {
|
|
@@ -3639,6 +3720,7 @@ function makeSpawnSubagent(parent, budget, parentDecodeRate, parentGenReserve) {
|
|
|
3639
3720
|
// them nested via onSubagent.
|
|
3640
3721
|
onContentDelta: parent.onContentDelta,
|
|
3641
3722
|
onReasoningDelta: parent.onReasoningDelta,
|
|
3723
|
+
onPromptProgress: parent.onPromptProgress,
|
|
3642
3724
|
onToolProgress: parent.onToolProgress,
|
|
3643
3725
|
// `onToolStart` is the one callback deliberately NOT forwarded (#509). The parent's live row
|
|
3644
3726
|
// is a single slot keyed to its own round: forwarding a nested start would overwrite the
|
package/dist/agent/readfirst.js
CHANGED
|
@@ -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
|
-
|
|
108
|
-
if (this.bounced.has(p))
|
|
113
|
+
if (this.bounced.has(this.norm(path)))
|
|
109
114
|
return false;
|
|
110
|
-
|
|
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 ' +
|
package/dist/cli.js
CHANGED
|
@@ -36,10 +36,10 @@ if (headless?.help) {
|
|
|
36
36
|
process.exit(0);
|
|
37
37
|
}
|
|
38
38
|
if (headless) {
|
|
39
|
-
const { runHeadless } = await import('./headless/headless.js');
|
|
39
|
+
const { runHeadless, terminalSafeWriter } = await import('./headless/headless.js');
|
|
40
40
|
const code = await runHeadless(headless, {
|
|
41
|
-
stdout:
|
|
42
|
-
stderr:
|
|
41
|
+
stdout: terminalSafeWriter(process.stdout),
|
|
42
|
+
stderr: terminalSafeWriter(process.stderr),
|
|
43
43
|
readStdin: async () => {
|
|
44
44
|
if (process.stdin.isTTY) {
|
|
45
45
|
process.stderr.write(`reika: -p needs a prompt or piped stdin\n${USAGE}\n`);
|