@0perator/operator 0.1.285 → 0.1.313

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.
Files changed (98) hide show
  1. package/README.md +24 -2
  2. package/dist/acp/agent.js +2 -1
  3. package/dist/acp/config-options.js +3 -1
  4. package/dist/acp/tool-map.js +2 -1
  5. package/dist/auth/commands.js +69 -13
  6. package/dist/autonomy/agent-cli.js +304 -0
  7. package/dist/autonomy/cloud-agent.js +439 -0
  8. package/dist/autonomy/cron-lifecycle.js +78 -0
  9. package/dist/autonomy/cron-lock.js +121 -0
  10. package/dist/autonomy/cron.js +216 -43
  11. package/dist/autonomy/delegate.js +5 -1
  12. package/dist/autonomy/incidents.js +135 -0
  13. package/dist/autonomy/session-factory.js +25 -16
  14. package/dist/background/index.js +40 -0
  15. package/dist/bus/inbox.js +20 -0
  16. package/dist/classifier/config.js +47 -0
  17. package/dist/classifier/modes.js +41 -0
  18. package/dist/classifier/types.js +1 -0
  19. package/dist/cli.js +529 -53
  20. package/dist/config/features.js +69 -0
  21. package/dist/config/persona.js +118 -99
  22. package/dist/config/scaffold.js +15 -0
  23. package/dist/config/settings.js +96 -6
  24. package/dist/consolidation/sleep.js +73 -11
  25. package/dist/engine/agent.js +275 -18
  26. package/dist/engine/anthropic-chat.js +343 -0
  27. package/dist/engine/aurora.js +101 -13
  28. package/dist/engine/batch-scheduler.js +41 -9
  29. package/dist/engine/classifier.js +85 -0
  30. package/dist/engine/compaction.js +24 -5
  31. package/dist/engine/fast-start.js +25 -0
  32. package/dist/engine/loop-guard.js +448 -0
  33. package/dist/engine/net-error.js +24 -0
  34. package/dist/engine/repetition-guard.js +180 -0
  35. package/dist/engine/selfheal.js +8 -0
  36. package/dist/engine/toolcalls.js +51 -1
  37. package/dist/engine/verify-gate.js +2 -0
  38. package/dist/flywheel/processor.js +78 -31
  39. package/dist/flywheel/srft.js +13 -0
  40. package/dist/hooks/index.js +196 -0
  41. package/dist/mcp/config.js +21 -1
  42. package/dist/memory/index.js +0 -0
  43. package/dist/memory/providers.js +210 -0
  44. package/dist/memory/session-catalog.js +422 -0
  45. package/dist/memory/session-providers.js +121 -0
  46. package/dist/memory/session-sources.js +335 -0
  47. package/dist/memory/skylark.js +131 -0
  48. package/dist/models/bench.js +103 -0
  49. package/dist/models/registry.js +144 -0
  50. package/dist/models/switch.js +69 -0
  51. package/dist/observability/blackbox.js +37 -0
  52. package/dist/permissions/policy.js +31 -6
  53. package/dist/router/discovery.js +127 -0
  54. package/dist/router/models.js +107 -16
  55. package/dist/router/portal.js +100 -0
  56. package/dist/router/router.js +1 -1
  57. package/dist/services/preflight.js +55 -7
  58. package/dist/session.js +316 -46
  59. package/dist/tools/chauffeur.js +12 -0
  60. package/dist/tools/executor.js +19 -9
  61. package/dist/tools/find-files.js +483 -0
  62. package/dist/tools/git-pr.js +94 -0
  63. package/dist/tools/incident-tools.js +82 -0
  64. package/dist/tools/memory.js +12 -2
  65. package/dist/tools/registry.js +281 -85
  66. package/dist/tools/semantic-compress.js +124 -0
  67. package/dist/tools/shell-context.js +1 -0
  68. package/dist/tools/shell-jobs.js +160 -0
  69. package/dist/tools/shell-session.js +170 -4
  70. package/dist/tools/wave-tools.js +609 -0
  71. package/dist/tools/wave2-tools.js +411 -0
  72. package/dist/ui/App.js +15 -4
  73. package/dist/ui/BgPanel.js +30 -6
  74. package/dist/ui/Composer.js +11 -1
  75. package/dist/ui/QuestionPrompt.js +31 -11
  76. package/dist/ui/SessionPicker.js +86 -0
  77. package/dist/ui/StatusRule.js +5 -5
  78. package/dist/ui/ToolStep.js +2 -1
  79. package/dist/ui/Transcript.js +17 -1
  80. package/dist/ui/index.js +1 -1
  81. package/dist/ui/liveTools.js +21 -3
  82. package/dist/ui/slashCommands.js +2 -0
  83. package/dist/util/screenshots.js +74 -8
  84. package/dist/util/slash.js +2 -2
  85. package/package.json +8 -2
  86. package/dist/engine/cli.js +0 -1171
  87. package/dist/router/models.js.bak +0 -78
  88. package/dist/router/models.js.bak-1791259923 +0 -78
  89. package/dist/router/models.js.bak-pre-gateway +0 -78
  90. package/dist/router/models.js.bak-pre-patch2 +0 -78
  91. package/dist/router/models.js.bak2 +0 -78
  92. package/dist/services/model-autodetect.js +0 -240
  93. package/dist/tools/native-redirect.js +0 -140
  94. package/dist/tools/power-tools.js +0 -627
  95. package/dist/tools/registry.js.bak-1791259948 +0 -1914
  96. package/dist/tools/registry.js.bak-pre-plugins +0 -1914
  97. package/dist/ui/BusTray.js +0 -70
  98. package/dist/ui/resize.js +0 -160
@@ -5,13 +5,15 @@
5
5
  import { chat } from "./aurora.js";
6
6
  import { parseToolArgs } from "./json-repair.js";
