@0perator/operator 0.1.62 → 0.1.154
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/CHANGELOG.md +1035 -0
- package/LICENSE +19 -0
- package/dist/acp/agent.js +103 -0
- package/dist/acp/run.js +23 -0
- package/dist/auth/client.js +4 -1
- package/dist/auth/login-intent.js +12 -0
- package/dist/autonomy/board-run.js +65 -0
- package/dist/autonomy/board.js +83 -0
- package/dist/autonomy/dream.js +71 -0
- package/dist/autonomy/headless.js +70 -0
- package/dist/autonomy/index.js +260 -0
- package/dist/autonomy/keepawake.js +84 -0
- package/dist/autonomy/loop.js +82 -0
- package/dist/autonomy/reporter.js +54 -0
- package/dist/autonomy/routine-run.js +25 -0
- package/dist/autonomy/routines.js +173 -0
- package/dist/autonomy/session-factory.js +61 -0
- package/dist/background/index.js +275 -20
- package/dist/background/worktree.js +62 -0
- package/dist/cli.js +518 -95
- package/dist/config/brand.js +81 -0
- package/dist/config/operator-harness.js +86 -0
- package/dist/config/persona.js +174 -0
- package/dist/config/settings.js +98 -9
- package/dist/engine/agent.js +447 -51
- package/dist/engine/aurora.js +180 -64
- package/dist/engine/compaction.js +97 -5
- package/dist/engine/grandmaster.js +69 -10
- package/dist/engine/router-adapter.js +3 -0
- package/dist/engine/selfheal.js +35 -0
- package/dist/engine/verify-gate.js +81 -0
- package/dist/mcp/index.js +1 -1
- package/dist/permissions/index.js +13 -7
- package/dist/router/models.js +1 -1
- package/dist/router/router.js +46 -7
- package/dist/selfimprove/index.js +88 -0
- package/dist/services/preflight.js +42 -1
- package/dist/session.js +239 -22
- package/dist/telemetry/events.js +9 -0
- package/dist/tools/executor.js +62 -24
- package/dist/tools/git-status.js +71 -0
- package/dist/tools/mutating.js +9 -0
- package/dist/tools/registry.js +247 -26
- package/dist/tools/result-cap.js +23 -0
- package/dist/tools/searxng.js +42 -2
- package/dist/tools/shell-context.js +17 -0
- package/dist/ui/ActivitySpinner.js +6 -5
- package/dist/ui/App.js +23 -5
- package/dist/ui/AuthScreen.js +1 -1
- package/dist/ui/BgPanel.js +60 -5
- package/dist/ui/Composer.js +135 -13
- package/dist/ui/Header.js +6 -4
- package/dist/ui/InputRule.js +2 -1
- package/dist/ui/Markdown.js +69 -10
- package/dist/ui/Masthead.js +6 -4
- package/dist/ui/PlanPane.js +23 -0
- package/dist/ui/QuestionPrompt.js +22 -8
- package/dist/ui/StatsCard.js +15 -0
- package/dist/ui/StatusRule.js +13 -4
- package/dist/ui/SummaryCard.js +18 -0
- package/dist/ui/Table.js +114 -0
- package/dist/ui/ThinkingSpinner.js +6 -4
- package/dist/ui/ToolBatch.js +12 -0
- package/dist/ui/ToolStep.js +12 -4
- package/dist/ui/Transcript.js +30 -6
- package/dist/ui/chart.js +34 -0
- package/dist/ui/editdiff.js +84 -0
- package/dist/ui/highlight.js +89 -0
- package/dist/ui/osc.js +32 -0
- package/dist/ui/planExit.js +26 -0
- package/dist/ui/term.js +16 -0
- package/dist/ui/theme.js +60 -0
- package/dist/ui/tree.js +71 -0
- package/dist/util/slash.js +15 -0
- package/dist/util/throttle.js +28 -0
- package/package.json +11 -2
package/dist/engine/agent.js
CHANGED
|
@@ -5,13 +5,103 @@
|
|
|
5
5
|
import { chat } from "./aurora.js";
|
|
6
6
|
import { buildMessages } from "./messages.js";
|
|
7
7
|
import { recoverToolCalls } from "./toolcalls.js";
|
|
8
|
-
import { compact, needsCompaction, clampMaxTokens } from "./compaction.js";
|
|
9
|
-
import { classifyFailure, backoffMs, sleep } from "./selfheal.js";
|
|
8
|
+
import { compact, needsCompaction, shouldProactivelyCompact, fitToWindow, clampMaxTokens } from "./compaction.js";
|
|
9
|
+
import { classifyFailure, servedContextLimit, backoffMs, sleep } from "./selfheal.js";
|
|
10
|
+
import { TaskVerification, VERIFY_REMINDER, NOT_VERIFIED_BANNER } from "./verify-gate.js";
|
|
10
11
|
const MAX_SELF_HEAL_PER_TURN = 3;
|
|
11
|
-
|
|
12
|
-
|
|
12
|
+
// A "loading" 503 (endpoint restarting/warming) is a KNOWN-recoverable WAIT, not a failure — a model reload
|
|
13
|
+
// is ~30-90s, far longer than the ≤8s exponential self-heal backoff, so it gets its own patient budget that
|
|
14
|
+
// outlasts a reload instead of dying after 3 quick tries. 20 × 6s ≈ 2min ceiling, then surface honestly.
|
|
15
|
+
const MAX_LOADING_RETRIES = 20;
|
|
16
|
+
const DEFAULT_LOADING_BACKOFF_MS = 6000;
|
|
17
|
+
const LOOP_GUARD_LIMIT = 5; // identical (name+args) calls in a turn before short-circuiting — but a file
|
|
18
|
+
// mutation RESETS the count (see MUTATING_TOOLS): re-running the SAME test/build/compose after editing a
|
|
19
|
+
// file is verify-after-fix iteration, not a spin, so it must be unbounded. Only a genuinely repeated call
|
|
20
|
+
// with NO intervening edit (a true no-progress loop) trips this. Raised 3→5 so even a no-edit re-run has
|
|
21
|
+
// headroom before the guard fires. The narration/no-progress stalls below are the separate progress-gated stops.
|
|
22
|
+
import { MUTATING_TOOLS } from "../tools/mutating.js"; // single source of truth (see tools/mutating.ts) — a workspace edit ⇒ prior identical-call counts are stale
|
|
23
|
+
// Poll/status tools are meant to be called repeatedly while waiting on async work — NEVER a spin, so the
|
|
24
|
+
// loop guard skips them entirely (agent_status polls sub-agents, bash_output polls a background job).
|
|
25
|
+
const LOOP_GUARD_EXEMPT = new Set(["agent_status", "bash_output"]);
|
|
26
|
+
const CONTENT_LOOP_LIMIT = 3; // whole round (prose + actions) repeats this many times ⇒ light NUDGE to pivot
|
|
27
|
+
const CONTENT_LOOP_REDIRECT = 6; // …and at this many, escalate to a FORCED REDIRECT: make the model diagnose the
|
|
28
|
+
// loop and decompose OR switch approach, then reset its runway and CONTINUE (enterprise loop-recovery — the
|
|
29
|
+
// model self-corrects instead of the turn stopping). Only after CONTENT_LOOP_REDIRECT_MAX forced redirects on a
|
|
30
|
+
// still-unbroken loop does the turn finally hand back — so an autonomous session self-corrects for ~3× longer.
|
|
31
|
+
const CONTENT_LOOP_REDIRECT_MAX = 3;
|
|
13
32
|
const MAX_EMPTY_RETRIES = 1; // one nudge on an empty "dud" round before finalizing
|
|
14
|
-
const NO_PROGRESS_LIMIT =
|
|
33
|
+
const NO_PROGRESS_LIMIT = 8; // consecutive tool batches that return NOTHING new (past the soft budget) ⇒ genuine stall.
|
|
34
|
+
// Raised 6→8: a long, genuinely-progressing task can go momentarily quiet (a planning/reasoning round, a couple
|
|
35
|
+
// of empty greps) without being stalled — 8 empty-in-a-row is an unambiguous stall, still far below absCeiling.
|
|
36
|
+
// Stuck-turn guard. A turn can loop with work that VARIES just enough to slip every signature guard above
|
|
37
|
+
// (live 09-27: ~150 rounds / 28 min of diagnostic bash probes differing only in comments / heredoc-vs-`-c`,
|
|
38
|
+
// ZERO file edits, the model itself repeatedly writing "I'm stuck in a loop"). The one signal none of the
|
|
39
|
+
// identical-call / content-loop / no-progress guards catch is the model's OWN admission it is looping. A
|
|
40
|
+
// REPEATED admission with no file edit in between is the unambiguous stuck signal — very low false-positive,
|
|
41
|
+
// since a legitimate long read-only task (research, a big search) does not announce it is going in circles.
|
|
42
|
+
// So: an admission NUDGES and, if it repeats to SELF_LOOP_STOP with nothing breaking it, ends the turn
|
|
43
|
+
// gracefully (hands control back — never a freeze). Separately, a long run of tool rounds that touch no file
|
|
44
|
+
// only ever NUDGES once (NO_EDIT_NUDGE); it never stops a turn, so a genuine long read-only task is safe.
|
|
45
|
+
const SELF_LOOP_RE = /\b(stuck in a loop|going in circles|in an?(?: infinite)? loop|repeating (?:the same|myself|it)|same (?:code|thing|approach|command)(?: keeps| is| that)?(?: getting)? repeat|keep (?:repeating|doing the same|getting the same)|(?:try|take|need) (?:a |an )?(?:fresh|different|new|another) approach)\b/i;
|
|
46
|
+
const SELF_LOOP_STOP = 3; // model admits it's looping this many rounds (no file edit between) ⇒ graceful stop
|
|
47
|
+
const NO_EDIT_NUDGE = 15; // tool rounds that change NO file ⇒ ONE soft "converge, or say you're blocked" nudge (never a stop)
|
|
48
|
+
const REHYDRATE_MAX_FILES = 5; // after a compaction, name up to this many recently-touched files for the model to re-read
|
|
49
|
+
const COMPACTION_FAIL_LIMIT = 3; // rounds still OVER the window after compaction ran ⇒ it can't free space (summarizer failing / un-evictable bulk); stop spinning into the same wall
|
|
50
|
+
const MAX_TRUNC_RETRIES = 3; // chunk-write nudges before a repeatedly-truncated tool call surfaces honestly — a
|
|
51
|
+
// genuinely large body (docstring, generated file) can need one extra round past the quote-fix case: first
|
|
52
|
+
// nudge gets it chunking, second confirms the chunks are actually small enough
|
|
53
|
+
// Injected as a user-role nudge when the server rejects the model's own tool-call JSON as malformed (aurora
|
|
54
|
+
// /v1 500 "Failed to parse tool call arguments as JSON: missing closing quote" / "Unterminated string" —
|
|
55
|
+
// see selfheal's truncated_tool_call). TWO distinct causes produce that same server error: (1) a raw
|
|
56
|
+
// double-quote inside a string argument (e.g. a grep pattern) — the SHORT-command case seen live 09-26
|
|
57
|
+
// (`grep -l "^dependencies"`); (2) an over-long file_write/file_edit body (a ~2000-char triple-quoted Python
|
|
58
|
+
// docstring edit, seen live 09-26) cut off at the output-token limit. A single nudge listing both fixes made
|
|
59
|
+
// the model reach for the wrong one — re-quoting a call that was never a quoting problem, burning the retry
|
|
60
|
+
// budget on a large edit until it surfaced as a hard turn error instead of recovering. The server's own error
|
|
61
|
+
// message usually says WHERE the JSON parser choked ("at column 1999" / "at position 7992"); a short shell
|
|
62
|
+
// command breaks in the first few dozen characters, a truncated large body breaks in the hundreds/thousands
|
|
63
|
+
// — so that position picks the nudge that actually applies. No position in the message (older/other server
|
|
64
|
+
// wording) falls back to the original both-fixes text. Failing over is futile either way (the same call
|
|
65
|
+
// truncates on the next endpoint), so this always retries the SAME endpoint. Kept short: read mid-turn, not a
|
|
66
|
+
// standing directive. A user role (not a 2nd system message, which 400s the endpoint — SPEC §1).
|
|
67
|
+
const TRUNC_POS_RE = /at (?:column|position) (\d+)/i;
|
|
68
|
+
const TRUNC_LARGE_BODY_CHARS = 300; // past this, "cut off at column/position N" means a big body, not a quoted command
|
|
69
|
+
function truncatedToolPos(message) {
|
|
70
|
+
const m = TRUNC_POS_RE.exec(message);
|
|
71
|
+
return m ? Number(m[1]) : undefined;
|
|
72
|
+
}
|
|
73
|
+
const TRUNCATED_TOOL_NUDGE_QUOTE = "Your last tool call's arguments were not valid JSON — a double-quote inside a string argument broke it " +
|
|
74
|
+
"(e.g. grep -l \"^x\"). Rewrite it with SINGLE quotes or none — grep -l '^x', or grep -lE ^x — and retry.";
|
|
75
|
+
const TRUNCATED_TOOL_NUDGE_LARGE = "Your last tool call's arguments were not valid JSON — the content was cut off mid-string because it was " +
|
|
76
|
+
"too long for ONE call, not a quoting problem. Do not resend the same single large call. If it is a FILE, " +
|
|
77
|
+
"split it now: file_write a SMALL first chunk (a few dozen lines), then one or more file_edit calls to " +
|
|
78
|
+
"append the rest, each comfortably under ~1KB. If it is a single note/message that CANNOT be split (e.g. " +
|
|
79
|
+
"session_handoff, a message), rewrite it MUCH shorter — a few concise lines. If it is a MULTI-LINE SCRIPT " +
|
|
80
|
+
"inside a command (e.g. `python3 -c \"…many lines…\"` or `bash -c`), do NOT inline it — the newlines and " +
|
|
81
|
+
"quotes are what broke the JSON: write the script to a file with file_write, then run the file " +
|
|
82
|
+
"(`python3 /tmp/x.py`). Applies to any large body — a docstring, a generated file, a long config, a handoff note.";
|
|
83
|
+
const TRUNCATED_TOOL_NUDGE_GENERIC = "Your last tool call's arguments were not valid JSON, so it did not run. Rewrite it and retry — fix whichever applies:\n" +
|
|
84
|
+
"1. A double-quote inside a string argument can break the tool-call JSON. If a command contains \" (e.g. grep -l \"^x\"), " +
|
|
85
|
+
"rewrite it with SINGLE quotes or none — grep -l '^x', or grep -lE ^x. Prefer single quotes for any shell pattern/path with special characters.\n" +
|
|
86
|
+
"2. If it was a large file write cut off mid-content, split it: an initial file_write, then file_edit to append each further part, a few hundred lines per call.";
|
|
87
|
+
/** Pick the nudge that matches the actual cause when the server's error names WHERE it choked; falls back
|
|
88
|
+
* to the both-fixes text when it doesn't. */
|
|
89
|
+
function truncatedToolNudge(message) {
|
|
90
|
+
// A MULTI-LINE content body (a file body, a session_handoff note, a long message) is echoed by the server's
|
|
91
|
+
// "last read: '…'" with escaped newlines; a shell command never has them. So 2+ escaped newlines means the
|
|
92
|
+
// call was cut off because the CONTENT is long/multi-line — a truncation, NOT a stray embedded quote —
|
|
93
|
+
// regardless of how early the column is. This is the session_handoff case seen live 09-26: a note that
|
|
94
|
+
// truncated at column 164 (a premature model stop) was misclassified by the column heuristic as a quoting
|
|
95
|
+
// bug (<300 → quote nudge), so the model kept re-quoting a call that had no quote problem and burned all
|
|
96
|
+
// three retries into a hard turn error. Route multi-line bodies to the shorten/split nudge first.
|
|
97
|
+
const escapedNewlines = (message.match(/\\n/g) ?? []).length;
|
|
98
|
+
if (escapedNewlines >= 2)
|
|
99
|
+
return TRUNCATED_TOOL_NUDGE_LARGE;
|
|
100
|
+
const pos = truncatedToolPos(message);
|
|
101
|
+
if (pos === undefined)
|
|
102
|
+
return TRUNCATED_TOOL_NUDGE_GENERIC;
|
|
103
|
+
return pos >= TRUNC_LARGE_BODY_CHARS ? TRUNCATED_TOOL_NUDGE_LARGE : TRUNCATED_TOOL_NUDGE_QUOTE;
|
|
104
|
+
}
|
|
15
105
|
/** Fingerprint of an assistant round's PROSE, for catching a model narrating in circles while its
|
|
16
106
|
* tools make no progress (the "12× Empty outputs" burn). Strips embedded tool-call JSON / code fences
|
|
17
107
|
* so the fingerprint is the PROSE, stable even when the (varying) call args live inside the content
|
|
@@ -28,15 +118,34 @@ function contentSignature(content) {
|
|
|
28
118
|
.trim()
|
|
29
119
|
.slice(0, 200);
|
|
30
120
|
}
|
|
31
|
-
/** A tool batch "progressed" if any result
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
*
|
|
121
|
+
/** A tool batch "progressed" if any result shows the batch advanced the world. Gates BOTH the no-progress
|
|
122
|
+
* stall streak and the narration-loop guard, so a templated narration over PRODUCTIVE work is never
|
|
123
|
+
* mistaken for a loop. A result is a STALL sentinel only if it's empty, a FAILED silent command
|
|
124
|
+
* ("(no output; exit N)"), an error, or the executor's loop guard. A bare "(no output)" is an exit-0
|
|
125
|
+
* success — a heredoc that wrote a file, a mkdir, a silent passing check — which IS progress: counting
|
|
126
|
+
* it as a stall cut a live build off at round 11 because it wrote files via `cat > f <<EOF` heredocs
|
|
127
|
+
* (registry.ts returns "(no output)" for a silent success), and six of those in a row tripped the
|
|
128
|
+
* no-progress limit. `write`/`edit` return "wrote …"/"edited …", so those were never the problem. */
|
|
35
129
|
function batchProgressed(toolMsgs) {
|
|
36
130
|
return toolMsgs.some((tm) => {
|
|
37
131
|
const c = (tm.content || "").trim();
|
|
38
|
-
return c.length > 0 && !/^\(no output|^error[:\s]|^loop guard/i.test(c);
|
|
132
|
+
return c.length > 0 && !/^\(no output; exit|^error[:\s]|^loop guard/i.test(c);
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
/** Feed one settled tool batch to the verify-before-done ledger: zip each call's name + (parsed)
|
|
136
|
+
* `command` arg with its result string (index-aligned — runToolCalls preserves call order). */
|
|
137
|
+
function observeVerify(v, calls, toolMsgs) {
|
|
138
|
+
const names = calls.map((c) => c.function.name);
|
|
139
|
+
const commands = calls.map((c) => {
|
|
140
|
+
try {
|
|
141
|
+
return String(JSON.parse(c.function.arguments || "{}").command ?? "");
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
return "";
|
|
145
|
+
}
|
|
39
146
|
});
|
|
147
|
+
const results = toolMsgs.map((m) => m.content || "");
|
|
148
|
+
v.observe(names, commands, results);
|
|
40
149
|
}
|
|
41
150
|
/** Thrown by runTurn when the turn is interrupted via AgentOpts.signal (SPEC §9). One type for hosts to catch. */
|
|
42
151
|
export class TurnAbortedError extends Error {
|
|
@@ -49,6 +158,24 @@ function throwIfAborted(signal) {
|
|
|
49
158
|
if (signal?.aborted)
|
|
50
159
|
throw new TurnAbortedError();
|
|
51
160
|
}
|
|
161
|
+
/** Race a promise against the turn's abort signal so an interactive user's esc (which aborts opts.signal)
|
|
162
|
+
* ALWAYS returns control to the turn loop — even if the awaited work never resolves on its own (a hung tool
|
|
163
|
+
* whose child process is blocked on a lock/hook/prompt, the "checkpoint spins forever, esc won't help" freeze
|
|
164
|
+
* 2026-09-28). Rejects with TurnAbortedError on abort; the loop's abort handling then ends the turn cleanly.
|
|
165
|
+
* The abandoned work keeps running to its OWN timeout (tools set their own — e.g. checkpoint's git steps), but
|
|
166
|
+
* the SESSION is never frozen. The listener is removed on settle, so a batch that finishes normally leaks
|
|
167
|
+
* nothing. No signal → returns the promise unchanged (headless/tests). */
|
|
168
|
+
export function abortable(p, signal) {
|
|
169
|
+
if (!signal)
|
|
170
|
+
return p;
|
|
171
|
+
if (signal.aborted)
|
|
172
|
+
return Promise.reject(new TurnAbortedError());
|
|
173
|
+
return new Promise((resolve, reject) => {
|
|
174
|
+
const onAbort = () => reject(new TurnAbortedError());
|
|
175
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
176
|
+
p.then((v) => { signal.removeEventListener("abort", onAbort); resolve(v); }, (e) => { signal.removeEventListener("abort", onAbort); reject(e); });
|
|
177
|
+
});
|
|
178
|
+
}
|
|
52
179
|
/**
|
|
53
180
|
* True when `err` is (or happened during) an abort. Checking `signal.aborted` first is what makes
|
|
54
181
|
* this robust: once the user aborts, fetch rejects with a DOMException("AbortError") we must NOT
|
|
@@ -91,55 +218,125 @@ function parseArgs(raw) {
|
|
|
91
218
|
* batch via onToolBatch with a real (unrounded) duration.
|
|
92
219
|
*/
|
|
93
220
|
async function runToolCalls(toolCalls, tools, callCounts, onToolBatch, onToolStart, onToolResult) {
|
|
221
|
+
// One id for this whole round (SPEC parallel-tool-batch) — every call made here, however it
|
|
222
|
+
// resolves (executed, parse error, loop-guarded), shares it, so a host can box "N tools in
|
|
223
|
+
// parallel" together even for the calls that never reached the executor. Same id-shape idiom as
|
|
224
|
+
// board.ts/remote/host.ts (time + random suffix) — no node:crypto import, since this file is also
|
|
225
|
+
// loaded by the browser bundle (kode-web via index.browser.ts).
|
|
226
|
+
const batchId = "b" + Date.now().toString(36) + Math.random().toString(36).slice(2, 8);
|
|
227
|
+
const batchSize = toolCalls.length;
|
|
94
228
|
const pending = [];
|
|
95
229
|
const preResolved = new Map(); // id -> result, for parse errors + loop-guarded calls
|
|
96
230
|
const parsedArgs = new Map();
|
|
97
|
-
|
|
231
|
+
toolCalls.forEach((tc, batchIndex) => {
|
|
98
232
|
const parsed = parseArgs(tc.function.arguments);
|
|
99
233
|
if (!parsed.ok) {
|
|
100
234
|
preResolved.set(tc.id, `Error: could not parse arguments for tool "${tc.function.name}": ${parsed.error}`);
|
|
101
235
|
parsedArgs.set(tc.id, {});
|
|
102
|
-
|
|
236
|
+
return;
|
|
103
237
|
}
|
|
104
238
|
parsedArgs.set(tc.id, parsed.args);
|
|
239
|
+
// Poll/status tools (agent_status, bash_output) are DESIGNED to be called repeatedly with identical
|
|
240
|
+
// args while waiting on async work — that's not a spin, so they are never loop-guarded. Live 09-27:
|
|
241
|
+
// agent_status polled while sub-agents ran tripped the guard at 5 (and kept firing) even though the
|
|
242
|
+
// model was doing real work between polls.
|
|
243
|
+
if (LOOP_GUARD_EXEMPT.has(tc.function.name)) {
|
|
244
|
+
pending.push({ id: tc.id, name: tc.function.name, args: parsed.args, batchId, batchSize, batchIndex });
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
105
247
|
const sig = callSignature(tc.function.name, parsed.args);
|
|
106
248
|
const count = (callCounts.get(sig) ?? 0) + 1;
|
|
107
249
|
callCounts.set(sig, count);
|
|
108
|
-
if (count >= LOOP_GUARD_LIMIT) { // SPEC §2: short-circuit the
|
|
250
|
+
if (count >= LOOP_GUARD_LIMIT) { // SPEC §2: short-circuit the Nth identical call (matches executor's guard)
|
|
109
251
|
preResolved.set(tc.id, `Loop guard: "${tc.function.name}" has been called ${count} times this turn with identical ` +
|
|
110
252
|
`arguments. Try a different approach instead of repeating this call.`);
|
|
111
|
-
|
|
253
|
+
return;
|
|
112
254
|
}
|
|
113
|
-
pending.push({ id: tc.id, name: tc.function.name, args: parsed.args });
|
|
114
|
-
}
|
|
255
|
+
pending.push({ id: tc.id, name: tc.function.name, args: parsed.args, batchId, batchSize, batchIndex });
|
|
256
|
+
});
|
|
115
257
|
if (pending.length)
|
|
116
258
|
onToolStart?.(pending);
|
|
117
259
|
const started = performance.now();
|
|
118
260
|
const executed = pending.length
|
|
119
|
-
? await tools.executeParallel(pending, onToolResult ? (i, r) => onToolResult(pending[i].id, r) : undefined)
|
|
261
|
+
? await tools.executeParallel(pending, onToolResult ? (i, r) => onToolResult(pending[i].id, r, batchId) : undefined)
|
|
120
262
|
: [];
|
|
121
263
|
const durationMs = performance.now() - started;
|
|
122
264
|
const resultById = new Map(preResolved);
|
|
123
265
|
pending.forEach((p, i) => resultById.set(p.id, executed[i]));
|
|
266
|
+
// A file edit this round changed the workspace, so every prior "identical call" count is stale — a
|
|
267
|
+
// re-run of the same test/build/compose is now verify-after-fix progress, not a loop. Clear the counts so
|
|
268
|
+
// the next round's repeats start fresh; only a call repeated with NO intervening edit keeps accumulating
|
|
269
|
+
// toward LOOP_GUARD_LIMIT. This is what lets Operator iterate (edit → re-run → edit → re-run) unbounded.
|
|
270
|
+
if (pending.some((p) => MUTATING_TOOLS.has(p.name)))
|
|
271
|
+
callCounts.clear();
|
|
124
272
|
if (onToolBatch) {
|
|
125
|
-
const events = toolCalls.map((tc) => ({
|
|
273
|
+
const events = toolCalls.map((tc, batchIndex) => ({
|
|
126
274
|
name: tc.function.name,
|
|
127
275
|
args: parsedArgs.get(tc.id) ?? {},
|
|
128
276
|
result: resultById.get(tc.id) ?? "",
|
|
277
|
+
batchId,
|
|
278
|
+
batchSize,
|
|
279
|
+
batchIndex,
|
|
129
280
|
}));
|
|
130
281
|
onToolBatch(events, durationMs);
|
|
131
282
|
}
|
|
132
283
|
return toolCalls.map((tc) => ({ role: "tool", content: resultById.get(tc.id) ?? "", tool_call_id: tc.id }));
|
|
133
284
|
}
|
|
285
|
+
// Rehydration (enterprise compaction, continuity half). A compaction summarizes away raw tool outputs — a
|
|
286
|
+
// file the model read 20 turns ago now survives only as a lossy summary, so a later edit can act on STALE
|
|
287
|
+
// content. Track the files the model actually read/edited (LRU, most-recent first) and, right after a
|
|
288
|
+
// compaction, inject a note that (a) points the model back to the summary's plan and (b) names those files so
|
|
289
|
+
// it re-reads their CURRENT state before relying on them. Path is pulled from any tool call carrying a
|
|
290
|
+
// `path`/`paths` arg (file_read/file_edit/file_write/read_files), so it's tool-name-agnostic.
|
|
291
|
+
export function trackTouchedFiles(calls, touched) {
|
|
292
|
+
for (const c of calls) {
|
|
293
|
+
let paths = [];
|
|
294
|
+
try {
|
|
295
|
+
const a = JSON.parse(c.function?.arguments ?? "{}");
|
|
296
|
+
if (Array.isArray(a?.paths))
|
|
297
|
+
paths = a.paths.filter((p) => typeof p === "string");
|
|
298
|
+
else if (typeof a?.path === "string")
|
|
299
|
+
paths = [a.path];
|
|
300
|
+
}
|
|
301
|
+
catch { /* unparseable args — skip */ }
|
|
302
|
+
for (const p of paths) {
|
|
303
|
+
const i = touched.indexOf(p);
|
|
304
|
+
if (i >= 0)
|
|
305
|
+
touched.splice(i, 1);
|
|
306
|
+
touched.unshift(p);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
if (touched.length > REHYDRATE_MAX_FILES)
|
|
310
|
+
touched.length = REHYDRATE_MAX_FILES;
|
|
311
|
+
}
|
|
312
|
+
export function rehydrationNote(touched) {
|
|
313
|
+
const base = "[Context was just compacted to free space — the tool outputs and file contents above are now summarized " +
|
|
314
|
+
"and may be STALE. Resume from the summary's PENDING and NEXT STEP. Before you edit or rely on any file, " +
|
|
315
|
+
"re-read it fresh with file_read — do NOT trust a summarized earlier read";
|
|
316
|
+
return touched.length ? `${base}. Files you were working on (re-read before relying on them): ${touched.join(", ")}.]` : `${base}.]`;
|
|
317
|
+
}
|
|
134
318
|
/** Runs one user turn to completion: compacts, loops model↔tools ≤maxRounds, self-heals, finalizes. */
|
|
135
319
|
export async function runTurn(userInput, conversation, opts) {
|
|
136
320
|
const softRounds = opts.maxRounds ?? 10;
|
|
137
|
-
const absCeiling = Math.max(softRounds + 1, opts.maxRoundsHard ??
|
|
321
|
+
const absCeiling = Math.max(softRounds + 1, opts.maxRoundsHard ?? 400); // absolute safety stop; progress-aware below
|
|
138
322
|
const callCounts = new Map();
|
|
139
323
|
const contentSigs = new Map(); // per-round prose fingerprints → the narration loop guard
|
|
324
|
+
let forcedRedirects = 0; // enterprise loop-recovery: forced redirects spent this turn (each resets a repeated round's runway; the turn hands back only after CONTENT_LOOP_REDIRECT_MAX of them fail to break the loop)
|
|
140
325
|
let progressed = true; // did the PREVIOUS tool batch advance? gates the guard (progress clears it)
|
|
141
326
|
let noProgressStreak = 0; // consecutive tool batches that returned nothing new; reset by any real progress
|
|
327
|
+
let selfLoopStreak = 0; // consecutive rounds the model admitted it's looping, uninterrupted by a file edit
|
|
328
|
+
let noEditStreak = 0; // consecutive tool rounds that changed no file — investigating, not fixing
|
|
329
|
+
let noEditNudged = false; // the soft no-edit nudge fires at most once per turn
|
|
330
|
+
const touchedFiles = []; // files read/edited this turn (LRU) — re-surfaced by rehydration after a compaction
|
|
331
|
+
let compactionFailStreak = 0; // consecutive rounds still over budget after compaction fired — the circuit breaker
|
|
142
332
|
let selfHealBudget = MAX_SELF_HEAL_PER_TURN;
|
|
333
|
+
// Verify-before-done: a turn-local ledger of "changed files but never ran a passing check" (computed
|
|
334
|
+
// from observed tool execution, never self-reported). At the done-exit it injects ONE reminder to run
|
|
335
|
+
// the check; if the model still doesn't, the answer is finalized with an honest "not verified" banner.
|
|
336
|
+
const verify = new TaskVerification();
|
|
337
|
+
const verifyEnabled = opts.verifyGate?.enabled !== false;
|
|
338
|
+
const verifyMaxNudges = Math.max(0, opts.verifyGate?.maxNudges ?? 1);
|
|
339
|
+
let verifyNudges = 0;
|
|
143
340
|
conversation.user(userInput);
|
|
144
341
|
let rounds = 0;
|
|
145
342
|
let toolCallTotal = 0;
|
|
@@ -148,14 +345,36 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
148
345
|
let promptTokensTotal = 0; // prompt tokens PREFILLED, summed across rounds
|
|
149
346
|
let promptMsTotal = 0; // prefill ms summed across rounds
|
|
150
347
|
let emptyRetries = 0; // reasoning models sometimes return a "dud" round (no content, no tool calls)
|
|
348
|
+
let truncRetries = 0; // chunk-write nudges spent recovering a truncated-tool-call 500 (truncatedToolNudge)
|
|
349
|
+
let loadingRetries = 0; // patient waits spent while an endpoint reports it's still (re)loading its model
|
|
151
350
|
for (; rounds < absCeiling; rounds++) {
|
|
152
351
|
throwIfAborted(opts.signal); // stop before spending another round (covers compaction below too)
|
|
352
|
+
// Opt-in per-turn COST ceiling: if this turn has already spent its token budget, wrap up gracefully at the
|
|
353
|
+
// round boundary (never mid-round) instead of running on. A safety cap for cost-sensitive / unattended runs;
|
|
354
|
+
// complements the round ceiling + no-progress guards. The "[paused —" prefix (not "[stopped —") keeps the
|
|
355
|
+
// flywheel from misreading a budget stop as a failure-lesson.
|
|
356
|
+
if (opts.maxTurnTokens && rounds > 0 && tokensTotal + promptTokensTotal >= opts.maxTurnTokens) {
|
|
357
|
+
const spent = tokensTotal + promptTokensTotal;
|
|
358
|
+
const note = `[paused — this turn reached its token budget (${spent} ≥ ${opts.maxTurnTokens} tokens). ` +
|
|
359
|
+
`The work so far is above; continue with a fresh, focused request, or raise the budget ` +
|
|
360
|
+
`(KODE_TURN_MAX_TOKENS / settings.maxTurnTokens).]`;
|
|
361
|
+
conversation.assistant(note);
|
|
362
|
+
return { content: note, rounds, toolCalls: toolCallTotal, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal };
|
|
363
|
+
}
|
|
153
364
|
if (rounds === softRounds)
|
|
154
365
|
opts.onAutoContinue?.(rounds); // crossed the soft budget, still working — keep going while progressing
|
|
155
366
|
// Progress-aware stop: past the soft budget, end the turn only on a GENUINE stall (N consecutive
|
|
156
367
|
// tool batches that returned nothing new). A turn that keeps finding results runs to absCeiling.
|
|
157
368
|
if (rounds > softRounds && noProgressStreak >= NO_PROGRESS_LIMIT)
|
|
158
369
|
break;
|
|
370
|
+
// Soft checkpoint: many tool rounds with no file edit — investigating, not fixing. Nudge ONCE (never
|
|
371
|
+
// stop; a legitimate long read-only task is valid) to convert insight into action or surface a blocker.
|
|
372
|
+
if (!noEditNudged && noEditStreak >= NO_EDIT_NUDGE) {
|
|
373
|
+
noEditNudged = true;
|
|
374
|
+
conversation.user(`You've run ${noEditStreak} rounds of tools without changing a file. If you've found the root cause, ` +
|
|
375
|
+
`make the change now and verify it. If you're still gathering context that's fine — but if you're ` +
|
|
376
|
+
`going in circles, say so and switch to a genuinely different approach.`);
|
|
377
|
+
}
|
|
159
378
|
let endpoint = opts.router.select(buildMessages(opts.systemPrompt, conversation.all), opts.toolSchemas);
|
|
160
379
|
opts.onRoute?.(endpoint);
|
|
161
380
|
// Endpoint-aware (SPEC §5): rebuild against whichever endpoint is current, since self-heal
|
|
@@ -166,13 +385,46 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
166
385
|
tools: opts.toolSchemas,
|
|
167
386
|
summarize: opts.summarize,
|
|
168
387
|
threshold: opts.compactionThreshold,
|
|
388
|
+
ceilingTokens: opts.compactionCeilingTokens,
|
|
169
389
|
minKeepTurns: opts.minKeepTurns,
|
|
170
390
|
});
|
|
171
|
-
if (needsCompaction(conversation.all, compactionOptsFor(endpoint))) {
|
|
172
|
-
conversation.replaceAll(await compact(conversation.all, compactionOptsFor(endpoint)));
|
|
173
|
-
}
|
|
174
391
|
let response;
|
|
175
392
|
for (;;) {
|
|
393
|
+
// Harness-layer compaction gate — the single choke point every request passes through, on the
|
|
394
|
+
// INITIAL attempt AND after any self-heal failover/route switch below (which `continue`s back
|
|
395
|
+
// here, possibly onto a smaller-context endpoint). Sized to the CURRENT endpoint's window, so no
|
|
396
|
+
// route change can send an over-budget request; and since every surface (CLI, web, mobile/RC,
|
|
397
|
+
// ACP, headless) drives turns through this one runTurn, compaction is guaranteed fleet-wide.
|
|
398
|
+
const cOpts = compactionOptsFor(endpoint);
|
|
399
|
+
if (shouldProactivelyCompact(conversation.all, cOpts)) {
|
|
400
|
+
// Compact (evict + summarize old turns), then GUARANTEE fit: when the bulk is inside the kept recent
|
|
401
|
+
// turns (one turn that dumped huge tool output), fitToWindow elides the largest tool outputs in place
|
|
402
|
+
// so a request is NEVER dispatched over the current endpoint's window. Layer-3 backstop; Layer 1
|
|
403
|
+
// (servedContextLimit, in the catch below) keeps that window itself honest after a learned n_ctx.
|
|
404
|
+
const beforeLen = conversation.all.length;
|
|
405
|
+
conversation.replaceAll(fitToWindow(await compact(conversation.all, cOpts), cOpts));
|
|
406
|
+
// Rehydrate: if compaction actually evicted turns, re-surface the plan + recently-touched files so the
|
|
407
|
+
// model re-reads current state instead of acting on the now-summarized (stale) earlier reads.
|
|
408
|
+
if (conversation.all.length < beforeLen)
|
|
409
|
+
conversation.user(rehydrationNote(touchedFiles));
|
|
410
|
+
}
|
|
411
|
+
// Compaction circuit breaker: after any needed compaction, are we STILL over the window? If compaction
|
|
412
|
+
// ran but can't get the request under budget (the summarizer keeps failing, or the over-budget bulk is
|
|
413
|
+
// un-evictable) for COMPACTION_FAIL_LIMIT rounds running, stop spinning into the same wall — surface it
|
|
414
|
+
// honestly and hand control back rather than burning rounds to the ceiling. Reset the moment a round
|
|
415
|
+
// fits, so a transient squeeze that self-resolves never trips it.
|
|
416
|
+
if (needsCompaction(conversation.all, cOpts)) {
|
|
417
|
+
if (++compactionFailStreak >= COMPACTION_FAIL_LIMIT) {
|
|
418
|
+
const stuck = `[stopped — the context is over this model's window and compaction can't free enough space ` +
|
|
419
|
+
`(${compactionFailStreak} rounds running; the summarizer may be failing). Start a fresh session, or ask me ` +
|
|
420
|
+
`again with a shorter request — nothing was lost.]`;
|
|
421
|
+
conversation.assistant(stuck);
|
|
422
|
+
return { content: stuck, rounds: rounds + 1, toolCalls: toolCallTotal, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal };
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
else {
|
|
426
|
+
compactionFailStreak = 0;
|
|
427
|
+
}
|
|
176
428
|
const messages = buildMessages(opts.systemPrompt, conversation.all);
|
|
177
429
|
// Clamp generation to the room left after the real prompt (incl. tool_calls args + schemas) so a
|
|
178
430
|
// deep-session request never overflows the window into a truncated reply. See clampMaxTokens.
|
|
@@ -186,6 +438,7 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
186
438
|
tools: opts.toolSchemas,
|
|
187
439
|
thinking: opts.thinking,
|
|
188
440
|
signal: opts.signal,
|
|
441
|
+
background: opts.background, // endpoint gate: sub-agents yield the shared slot to the interactive main turn
|
|
189
442
|
onDelta: opts.onDelta,
|
|
190
443
|
onReasoning: opts.onReasoning,
|
|
191
444
|
});
|
|
@@ -193,12 +446,50 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
193
446
|
genMsTotal += response.genMs ?? 0; // accumulate real gen metrics across rounds
|
|
194
447
|
promptTokensTotal += response.promptTokens ?? 0;
|
|
195
448
|
promptMsTotal += response.promptMs ?? 0; // and prefill (the invisible wall-time cost)
|
|
449
|
+
opts.onTokens?.(tokensTotal); // authoritative live count — includes tool-call-arg + reasoning tokens the delta stream misses
|
|
196
450
|
break;
|
|
197
451
|
}
|
|
198
452
|
catch (err) {
|
|
199
453
|
if (isAbort(err, opts.signal))
|
|
200
454
|
throw new TurnAbortedError(); // never self-heal an interrupt
|
|
201
455
|
const recovery = classifyFailure(err);
|
|
456
|
+
// Truncated tool-call JSON (the model's own over-long file write cut off at the token limit): the
|
|
457
|
+
// server can't parse the unterminated arguments (aurora /v1 500). Failing over is futile — the next
|
|
458
|
+
// endpoint truncates the same write — so DON'T burn the failover budget or switch routes. Nudge the
|
|
459
|
+
// model to split the write into smaller calls and retry the SAME endpoint; after a couple of nudges
|
|
460
|
+
// that still truncate, surface it honestly rather than loop. The failed round added nothing to the
|
|
461
|
+
// conversation (chat() threw before streaming), so a bare user-role nudge is safe here (no leak).
|
|
462
|
+
if (recovery === "truncated_tool_call") {
|
|
463
|
+
if (truncRetries >= MAX_TRUNC_RETRIES) {
|
|
464
|
+
// Enterprise-grade: NEVER leave the user frozen re-hitting the same malformed-tool-call 500.
|
|
465
|
+
// Once the nudges are spent, end the turn with a clean, actionable message (not a raw 500 throw)
|
|
466
|
+
// so the user always regains control; the persona now steers multi-line scripts to files, so the
|
|
467
|
+
// next turn doesn't reproduce it. The failed round added nothing to the conversation.
|
|
468
|
+
const msg = "[I hit a repeated tool-call formatting error — an embedded multi-line script " +
|
|
469
|
+
"(python3 -c / bash -c) kept breaking the tool-call JSON. I'll write scripts to a file and run " +
|
|
470
|
+
"the file from here. Send your next message and I'll continue.]";
|
|
471
|
+
conversation.assistant(msg);
|
|
472
|
+
return { content: msg, rounds: rounds + 1, toolCalls: toolCallTotal, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal };
|
|
473
|
+
}
|
|
474
|
+
truncRetries += 1;
|
|
475
|
+
opts.onSelfHeal?.("server_error", truncRetries); // footer ↻ — a recovery is in flight
|
|
476
|
+
conversation.user(truncatedToolNudge(err instanceof Error ? err.message : String(err)));
|
|
477
|
+
continue;
|
|
478
|
+
}
|
|
479
|
+
// Endpoint (re)starting: a 503 whose body says it's loading/warming (seen live 09-26 when a JL2
|
|
480
|
+
// aurora restart to change ctx returned 503 "Loading model"). This WILL become ready, but a model
|
|
481
|
+
// reload is far longer than the self-heal backoff — so WAIT it out on a separate patient budget and
|
|
482
|
+
// retry the SAME endpoint (no failover: it's the one being brought up, and abandoning it loses the
|
|
483
|
+
// very context we're waiting for). The failed round added nothing to the conversation, so retrying
|
|
484
|
+
// is a no-op replay. Only give up after MAX_LOADING_RETRIES so a genuinely dead endpoint still ends.
|
|
485
|
+
if (recovery === "loading") {
|
|
486
|
+
if (loadingRetries >= MAX_LOADING_RETRIES)
|
|
487
|
+
throw err;
|
|
488
|
+
loadingRetries += 1;
|
|
489
|
+
opts.onSelfHeal?.("server_error", loadingRetries); // footer ↻ — waiting for the model to finish loading
|
|
490
|
+
await sleep(opts.loadingBackoffMs ?? DEFAULT_LOADING_BACKOFF_MS, opts.signal, () => new TurnAbortedError());
|
|
491
|
+
continue;
|
|
492
|
+
}
|
|
202
493
|
// Non-retryable: a malformed request (a bad tool call) or bad credentials won't be fixed by
|
|
203
494
|
// resending — fail fast rather than spin (that futile-retry storm is what burned minutes).
|
|
204
495
|
if (recovery === "bad_request" || recovery === "auth" || selfHealBudget <= 0)
|
|
@@ -206,21 +497,37 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
206
497
|
const attempt = MAX_SELF_HEAL_PER_TURN - selfHealBudget; // 0-based
|
|
207
498
|
selfHealBudget -= 1;
|
|
208
499
|
if (recovery === "context") {
|
|
209
|
-
//
|
|
500
|
+
// The SERVER just told us this endpoint's REAL window in the error body (n_ctx). LEARN it and clamp
|
|
501
|
+
// the endpoint to it — the configured window is often optimistic (09-26: JL2 served 64K, configured
|
|
502
|
+
// 256K), which is exactly why proactive compaction never fired before overflowing. Do this FIRST so
|
|
503
|
+
// both the routing choice and the compaction below size to the truth, not the roster's lie.
|
|
504
|
+
const served = servedContextLimit(err);
|
|
505
|
+
if (served !== undefined) {
|
|
506
|
+
opts.router.observeContext?.(endpoint, served); // persist the learned window for the rest of the session
|
|
507
|
+
if (served < endpoint.ctxWindow)
|
|
508
|
+
endpoint = { ...endpoint, ctxWindow: served };
|
|
509
|
+
}
|
|
210
510
|
opts.onSelfHeal?.("context_exceeded", attempt + 1);
|
|
511
|
+
// Prefer a genuinely BIGGER healthy endpoint; ignore a "recovery" that isn't larger (escalate can
|
|
512
|
+
// hand back a same-size endpoint, which would just overflow again).
|
|
211
513
|
const bigger = opts.router.recover(endpoint, "context_exceeded");
|
|
212
|
-
if (bigger) {
|
|
514
|
+
if (bigger && bigger.ctxWindow > endpoint.ctxWindow) {
|
|
213
515
|
endpoint = bigger;
|
|
214
516
|
opts.onRoute?.(endpoint);
|
|
215
517
|
continue;
|
|
216
518
|
}
|
|
217
|
-
//
|
|
218
|
-
//
|
|
219
|
-
//
|
|
220
|
-
const
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
519
|
+
// No larger endpoint: make THIS one fit. Evict old turns, then elide oversized tool outputs in the
|
|
520
|
+
// KEPT turns (fitToWindow) — this recovers the "12-min trace dump in the last turn" case that
|
|
521
|
+
// eviction alone can't shed. Give up only if we genuinely couldn't shrink the request at all.
|
|
522
|
+
const before = conversation.all;
|
|
523
|
+
const cOpts = compactionOptsFor(endpoint);
|
|
524
|
+
const shrunk = fitToWindow(await compact(before, cOpts), cOpts);
|
|
525
|
+
conversation.replaceAll(shrunk);
|
|
526
|
+
const chars = (ms) => ms.reduce((n, m) => n + m.content.length, 0);
|
|
527
|
+
if (chars(shrunk) >= chars(before))
|
|
528
|
+
throw err; // nothing left to shed — surface honestly rather than spin
|
|
529
|
+
if (shrunk.length < before.length)
|
|
530
|
+
conversation.user(rehydrationNote(touchedFiles)); // rehydrate after a forced compaction
|
|
224
531
|
continue;
|
|
225
532
|
}
|
|
226
533
|
// transient (429 / 5xx / network drop): a busy or unhealthy backend, NOT a context problem.
|
|
@@ -236,37 +543,109 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
236
543
|
continue;
|
|
237
544
|
}
|
|
238
545
|
}
|
|
239
|
-
//
|
|
240
|
-
//
|
|
241
|
-
//
|
|
242
|
-
//
|
|
243
|
-
//
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
546
|
+
// Round-loop guard: a true loop repeats the SAME STEP — identical narration AND identical intended
|
|
547
|
+
// actions (tool name+args), or identical narration with no action at all. The signature is the WHOLE
|
|
548
|
+
// round (prose + the calls it drives), NOT the prose alone: a model doing DIFFERENT work each round
|
|
549
|
+
// (writing mod1, mod2, mod3 — different tool args) while narrating with the same boilerplate ("writing
|
|
550
|
+
// the next module") is PRODUCTIVE, so its rounds get distinct signatures and never accumulate. Keying
|
|
551
|
+
// on prose alone cut exactly that productive-but-repetitive case off at round 3 (a small local model
|
|
552
|
+
// narrates repetitively by nature) — caught by a real-world drive. Only when the whole round repeats
|
|
553
|
+
// CONTENT_LOOP_LIMIT× do we stop; the no-progress STALL streak below is the separate, progress-gated
|
|
554
|
+
// backstop. Gate on RAW length so non-Latin narration still qualifies.
|
|
555
|
+
if (response.content.trim().length >= 40) {
|
|
248
556
|
const csig = contentSignature(response.content);
|
|
249
557
|
if (csig) {
|
|
250
|
-
const
|
|
251
|
-
|
|
558
|
+
const actions = response.toolCalls.map((c) => `${c.function?.name ?? ""}:${c.function?.arguments ?? ""}`).sort().join("|");
|
|
559
|
+
const rsig = `${csig}\u0000${actions}`; // prose + the actions it drives — the whole round
|
|
560
|
+
const seen = (contentSigs.get(rsig) ?? 0) + 1;
|
|
561
|
+
contentSigs.set(rsig, seen);
|
|
252
562
|
if (seen >= CONTENT_LOOP_LIMIT) {
|
|
253
563
|
const gist = response.content.trim().split("\n", 1)[0].slice(0, 200);
|
|
254
|
-
|
|
255
|
-
|
|
564
|
+
if (seen < CONTENT_LOOP_REDIRECT) {
|
|
565
|
+
// Early, light nudge: the whole round repeated (same prose + same call) with no new result. A hard
|
|
566
|
+
// stop here would break autonomy right when the model usually already knows how to pivot (live
|
|
567
|
+
// 09-27). NUDGE it to try something different and CONTINUE; keep counting so a model that ignores
|
|
568
|
+
// the nudge escalates. A bare user-role nudge is safe here (no leak).
|
|
569
|
+
opts.onSelfHeal?.("server_error", seen - CONTENT_LOOP_LIMIT + 1); // footer ↻ — breaking a stall
|
|
570
|
+
conversation.user(`You've repeated the same step ${seen}× with the same result — that approach is not working. Do NOT ` +
|
|
571
|
+
`end the turn or ask me how to proceed. STOP repeating it and try a genuinely DIFFERENT approach: a ` +
|
|
572
|
+
`different command, tool, path, or angle; if a tool seems broken, work around it. If you already ` +
|
|
573
|
+
`know the fix (you often do — you just described one), do it now.`);
|
|
574
|
+
continue;
|
|
575
|
+
}
|
|
576
|
+
if (forcedRedirects < CONTENT_LOOP_REDIRECT_MAX) {
|
|
577
|
+
// ENTERPRISE LOOP-RECOVERY (forced redirect): the light nudge didn't break the loop. Instead of
|
|
578
|
+
// STOPPING the turn (which ends an autonomous session), FORCE the model to step back — diagnose
|
|
579
|
+
// what it keeps doing and why it isn't working, then decompose the step or switch approach — and
|
|
580
|
+
// give it a FRESH runway (reset this round-signature's count) so it can continue. Only after
|
|
581
|
+
// CONTENT_LOOP_REDIRECT_MAX of these fail does the turn finally hand back, so a long autonomous run
|
|
582
|
+
// self-corrects several times before giving up. This is what keeps sessions running instead of
|
|
583
|
+
// dying on the first hard loop.
|
|
584
|
+
forcedRedirects += 1;
|
|
585
|
+
contentSigs.set(rsig, 0); // fresh runway for this signature after the forced redirect
|
|
586
|
+
opts.onSelfHeal?.("server_error", forcedRedirects); // footer ↻ — a forced self-correction
|
|
587
|
+
conversation.user(`You have repeated the SAME step ${seen}× and it is STILL not working — repeating it again will not ` +
|
|
588
|
+
`help. Stop and do this explicitly, in order:\n` +
|
|
589
|
+
`1. In ONE line, state exactly WHAT you keep doing and WHY it isn't making progress (what you ` +
|
|
590
|
+
`expected vs what actually happened).\n` +
|
|
591
|
+
`2. Then pick ONE and do it immediately:\n` +
|
|
592
|
+
` (a) BREAK IT DOWN — split the stuck step into a smaller, concrete sub-action and do just that ` +
|
|
593
|
+
`one thing now; or\n` +
|
|
594
|
+
` (b) SWITCH APPROACH — a genuinely different tool, command, path, or order of operations; if a ` +
|
|
595
|
+
`tool or command seems broken, work around it.\n` +
|
|
596
|
+
`Do NOT reproduce your previous output, do NOT end the turn, and do NOT ask me how to proceed — ` +
|
|
597
|
+
`decide and act on the smallest next concrete step.`);
|
|
598
|
+
continue;
|
|
599
|
+
}
|
|
600
|
+
// Exhausted the forced redirects on a still-unbroken loop — genuinely intractable. Hand back cleanly
|
|
601
|
+
// (never freeze). The other guards (no-progress stall, round ceiling) also backstop this.
|
|
602
|
+
const stuck = `[stopped — I repeated the same step ${seen}× and self-correction (${forcedRedirects} ` +
|
|
603
|
+
`forced redirects) didn't break it, which usually means a tool isn't doing what I expect. Where I'm ` +
|
|
604
|
+
`stuck: ${gist}\nTell me how you'd like to proceed.]`;
|
|
256
605
|
conversation.assistant(stuck);
|
|
257
606
|
return { content: stuck, rounds: rounds + 1, toolCalls: toolCallTotal, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal };
|
|
258
607
|
}
|
|
259
608
|
}
|
|
260
609
|
}
|
|
610
|
+
// Stuck-turn guard (SELF_LOOP_* above): the model's own admission it's looping is the one signal the
|
|
611
|
+
// signature guards miss. Only counts when the model wants to keep ACTING (has tool calls) and is NOT
|
|
612
|
+
// fixing (no file edit this round) — so a final answer that merely mentions "a different approach", and a
|
|
613
|
+
// round that admits-and-fixes, both pass through untouched. A file edit clears the streak (broke out).
|
|
614
|
+
{
|
|
615
|
+
const mutatingThisRound = response.toolCalls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? ""));
|
|
616
|
+
if (response.toolCalls.length > 0 && !mutatingThisRound && SELF_LOOP_RE.test(response.content)) {
|
|
617
|
+
selfLoopStreak += 1;
|
|
618
|
+
if (selfLoopStreak >= SELF_LOOP_STOP) {
|
|
619
|
+
const gist = response.content.trim().split("\n").find((l) => l.trim())?.slice(0, 200) ?? "";
|
|
620
|
+
const stuck = `[stopped — I said I was going in circles ${selfLoopStreak}× without making a change that broke ` +
|
|
621
|
+
`the loop, so I'm handing back rather than burning more time. Where I am: ${gist}\nTell me how you'd like ` +
|
|
622
|
+
`to proceed — a different angle, or I can apply the fix I've been circling if you confirm it.]`;
|
|
623
|
+
conversation.assistant(stuck);
|
|
624
|
+
return { content: stuck, rounds: rounds + 1, toolCalls: toolCallTotal, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal };
|
|
625
|
+
}
|
|
626
|
+
opts.onSelfHeal?.("server_error", selfLoopStreak); // footer ↻ — breaking a self-declared loop
|
|
627
|
+
conversation.user(`You just said you're stuck or looping — that is the moment to CHANGE something concrete, not run the ` +
|
|
628
|
+
`same investigation again. If you understand the root cause, apply the fix NOW with file_edit/file_write ` +
|
|
629
|
+
`and verify it. If a tool, path, or approach isn't working, switch to a genuinely different one. If you ` +
|
|
630
|
+
`are truly blocked, STOP and tell me exactly what is blocking you and what you would try next.`);
|
|
631
|
+
continue; // let the model act on the nudge; don't dispatch this round's repeated calls
|
|
632
|
+
}
|
|
633
|
+
selfLoopStreak = 0; // a round that fixes, doesn't act, or doesn't admit looping clears the streak
|
|
634
|
+
}
|
|
261
635
|
if (response.toolCalls.length > 0) {
|
|
262
636
|
throwIfAborted(opts.signal); // don't dispatch a tool batch for a turn the user already cancelled
|
|
263
637
|
conversation.assistant(response.content, response.toolCalls);
|
|
264
|
-
|
|
638
|
+
// Race the batch against the abort signal so esc breaks even a hung tool (a frozen child process) —
|
|
639
|
+
// the abandoned tool runs to its own timeout, but the turn is never wedged.
|
|
640
|
+
const toolMsgs = await abortable(runToolCalls(response.toolCalls, opts.tools, callCounts, opts.onToolBatch, opts.onToolStart, opts.onToolResult), opts.signal);
|
|
265
641
|
for (const tm of toolMsgs)
|
|
266
642
|
conversation.tool(tm.tool_call_id, tm.content);
|
|
643
|
+
observeVerify(verify, response.toolCalls, toolMsgs); // verify-before-done: record mutation / verify signal
|
|
267
644
|
toolCallTotal += response.toolCalls.length;
|
|
268
645
|
progressed = batchProgressed(toolMsgs);
|
|
269
646
|
noProgressStreak = progressed ? 0 : noProgressStreak + 1; // reset the stall counter on any real progress
|
|
647
|
+
noEditStreak = response.toolCalls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? "")) ? 0 : noEditStreak + 1;
|
|
648
|
+
trackTouchedFiles(response.toolCalls, touchedFiles);
|
|
270
649
|
continue;
|
|
271
650
|
}
|
|
272
651
|
// No structured tool_calls — check for text-encoded ones before treating this as final.
|
|
@@ -274,12 +653,15 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
274
653
|
if (recovered.calls.length > 0) {
|
|
275
654
|
throwIfAborted(opts.signal);
|
|
276
655
|
conversation.assistant(recovered.cleanedContent, recovered.calls);
|
|
277
|
-
const toolMsgs = await runToolCalls(recovered.calls, opts.tools, callCounts, opts.onToolBatch, opts.onToolStart, opts.onToolResult);
|
|
656
|
+
const toolMsgs = await abortable(runToolCalls(recovered.calls, opts.tools, callCounts, opts.onToolBatch, opts.onToolStart, opts.onToolResult), opts.signal);
|
|
278
657
|
for (const tm of toolMsgs)
|
|
279
658
|
conversation.tool(tm.tool_call_id, tm.content);
|
|
659
|
+
observeVerify(verify, recovered.calls, toolMsgs); // verify-before-done: record mutation / verify signal
|
|
280
660
|
toolCallTotal += recovered.calls.length;
|
|
281
661
|
progressed = batchProgressed(toolMsgs);
|
|
282
662
|
noProgressStreak = progressed ? 0 : noProgressStreak + 1; // reset the stall counter on any real progress
|
|
663
|
+
noEditStreak = recovered.calls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? "")) ? 0 : noEditStreak + 1;
|
|
664
|
+
trackTouchedFiles(recovered.calls, touchedFiles);
|
|
283
665
|
continue;
|
|
284
666
|
}
|
|
285
667
|
const final = stripScratchpad(recovered.cleanedContent);
|
|
@@ -305,12 +687,26 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
305
687
|
continue;
|
|
306
688
|
}
|
|
307
689
|
}
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
690
|
+
// Verify-before-done gate: the model is finalizing (no more tool calls). If this turn CHANGED files
|
|
691
|
+
// but no passing check was observed, inject ONE reminder to run it and give the model another round.
|
|
692
|
+
// Record `final` as the model's own done-claim first, then a user-role reminder — the "user-role leak"
|
|
693
|
+
// warning above applies only to an EMPTY round; here real content + tool results exist, so the reminder
|
|
694
|
+
// is answered as the intended verify step, not mistaken for the request. Capped (verifyMaxNudges) →
|
|
695
|
+
// ≤1 extra round, the main-loop mirror of grandmaster's single repair round.
|
|
696
|
+
if (verifyEnabled && final && verify.gate() && verifyNudges < verifyMaxNudges) {
|
|
697
|
+
verifyNudges++;
|
|
698
|
+
conversation.assistant(final);
|
|
699
|
+
conversation.user(VERIFY_REMINDER);
|
|
700
|
+
continue;
|
|
701
|
+
}
|
|
702
|
+
const unverified = verifyEnabled && verify.gate(); // changed files, still no passing check after the nudge
|
|
703
|
+
const answer = (unverified ? NOT_VERIFIED_BANNER : "") +
|
|
704
|
+
(final || stripScratchpad(response.reasoningContent ?? "") ||
|
|
705
|
+
(response.stopReason === "length"
|
|
706
|
+
? "(hit the output limit before an answer landed — ask me to continue and I'll pick up where I left off.)"
|
|
707
|
+
: "(the model returned an empty response — try rephrasing.)"));
|
|
312
708
|
conversation.assistant(answer);
|
|
313
|
-
return { content: answer, rounds: rounds + 1, toolCalls: toolCallTotal, stopReason: response.stopReason, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal };
|
|
709
|
+
return { content: answer, rounds: rounds + 1, toolCalls: toolCallTotal, stopReason: response.stopReason, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal, unverified: unverified || undefined };
|
|
314
710
|
}
|
|
315
711
|
const timeoutMsg = `[stopped after ${rounds} tool rounds — the task may be unfinished; ask me to continue and I'll pick up where I left off]`;
|
|
316
712
|
conversation.assistant(timeoutMsg);
|