7
7
  import { buildMessages } from "./messages.js";
8
- import { recoverToolCalls } from "./toolcalls.js";
9
- import { compact, needsCompaction, shouldProactivelyCompact, fitToWindow, clampMaxTokens } from "./compaction.js";
8
+ import { recoverToolCalls, cleanAssistantProse } from "./toolcalls.js";
9
+ import { compact, needsCompaction, shouldProactivelyCompact, fitToWindow, clampMaxTokens, outputRoom, headroomTargetRatio, TOOL_CALL_HEADROOM_TOKENS } from "./compaction.js";
10
10
  import { globalTokenMeter, endpointKey, requestChars } from "./token-meter.js";
11
11
  import { classifyFailure, servedContextLimit, backoffMs, sleep } from "./selfheal.js";
12
12
  import { TaskVerification, VERIFY_REMINDER, NOT_VERIFIED_BANNER } from "./verify-gate.js";
13
13
  import { detectRefusal, buildAffirmativeRetry, UNRESTRICTED_MAX_RETRIES } from "./unrestricted.js";
14
14
  import { ComputerEventStream, ComputerEventTracker } from "./computer-event.js";
15
+ import { LoopGuard, PollSpinGuard, NoWriteProgressGuard, loopStopNote, resolveLoopGuardConfig } from "./loop-guard.js";
16
+ import { RunawayStreamWatch, ReasoningBudgetWatch, isDegenerateReply, REPETITION_INTERRUPTED, REASONING_BUDGET_INTERRUPTED } from "./repetition-guard.js";
15
17
  const MAX_SELF_HEAL_PER_TURN = 3;
16
18
  // A "loading" 503 (endpoint restarting/warming) is a KNOWN-recoverable WAIT, not a failure — a model reload
17
19
  // is ~30-90s, far longer than the ≤8s exponential self-heal backoff, so it gets its own patient budget that
@@ -28,6 +30,14 @@ import { ANNOUNCE_NUDGE, ANNOUNCE_NUDGE_MAX, detectUnfinishedAction } from "./co
28
30
  // Poll/status tools are meant to be called repeatedly while waiting on async work — NEVER a spin, so the
29
31
  // loop guard skips them entirely (agent_status polls sub-agents, bash_output polls a background job).
30
32
  const LOOP_GUARD_EXEMPT = new Set(["agent_status", "bash_output"]);
33
+ // Status/introspection tools return the SAME facts for the whole turn and are never progress when repeated.
34
+ // A weak model can fixate on one and poll it instead of answering — seen live on belmont-30b calling
35
+ // self_status 5–9× every turn until a human interrupted, because LOOP_GUARD_LIMIT only short-circuits and the
36
+ // hard stop sits at 10. Cap them tight and interactive-safe: the 2nd identical call is refused, a 3rd ends the
37
+ // turn and hands back. No intervening-edit reset — a status fact does not change because a file was written.
38
+ const STATUS_TOOLS = new Set(["self_status"]);
39
+ const STATUS_TOOL_REFUSE = 2; // identical calls before the status tool is refused for the rest of the turn
40
+ const STATUS_TOOL_HARD = 3; // …before the turn ends and hands back to the user
31
41
  // Hard backstop: after this many identical (name+args) calls in a turn with NO intervening edit, the model is
32
42
  // spinning on a poisoned call and ignoring every short-circuit warning — abort the turn cleanly instead of
33
43
  // burning rounds to maxRoundsHard. An Aurora blip once drove the same blocked bash call 16× before the turn
@@ -70,7 +80,13 @@ const CONTENT_LOOP_REDIRECT = 6; // …and at this many, escalate to a FORCED RE
70
80
  // model self-corrects instead of the turn stopping). Only after CONTENT_LOOP_REDIRECT_MAX forced redirects on a
71
81
  // still-unbroken loop does the turn finally hand back — so an autonomous session self-corrects for ~3× longer.
72
82
  const CONTENT_LOOP_REDIRECT_MAX = 3;
73
- const MAX_EMPTY_RETRIES = 1; // one nudge on an empty "dud" round before finalizing
83
+ const MAX_EMPTY_RETRIES = 2; // retries on an empty "dud" round before finalizing; each retry escalates sampling
84
+ // Temperature ESCALATION for the empty-retry ONLY. The operator decodes greedily (temperature 0) for
85
+ // determinism, so a completion that comes back empty is a deterministic argmax-EOS for that exact prompt —
86
+ // re-requesting it bit-identically reproduces the same empty forever, and the turn must never hand that
87
+ // dead-end back to the owner. On each successive empty we raise the temperature so EOS-first gets progressively
88
+ // less probable and real content emerges (retry 1 → 0.7, retry 2 → 1.0); the normal path keeps temperature 0.
89
+ const emptyRetryTemp = (n) => Math.min(0.7 + 0.3 * (n - 1), 1.0);
74
90
  const NO_PROGRESS_LIMIT = 8; // consecutive tool batches that return NOTHING new (past the soft budget) ⇒ genuine stall.
75
91
  // Raised 6→8: a long, genuinely-progressing task can go momentarily quiet (a planning/reasoning round, a couple
76
92
  // of empty greps) without being stalled — 8 empty-in-a-row is an unambiguous stall, still far below absCeiling.
@@ -205,7 +221,7 @@ export function capToolRound(msgs) {
205
221
  * no-progress limit. `write`/`edit` return "wrote …"/"edited …", so those were never the problem. */
206
222
  function batchProgressed(toolMsgs) {
207
223
  return toolMsgs.some((tm) => {
208
- const c = (tm.content || "").trim();
224
+ const c = (tm.content || "").replace(/\[note: [^\]]*\]/g, "").trim(); // the loop guard's own notes are not new information
209
225
  return c.length > 0 && !/^\(no output; exit|^error[:\s]|^loop guard/i.test(c);
210
226
  });
211
227
  }
@@ -281,14 +297,14 @@ function parseArgs(raw) {
281
297
  // truncation-vs-malformed is classified so the error the model sees is ACTIONABLE (the generic
282
298
  // "Unterminated string" reply sent a live review session on a 69-tool-call hallucination spiral).
283
299
  const r = parseToolArgs(raw);
284
- return r.ok ? { ok: true, args: r.args } : { ok: false, error: r.error };
300
+ return r.ok ? { ok: true, args: r.args } : { ok: false, error: r.error, truncated: r.truncated === true };
285
301
  }
286
302
  /**
287
303
  * Runs tool_calls (structured or text-recovered) through the executor, honoring the loop
288
304
  * guard (SPEC §2: identical (name,args) ≥3× this turn is short-circuited) and reporting the
289
305
  * batch via onToolBatch with a real (unrounded) duration.
290
306
  */
291
- async function runToolCalls(toolCalls, tools, callCounts, rca, onToolBatch, onToolStart, onToolResult, signal) {
307
+ async function runToolCalls(toolCalls, tools, callCounts, rca, onToolBatch, onToolStart, onToolResult, signal, guard, onBadArgs) {
292
308
  // One id for this whole round (SPEC parallel-tool-batch) — every call made here, however it
293
309
  // resolves (executed, parse error, loop-guarded), shares it, so a host can box "N tools in
294
310
  // parallel" together even for the calls that never reached the executor. Same id-shape idiom as
@@ -300,14 +316,24 @@ async function runToolCalls(toolCalls, tools, callCounts, rca, onToolBatch, onTo
300
316
  const preResolved = new Map(); // id -> result, for parse errors + loop-guarded calls
301
317
  const parsedArgs = new Map();
302
318
  let loopAbort; // set when a signature blows past LOOP_GUARD_HARD — the turn is aborted (below)
319
+ const guardSkip = new Set(); // calls that never reached the executor for a reason the result guard must not count (parse error, refused cap, re-worded repeat)
320
+ const guardReplay = new Set(); // calls the identical-args counter refused: one more repeat for the result guard, nothing else
303
321
  toolCalls.forEach((tc, batchIndex) => {
304
322
  const parsed = parseArgs(tc.function.arguments);
305
323
  if (!parsed.ok) {
324
+ onBadArgs?.(tc, parsed.truncated);
306
325
  preResolved.set(tc.id, `Error: could not parse arguments for tool "${tc.function.name}": ${parsed.error}`);
307
326
  parsedArgs.set(tc.id, {});
327
+ guardSkip.add(tc.id);
308
328
  return;
309
329
  }
310
330
  parsedArgs.set(tc.id, parsed.args);
331
+ const capped = guard?.beforeCall(tc.function.name, parsed.args);
332
+ if (capped?.action === "halt") { // per-turn cap or a replay the result guard already knows is futile: refuse, the turn ends after this batch
333
+ preResolved.set(tc.id, `Blocked ${tc.function.name}: ${capped.message}. Work with what you already have and give the user your answer.`);
334
+ guardSkip.add(tc.id);
335
+ return;
336
+ }
311
337
  // Poll/status tools (agent_status, bash_output) are DESIGNED to be called repeatedly with identical
312
338
  // args while waiting on async work — that's not a spin, so they are never loop-guarded. Live 09-27:
313
339
  // agent_status polled while sub-agents ran tripped the guard at 5 (and kept firing) even though the
@@ -319,6 +345,19 @@ async function runToolCalls(toolCalls, tools, callCounts, rca, onToolBatch, onTo
319
345
  const sig = callSignature(tc.function.name, parsed.args);
320
346
  const count = (callCounts.get(sig) ?? 0) + 1;
321
347
  callCounts.set(sig, count);
348
+ if (STATUS_TOOLS.has(tc.function.name) && count >= STATUS_TOOL_REFUSE) {
349
+ // A status tool returns the same facts all turn; a repeat is a poll, never progress. Refuse it and, once
350
+ // the model has ignored that, end the turn so it stops polling and hands back instead of spinning to 10.
351
+ if (count >= STATUS_TOOL_HARD) {
352
+ loopAbort = `"${tc.function.name}" is a read-only status tool that returns the same facts all turn; it ` +
353
+ `was called ${count}× — the turn was ended so you stop polling it. Answer the user from the status ` +
354
+ `already returned, or ask them what you should do next.`;
355
+ }
356
+ preResolved.set(tc.id, `Loop guard: "${tc.function.name}" already returned your status this turn and it has not changed. Do ` +
357
+ `NOT call it again — answer the user, or ask them what you should do next.`);
358
+ guardReplay.add(tc.id);
359
+ return;
360
+ }
322
361
  if (count >= LOOP_GUARD_LIMIT) { // SPEC §2: short-circuit the Nth identical call (matches executor's guard)
323
362
  if (count >= LOOP_GUARD_HARD) {
324
363
  // The model ignored LOOP_GUARD_HARD short-circuit warnings for this exact call with no intervening edit —
@@ -329,6 +368,7 @@ async function runToolCalls(toolCalls, tools, callCounts, rca, onToolBatch, onTo
329
368
  }
330
369
  preResolved.set(tc.id, `Loop guard: "${tc.function.name}" has been called ${count} times this turn with identical ` +
331
370
  `arguments. Try a different approach instead of repeating this call.`);
371
+ guardReplay.add(tc.id);
332
372
  return;
333
373
  }
334
374
  // RCA gate (see RCA_STOP above): division of labour with the guard above — EXACT repeats are LOOP_GUARD's
@@ -344,6 +384,7 @@ async function runToolCalls(toolCalls, tools, callCounts, rca, onToolBatch, onTo
344
384
  loopAbort = `stuck — repeated completed action: "${tc.function.name}" already COMPLETED this turn (spelled ${arm.size} way(s)) and a merely re-worded variant was re-issued ${refused}× despite the short-circuit. The action is DONE — its result is already in the history above.`;
345
385
  }
346
386
  preResolved.set(tc.id, `Repeated action: "${tc.function.name}" with these arguments already COMPLETED successfully this turn (re-wording it does not make it new work). Re-running cannot produce anything new. Finalize your answer from the existing result, or take a materially DIFFERENT action.`);
387
+ guardSkip.add(tc.id);
347
388
  return;
348
389
  }
349
390
  pending.push({ id: tc.id, name: tc.function.name, args: parsed.args, batchId, batchSize, batchIndex });
@@ -389,6 +430,17 @@ async function runToolCalls(toolCalls, tools, callCounts, rca, onToolBatch, onTo
389
430
  seen.add(callSignature(p.name, p.args));
390
431
  }
391
432
  });
433
+ // Result guard (engine/loop-guard.ts): feed the settled calls in batch order. It appends a short plain note
434
+ // to a result that repeats itself, swaps a byte-identical large duplicate for a reference stub, and records a
435
+ // halt the caller acts on after the batch. Raw results above stay untouched for the progress ledgers.
436
+ if (guard)
437
+ for (const tc of toolCalls) {
438
+ const args = parsedArgs.get(tc.id);
439
+ const raw = resultById.get(tc.id);
440
+ if (!args || raw === undefined || guardSkip.has(tc.id))
441
+ continue;
442
+ resultById.set(tc.id, guard.afterCall(tc.function.name, args, raw, { id: tc.id, shortCircuited: guardReplay.has(tc.id) }).result);
443
+ }
392
444
  if (onToolBatch) {
393
445
  const events = toolCalls.map((tc, batchIndex) => ({
394
446
  name: tc.function.name,
@@ -435,12 +487,59 @@ export function rehydrationNote(touched) {
435
487
  "re-read it fresh with file_read — do NOT trust a summarized earlier read";
436
488
  return touched.length ? `${base}. Files you were working on (re-read before relying on them): ${touched.join(", ")}.]` : `${base}.]`;
437
489
  }
490
+ /** Streaming half of the repetition guard: wraps the delta callbacks and the abort signal handed to chat() so a
491
+ * reply that has become a runaway loop is torn down mid-stream (the transport closes the fetch) instead of
492
+ * streaming until the output cap. A host abort still aborts. `tripped` tells the caller which one it was. */
493
+ function watchRepetition(opts, on) {
494
+ if (!on)
495
+ return { signal: opts.signal, onDelta: opts.onDelta, onReasoning: opts.onReasoning, tripped: false, dispose: () => { } };
496
+ const ctl = new AbortController();
497
+ const link = () => ctl.abort();
498
+ if (opts.signal?.aborted)
499
+ ctl.abort();
500
+ else
501
+ opts.signal?.addEventListener("abort", link, { once: true });
502
+ const text = new RunawayStreamWatch();
503
+ const thought = new RunawayStreamWatch(); // reasoning that REPEATS a fragment
504
+ const thoughtBudget = new ReasoningBudgetWatch(); // reasoning that goes LONG without acting ("in circles")
505
+ const w = {
506
+ signal: ctl.signal,
507
+ tripped: false,
508
+ onDelta: (c) => { opts.onDelta?.(c); if (!w.tripped && text.feed(c)) {
509
+ w.tripped = true;
510
+ w.tripReason = "repetition";
511
+ ctl.abort();
512
+ } },
513
+ onReasoning: (c) => {
514
+ opts.onReasoning?.(c);
515
+ if (w.tripped)
516
+ return;
517
+ if (thought.feed(c)) {
518
+ w.tripped = true;
519
+ w.tripReason = "repetition";
520
+ ctl.abort();
521
+ return;
522
+ }
523
+ if (thoughtBudget.feed(c)) {
524
+ w.tripped = true;
525
+ w.tripReason = "budget";
526
+ ctl.abort();
527
+ }
528
+ },
529
+ dispose: () => opts.signal?.removeEventListener("abort", link),
530
+ };
531
+ return w;
532
+ }
438
533
  /** Runs one user turn to completion: compacts, loops model↔tools ≤maxRounds, self-heals, finalizes. */
439
534
  export async function runTurn(userInput, conversation, opts) {
440
535
  const softRounds = opts.maxRounds ?? 10;
441
536
  const absCeiling = Math.max(softRounds + 1, opts.maxRoundsHard ?? 400); // absolute safety stop; progress-aware below
442
537
  const turnStart = Date.now(); // for the per-turn wall-clock budget (opts.maxTurnWallClockMs) — the only bound on TIME
443
538
  const callCounts = new Map();
539
+ const guardCfg = resolveLoopGuardConfig(opts.loopGuard, { unattended: opts.unattended === true });
540
+ const guard = guardCfg.enabled ? new LoopGuard(guardCfg) : undefined; // result-aware tool loop guard (engine/loop-guard.ts)
541
+ const pollSpin = guardCfg.enabled ? new PollSpinGuard() : undefined; // auto-post-poller (agent_status) spin guard — a separate detector, since pollers are EXEMPT from `guard`
542
+ const noWriteProgress = guardCfg.enabled ? new NoWriteProgressGuard(guardCfg.warnInvestigateLoop, guardCfg.stopInvestigateLoop, guardCfg.hardStop) : undefined; // investigate-loop detector — catches rounds with zero mutating calls
444
543
  const rca = { succeeded: new Map(), refused: new Map() }; // normalized-fingerprint → completed exact spellings; + refusal tally (see RCA_STOP)
445
544
  const contentSigs = new Map(); // per-round prose fingerprints → the narration loop guard
446
545
  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)
@@ -483,9 +582,13 @@ export async function runTurn(userInput, conversation, opts) {
483
582
  const continuationEnabled = opts.turnContinuation?.enabled !== false && (opts.toolSchemas?.length ?? 0) > 0;
484
583
  const continuationMax = Math.max(0, opts.turnContinuation?.maxNudges ?? ANNOUNCE_NUDGE_MAX);
485
584
  let announceNudges = 0;
585
+ let malformedCallNudges = 0; // bounded re-prompts for an unparseable text tool call
486
586
  // Spectre-parity (b): bounded auto-continue after a LENGTH truncation (see gate at finalize).
487
587
  let truncationContinues = 0;
488
588
  const TRUNCATION_CONTINUE_MAX = 3;
589
+ // One-shot: the empty-retry path sets this to the perturbed temperature for the NEXT request only (0 = use
590
+ // the normal temperature). Consumed right after the request is issued, so it never leaks past the one retry.
591
+ let retryTempOverride = 0;
489
592
  // Cortana think-on truncation fix (task #14): once a round this turn hits the output-token limit, native
490
593
  // reasoning (/think) is the thing that ate the budget — a think-heavy model spends the window reasoning,
491
594
  // then the tool-call JSON (or answer) is cut off mid-generation. Re-running the recovery round WITH think
@@ -498,9 +601,9 @@ export async function runTurn(userInput, conversation, opts) {
498
601
  // Converge-or-stop guard (NO_CONVERGE_LIMIT): consecutive tool rounds with no new narration and no landed edit.
499
602
  let convergeStreak = 0;
500
603
  const narratedSigs = new Set(); // prose fingerprints already spoken this turn — repeating one is not "new" text
501
- const stopTurn = (note, roundsRun) => {
604
+ const stopTurn = (note, roundsRun, stopReason) => {
502
605
  conversation.assistant(note);
503
- return { content: note, rounds: roundsRun, toolCalls: toolCallTotal, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal };
606
+ return { content: note, rounds: roundsRun, toolCalls: toolCallTotal, stopReason, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal };
504
607
  };
505
608
  /** Feed one settled tool batch to the converge guard; true ⇒ the turn has stalled and must stop. */
506
609
  const stalledNotConverging = (calls, toolMsgs, content) => {
@@ -529,6 +632,7 @@ export async function runTurn(userInput, conversation, opts) {
529
632
  let promptMsTotal = 0; // prefill ms summed across rounds
530
633
  let emptyRetries = 0; // reasoning models sometimes return a "dud" round (no content, no tool calls)
531
634
  let truncRetries = 0; // chunk-write nudges spent recovering a truncated-tool-call 500 (truncatedToolNudge)
635
+ let truncDispatched = 0; // cut-off calls let through to dispatch after the retry budget; a 2nd means the loop isn't converging → hand back
532
636
  let loadingRetries = 0; // patient waits spent while an endpoint reports it's still (re)loading its model
533
637
  for (; rounds < absCeiling; rounds++) {
534
638
  throwIfAborted(opts.signal); // stop before spending another round (covers compaction below too)
@@ -602,6 +706,7 @@ export async function runTurn(userInput, conversation, opts) {
602
706
  spill: opts.spill, // GW-10-COMPLETE: fitToWindow offloads (re-readable) when the host can write files
603
707
  });
604
708
  let response;
709
+ let lastMaxTokens; // the clamp actually sent this round — black-box evidence
605
710
  for (;;) {
606
711
  // Harness-layer compaction gate — the single choke point every request passes through, on the
607
712
  // INITIAL attempt AND after any self-heal failover/route switch below (which `continue`s back
@@ -621,6 +726,16 @@ export async function runTurn(userInput, conversation, opts) {
621
726
  if (conversation.all.length < beforeLen)
622
727
  conversation.user(rehydrationNote(touchedFiles));
623
728
  }
729
+ // Intra-turn output-headroom guard (task #14's third leg — _ai-docs 2026-10-19): the proactive gate
730
+ // above keeps the PROMPT under threshold, but near the window (or on a small endpoint) the leftover
731
+ // generation room can still fall under a tool-safe size — the model then streams a large tool call
732
+ // into a doomed budget and truncates mid-JSON. Shed oversized tool outputs NOW, with a tighter target
733
+ // that reserves TOOL_CALL_HEADROOM_TOKENS of output room; eviction of OLD turns is the proactive
734
+ // gate's job, so no rehydration is owed here. Best-effort: on a genuinely tiny window the floor is
735
+ // unreachable (headroomTargetRatio clamps to 0) and clampMaxTokens' own floor still applies.
736
+ if (outputRoom(buildMessages(opts.systemPrompt, conversation.all), cOpts) < TOOL_CALL_HEADROOM_TOKENS) {
737
+ conversation.replaceAll(fitToWindow(conversation.all, cOpts, headroomTargetRatio(cOpts, TOOL_CALL_HEADROOM_TOKENS)));
738
+ }
624
739
  // Compaction circuit breaker: after any needed compaction, are we STILL over the window? If compaction
625
740
  // ran but can't get the request under budget (the summarizer keeps failing, or the over-budget bulk is
626
741
  // un-evictable) for COMPACTION_FAIL_LIMIT rounds running, stop spinning into the same wall — surface it
@@ -642,6 +757,8 @@ export async function runTurn(userInput, conversation, opts) {
642
757
  // Clamp generation to the room left after the real prompt (incl. tool_calls args + schemas) so a
643
758
  // deep-session request never overflows the window into a truncated reply. See clampMaxTokens.
644
759
  const maxTokens = clampMaxTokens(messages, compactionOptsFor(endpoint), opts.maxTokens ?? 8192);
760
+ lastMaxTokens = maxTokens;
761
+ const watch = watchRepetition(opts, guardCfg.enabled && guardCfg.repetition);
645
762
  try {
646
763
  response = await chat(messages, {
647
764
  base: endpoint.base,
@@ -649,14 +766,19 @@ export async function runTurn(userInput, conversation, opts) {
649
766
  token: endpoint.token,
650
767
  transport: endpoint.transport,
651
768
  maxTokens,
652
- temperature: opts.temperature,
769
+ // Empty-retry perturbation: a greedy (temp 0) empty is deterministic, so the retry must change the
770
+ // sampling to escape it. One-shot — consumed right after this call so the normal path stays greedy.
771
+ temperature: retryTempOverride > 0 ? retryTempOverride : opts.temperature,
653
772
  tools: opts.toolSchemas,
654
773
  thinking: (truncatedThisTurn || thinkLatched) ? false : opts.thinking, // read LIVE: task #14 truncation latch OR the think-spiral latch disables native reasoning for the rest of the turn
655
- signal: opts.signal,
774
+ signal: watch.signal,
656
775
  background: opts.background, // endpoint gate: sub-agents yield the shared slot to the interactive main turn
657
- onDelta: opts.onDelta,
658
- onReasoning: opts.onReasoning,
776
+ onDelta: watch.onDelta,
777
+ onReasoning: watch.onReasoning,
778
+ onPromptProgress: opts.onPromptProgress,
659
779
  });
780
+ watch.dispose();
781
+ retryTempOverride = 0; // one-shot consumed: this request has read the perturbed temperature
660
782
  tokensTotal += response.tokens ?? 0;
661
783
  genMsTotal += response.genMs ?? 0; // accumulate real gen metrics across rounds
662
784
  promptTokensTotal += response.promptTokens ?? 0;
@@ -682,6 +804,13 @@ export async function runTurn(userInput, conversation, opts) {
682
804
  break;
683
805
  }
684
806
  catch (err) {
807
+ watch.dispose();
808
+ // The stream became a runaway repetition loop and the watch tore it down: end the turn here, before any
809
+ // retry or continue-nudge could re-seed it. The partial is dropped; history keeps only the marker.
810
+ if (watch.tripped && !opts.signal?.aborted)
811
+ return watch.tripReason === "budget"
812
+ ? stopTurn(REASONING_BUDGET_INTERRUPTED, rounds + 1, "reasoning_budget")
813
+ : stopTurn(REPETITION_INTERRUPTED, rounds + 1, "repetition");
685
814
  if (isAbort(err, opts.signal))
686
815
  throw new TurnAbortedError(); // never self-heal an interrupt
687
816
  const recovery = classifyFailure(err);
@@ -810,6 +939,7 @@ export async function runTurn(userInput, conversation, opts) {
810
939
  background: opts.background,
811
940
  onDelta: opts.onDelta,
812
941
  onReasoning: opts.onReasoning,
942
+ onPromptProgress: opts.onPromptProgress,
813
943
  });
814
944
  }
815
945
  }
@@ -819,6 +949,60 @@ export async function runTurn(userInput, conversation, opts) {
819
949
  // paths — a cut-off tool call and a cut-off text answer both carry stopReason "length".
820
950
  if (response.stopReason === "length")
821
951
  truncatedThisTurn = true;
952
+ // LOCAL truncated-tool-call recovery (_ai-docs 2026-10-19): a settled tool-calling round can carry a
953
+ // call whose arguments were cut off mid-JSON — stopReason is undefined here (a tool-calling turn is
954
+ // legitimately terminal), so the length latch above never saw it. The OLD engine dispatched the
955
+ // half-written call, which dead-ended as a "could not parse arguments … CUT OFF" tool result. Recover
956
+ // it on the SAME budget as the server-thrown truncated_tool_call path: latch reasoning OFF (it ate the
957
+ // budget), DROP the whole round (an assistant(tool_calls) with no matching results is an invalid
958
+ // sequence — never persist or dispatch it), nudge toward chunked writes, and re-prompt; the headroom
959
+ // guard at the top of the next iteration frees room, and the retry runs with thinking off, so the
960
+ // re-emitted call fits. Once the shared truncRetries budget is spent the guard stops firing and the
961
+ // call dispatches, so its parse-error result surfaces honestly instead of looping.
962
+ if (response.toolCalls.length > 0) {
963
+ const cut = response.toolCalls.find((c) => {
964
+ const parsed = parseToolArgs(c.function?.arguments ?? "");
965
+ return !parsed.ok && parsed.truncated;
966
+ });
967
+ if (cut) {
968
+ if (truncRetries < MAX_TRUNC_RETRIES) {
969
+ // In budget: drop the half-written round, latch reasoning off, nudge toward chunked writes, retry.
970
+ truncatedThisTurn = true;
971
+ truncRetries += 1;
972
+ opts.onSelfHeal?.("server_error", truncRetries); // footer ↻ — a recovery is in flight
973
+ opts.onTruncationEvidence?.({
974
+ tool: cut.function?.name ?? "", args: cut.function?.arguments ?? "", truncated: true, recovered: true,
975
+ finishReason: response.finishReason, maxTokensSent: lastMaxTokens, promptTokens: response.promptTokens,
976
+ genTokens: response.tokens, endpoint: endpoint.base, model: endpoint.model,
977
+ });
978
+ conversation.user(truncatedToolNudge(cut.function?.arguments ?? ""));
979
+ continue;
980
+ }
981
+ // Budget spent. A truncated call bypasses the (name,args) loop guard — it's never dispatched with a
982
+ // real signature (guardSkip) — so without THIS halt an autonomous model re-issues the same oversized
983
+ // call every round and spins visibly (the 25× file_write loop seen live 2026-10-19). Let exactly ONE
984
+ // cut-off call DISPATCH first so its parse error surfaces honestly (the model may self-correct from
985
+ // it — onBadArgs records the raw evidence). If it STILL truncates after seeing that, the retries
986
+ // aren't converging: hand back cleanly with the decomposition the nudges asked for, rather than spin.
987
+ if (truncDispatched >= 1) {
988
+ truncatedThisTurn = true;
989
+ const msg = "[I kept hitting a cut-off tool call — an oversized argument (usually a large multi-line " +
990
+ "file body) exceeded the per-call output budget even after chunk-write nudges, so I stopped rather " +
991
+ "than spin. To get it done: ask me to write it in pieces (an initial file_write of the first " +
992
+ "section, then file_edit to append each next part, a few hundred lines per call), or paste the " +
993
+ "content and I'll place it.]";
994
+ conversation.assistant(msg);
995
+ return { content: msg, rounds: rounds + 1, toolCalls: toolCallTotal, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal };
996
+ }
997
+ truncDispatched += 1; // fall through to dispatch; onBadArgs fires the evidence (recovered:false)
998
+ }
999
+ }
1000
+ // Degenerate output (engine/repetition-guard.ts): a reply that is mostly one repeated fragment must never reach
1001
+ // the continue-nudge below (it would stitch the loop into history and re-seed it) nor be recorded verbatim.
1002
+ // Runs BEFORE every nudge; the looped text is dropped and the turn tells the user plainly.
1003
+ if (guardCfg.enabled && guardCfg.repetition && response.toolCalls.length === 0 && isDegenerateReply(response.content, response.stopReason)) {
1004
+ return stopTurn(REPETITION_INTERRUPTED, rounds + 1, "repetition");
1005
+ }
822
1006
  // Round-loop guard: a true loop repeats the SAME STEP — identical narration AND identical intended
823
1007
  // actions (tool name+args), or identical narration with no action at all. The signature is the WHOLE
824
1008
  // round (prose + the calls it drives), NOT the prose alone: a model doing DIFFERENT work each round
@@ -936,41 +1120,110 @@ export async function runTurn(userInput, conversation, opts) {
936
1120
  }
937
1121
  if (response.toolCalls.length > 0) {
938
1122
  throwIfAborted(opts.signal); // don't dispatch a tool batch for a turn the user already cancelled
939
- conversation.assistant(response.content, response.toolCalls);
1123
+ // Strip any leaked tool-call/thinking delimiter tags the model emitted into content ALONGSIDE the
1124
+ // structured calls (the "</parameter></function></tool_call>" / "</thinking>" leak) — recovery handles
1125
+ // the no-structured-calls path; this keeps the structured path's prose clean too.
1126
+ conversation.assistant(cleanAssistantProse(response.content), response.toolCalls);
940
1127
  // Race the batch against the abort signal so esc breaks even a hung tool (a frozen child process) —
941
1128
  // the abandoned tool runs to its own timeout, but the turn is never wedged.
942
- const toolMsgs = await abortable(runToolCalls(response.toolCalls, opts.tools, callCounts, rca, opts.onToolBatch, onToolStartFx, onToolResultFx, opts.signal), opts.signal);
1129
+ const onBadArgs = (tc, truncated) => opts.onTruncationEvidence?.({
1130
+ tool: tc.function?.name ?? "", args: tc.function?.arguments ?? "", truncated, recovered: false,
1131
+ finishReason: response.finishReason, maxTokensSent: lastMaxTokens, promptTokens: response.promptTokens,
1132
+ genTokens: response.tokens, endpoint: endpoint.base, model: endpoint.model,
1133
+ });
1134
+ const toolMsgs = await abortable(runToolCalls(response.toolCalls, opts.tools, callCounts, rca, opts.onToolBatch, onToolStartFx, onToolResultFx, opts.signal, guard, onBadArgs), opts.signal);
943
1135
  for (const tm of capToolRound(toolMsgs))
944
1136
  conversation.tool(tm.tool_call_id, tm.content); // cap the ROUND's total tool output so a high-fanout round can't overflow the window / defeat compaction
945
1137
  observeVerify(verify, response.toolCalls, toolMsgs); // verify-before-done: record mutation / verify signal
946
1138
  toolCallTotal += response.toolCalls.length;
1139
+ if (guard?.halt)
1140
+ return stopTurn(loopStopNote(guard.halt), rounds + 1); // the loop guard ended the turn: say so plainly
947
1141
  progressed = batchProgressed(toolMsgs);
948
1142
  noProgressStreak = progressed ? 0 : noProgressStreak + 1; // reset the stall counter on any real progress
949
1143
  noEditStreak = response.toolCalls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? "")) ? 0 : noEditStreak + 1;
950
1144
  trackTouchedFiles(response.toolCalls, touchedFiles);
1145
+ // Poll-spin guard: an agent_status spin (auto-post pending, no other work, no status change) wastes the
1146
+ // turn — pollers are exempt from the loop guard above, so this catches them. Nudge once, then end the
1147
+ // turn so the auto-posted sub-agent results resume it (rather than burning the budget re-checking).
1148
+ if (pollSpin) {
1149
+ const ps = pollSpin.observe(response.toolCalls.map((c) => c.function.name), toolMsgs.map((m) => m.content ?? ""));
1150
+ if (ps.action === "halt")
1151
+ return stopTurn(ps.message, rounds + 1);
1152
+ if (ps.action === "nudge") {
1153
+ conversation.user(ps.message);
1154
+ continue;
1155
+ }
1156
+ }
1157
+ if (noWriteProgress) {
1158
+ const nwp = noWriteProgress.observe(response.toolCalls.map((c) => c.function.name));
1159
+ if (nwp.action === "halt")
1160
+ return stopTurn(nwp.message, rounds + 1);
1161
+ if (nwp.action === "warn") {
1162
+ // Warn rides alongside execution as a result note (never blocks the turn).
1163
+ // Append to the last tool message's content.
1164
+ const last = toolMsgs[toolMsgs.length - 1];
1165
+ if (last)
1166
+ last.content += "\n\n[note: " + nwp.message + "]";
1167
+ }
1168
+ }
951
1169
  if (stalledNotConverging(response.toolCalls, toolMsgs, response.content))
952
1170
  return stopTurn(notConvergingNote(response.toolCalls), rounds + 1);
953
1171
  continue;
954
1172
  }
955
1173
  // No structured tool_calls — check for text-encoded ones before treating this as final.
956
- const recovered = recoverToolCalls(response.content);
1174
+ let recovered = recoverToolCalls(response.content);
1175
+ // The call's opener can sit in the reasoning channel while its closing tags stream as content (seen live: the
1176
+ // turn ended on "</parameter></function></tool_call>" with nothing run). Recover from the reasoning too.
1177
+ if (recovered.calls.length === 0 && recovered.malformed && response.reasoningContent) {
1178
+ const fromReasoning = recoverToolCalls(response.reasoningContent);
1179
+ if (fromReasoning.calls.length > 0)
1180
+ recovered = { ...recovered, calls: fromReasoning.calls };
1181
+ }
957
1182
  if (recovered.calls.length > 0) {
958
1183
  throwIfAborted(opts.signal);
959
1184
  conversation.assistant(recovered.cleanedContent, recovered.calls);
960
- const toolMsgs = await abortable(runToolCalls(recovered.calls, opts.tools, callCounts, rca, opts.onToolBatch, onToolStartFx, onToolResultFx, opts.signal), opts.signal);
1185
+ const toolMsgs = await abortable(runToolCalls(recovered.calls, opts.tools, callCounts, rca, opts.onToolBatch, onToolStartFx, onToolResultFx, opts.signal, guard), opts.signal);
961
1186
  for (const tm of capToolRound(toolMsgs))
962
1187
  conversation.tool(tm.tool_call_id, tm.content); // cap the ROUND's total tool output so a high-fanout round can't overflow the window / defeat compaction
963
1188
  observeVerify(verify, recovered.calls, toolMsgs); // verify-before-done: record mutation / verify signal
964
1189
  toolCallTotal += recovered.calls.length;
1190
+ if (guard?.halt)
1191
+ return stopTurn(loopStopNote(guard.halt), rounds + 1);
965
1192
  progressed = batchProgressed(toolMsgs);
966
1193
  noProgressStreak = progressed ? 0 : noProgressStreak + 1; // reset the stall counter on any real progress
967
1194
  noEditStreak = recovered.calls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? "")) ? 0 : noEditStreak + 1;
968
1195
  trackTouchedFiles(recovered.calls, touchedFiles);
1196
+ if (pollSpin) {
1197
+ const ps = pollSpin.observe(recovered.calls.map((c) => c.function.name), toolMsgs.map((m) => m.content ?? ""));
1198
+ if (ps.action === "halt")
1199
+ return stopTurn(ps.message, rounds + 1);
1200
+ if (ps.action === "nudge") {
1201
+ conversation.user(ps.message);
1202
+ continue;
1203
+ }
1204
+ }
1205
+ if (noWriteProgress) {
1206
+ const nwp = noWriteProgress.observe(recovered.calls.map((c) => c.function.name));
1207
+ if (nwp.action === "halt")
1208
+ return stopTurn(nwp.message, rounds + 1);
1209
+ if (nwp.action === "warn") {
1210
+ conversation.user(nwp.message);
1211
+ continue;
1212
+ }
1213
+ }
969
1214
  if (stalledNotConverging(recovered.calls, toolMsgs, recovered.cleanedContent))
970
1215
  return stopTurn(notConvergingNote(recovered.calls), rounds + 1);
971
1216
  continue;
972
1217
  }
973
1218
  const final = stripScratchpad(recovered.cleanedContent);
1219
+ // A tool call that could not be parsed (stray tags, cut off) must not end the turn silently: the model said it
1220
+ // would act and nothing ran. Tell it, once or twice, to re-emit the call as a proper tool call.
1221
+ if (recovered.malformed && malformedCallNudges < 2 && response.stopReason !== "length") {
1222
+ malformedCallNudges++;
1223
+ conversation.assistant(final);
1224
+ conversation.user("Your last tool call was malformed (a tag was missing or the call was cut off), so NOTHING ran. Call the tool again now as a proper tool call, with the complete arguments. If the content is long, split it into smaller calls.");
1225
+ continue;
1226
+ }
974
1227
  // Empty round — two very different causes, handled differently so we never (a) inject a user-role
975
1228
  // directive that renders as the user speaking and gets answered as the request, nor (b) treat a
976
1229
  // budget-truncated turn as a "dud".
@@ -988,8 +1241,12 @@ export async function runTurn(userInput, conversation, opts) {
988
1241
  else {
989
1242
  // Genuine empty (finish "stop"): after tool calls the tool RESULTS are already in the conversation,
990
1243
  // so just retry — the model gets another shot to write the final answer WITH that output in context.
991
- // We inject NOTHING: a 2nd system message 400s the endpoint (SPEC §1, one system message only), and
992
- // a user-role nudge would render as the user speaking and be answered as the request (the leak).
1244
+ // We inject NOTHING into the conversation: a 2nd system message 400s the endpoint (SPEC §1, one system
1245
+ // message only), and a user-role nudge would render as the user speaking and be answered as the request
1246
+ // (the leak). Instead we PERTURB SAMPLING: the operator decodes greedily (temp 0), so a bit-identical
1247
+ // re-request reproduces the same deterministic argmax-EOS empty forever; raising the retry's temperature
1248
+ // is the one change that can actually escape it, and it touches nothing in the conversation.
1249
+ retryTempOverride = emptyRetryTemp(emptyRetries); // escalate: retry 1 → 0.7, retry 2 → 1.0
993
1250
  continue;
994
1251
  }
995
1252
  }