@0perator/operator 0.1.352 → 0.1.354

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 (92) hide show
  1. package/dist/acp/agent.js +4 -2
  2. package/dist/acp/tool-map.js +5 -4
  3. package/dist/autonomy/delegate.js +55 -2
  4. package/dist/autonomy/headless.js +4 -1
  5. package/dist/autonomy/session-factory.js +1 -0
  6. package/dist/background/index.js +86 -10
  7. package/dist/background/notices.js +16 -4
  8. package/dist/cli.js +1072 -178
  9. package/dist/config/home.js +6 -0
  10. package/dist/config/memory-sections.js +92 -0
  11. package/dist/config/persona.js +144 -26
  12. package/dist/config/settings.js +15 -4
  13. package/dist/consolidation/scheduler.js +9 -2
  14. package/dist/consolidation/sleep.js +39 -278
  15. package/dist/engine/agent.js +547 -92
  16. package/dist/engine/anthropic-chat.js +13 -2
  17. package/dist/engine/aurora.js +135 -30
  18. package/dist/engine/batch-scheduler.js +27 -3
  19. package/dist/engine/compaction.js +12 -5
  20. package/dist/engine/continuation.js +51 -22
  21. package/dist/engine/contract.js +1 -1
  22. package/dist/engine/decision-points.js +7 -1
  23. package/dist/engine/front-door.js +59 -0
  24. package/dist/engine/grandmaster.js +13 -1
  25. package/dist/engine/loop-guard.js +694 -0
  26. package/dist/engine/net-error.js +2 -1
  27. package/dist/engine/owner-act.js +52 -0
  28. package/dist/engine/selfheal.js +48 -0
  29. package/dist/engine/verify-gate.js +52 -0
  30. package/dist/flywheel/processor.js +3 -1
  31. package/dist/flywheel/srft.js +8 -4
  32. package/dist/hooks/index.js +12 -8
  33. package/dist/mcp/index.js +9 -4
  34. package/dist/permissions/index.js +32 -11
  35. package/dist/permissions/modes.js +42 -0
  36. package/dist/permissions/plan-review.js +100 -0
  37. package/dist/permissions/policy.js +16 -5
  38. package/dist/permissions/signature.js +8 -3
  39. package/dist/remote/safe-commands.js +1 -1
  40. package/dist/router/read-rates.js +152 -0
  41. package/dist/selfimprove/backfill.js +174 -0
  42. package/dist/selfimprove/index.js +146 -57
  43. package/dist/selfimprove/lessons.js +429 -0
  44. package/dist/selfimprove/sync.js +58 -0
  45. package/dist/session.js +375 -31
  46. package/dist/skills/finder.js +219 -0
  47. package/dist/tools/deferred.js +28 -18
  48. package/dist/tools/executor.js +7 -3
  49. package/dist/tools/registry.js +34 -4
  50. package/dist/ui/ActivitySpinner.js +21 -12
  51. package/dist/ui/App.js +107 -30
  52. package/dist/ui/ApprovalPrompt.js +5 -3
  53. package/dist/ui/ArtifactPicker.js +3 -3
  54. package/dist/ui/BgPanel.js +105 -5
  55. package/dist/ui/Composer.js +85 -9
  56. package/dist/ui/PlanPane.js +72 -8
  57. package/dist/ui/QuestionPrompt.js +6 -4
  58. package/dist/ui/SecretPrompt.js +8 -3
  59. package/dist/ui/SessionPicker.js +2 -2
  60. package/dist/ui/SkillFinder.js +153 -0
  61. package/dist/ui/StatusRule.js +5 -2
  62. package/dist/ui/SummaryCard.js +3 -1
  63. package/dist/ui/ThinkingSpinner.js +11 -2
  64. package/dist/ui/ToolBatch.js +11 -2
  65. package/dist/ui/ToolStep.js +36 -13
  66. package/dist/ui/Transcript.js +13 -2
  67. package/dist/ui/actNow.js +61 -0
  68. package/dist/ui/batchLine.js +165 -0
  69. package/dist/ui/conversations.js +154 -0
  70. package/dist/ui/decodeHealth.js +77 -0
  71. package/dist/ui/expand.js +17 -0
  72. package/dist/ui/fit.js +40 -0
  73. package/dist/ui/fitTail.js +14 -0
  74. package/dist/ui/fold.js +149 -0
  75. package/dist/ui/format.js +46 -2
  76. package/dist/ui/liveTools.js +163 -13
  77. package/dist/ui/modelPicker.js +78 -6
  78. package/dist/ui/nextStep.js +103 -0
  79. package/dist/ui/pending.js +57 -0
  80. package/dist/ui/phase.js +105 -0
  81. package/dist/ui/planExit.js +0 -5
  82. package/dist/ui/progressbar.js +4 -26
  83. package/dist/ui/readForecast.js +44 -0
  84. package/dist/ui/readProgress.js +119 -0
  85. package/dist/ui/reportLine.js +62 -0
  86. package/dist/ui/slashCommands.js +1 -1
  87. package/dist/ui/theme.js +1 -0
  88. package/dist/ui/turnFlow.js +72 -0
  89. package/dist/ui/turnLedger.js +121 -0
  90. package/dist/ui/turnScope.js +11 -0
  91. package/dist/util/slash.js +18 -0
  92. package/package.json +1 -1
@@ -2,19 +2,22 @@
2
2
  // text tool-call recovery (toolcalls.ts) and compaction (compaction.ts). Tools and routing are
3
3
  // NOT implemented here — this file depends only on the two interfaces below, which the
4
4
  // kode-tsi/src/tools/** + kode-tsi/src/router/** lane implements.
5
- import { chat, endpointSlots, getOperatorToken, requiresOperatorToken } from "./aurora.js";
5
+ import { chat, endpointSlots, getOperatorToken, requiresOperatorToken, StreamServerError } from "./aurora.js";
6
6
  import { parseToolArgs } from "./json-repair.js";
7
7
  import { buildMessages } from "./messages.js";
8
8
  import { recoverToolCalls, cleanAssistantProse } from "./toolcalls.js";
9
9
  import { compact, needsCompaction, shouldProactivelyCompact, fitToWindow, clampMaxTokens, outputRoom, headroomTargetRatio, effectiveCeilingTokens, fullRequestEstimate, TOOL_CALL_HEADROOM_TOKENS } from "./compaction.js";
10
10
  import { globalTokenMeter, endpointKey, requestChars } from "./token-meter.js";
11
- import { classifyFailure, servedContextLimit, outputCeilingLimit, learnOutputCeiling, learnedOutputCeiling, backoffMs, sleep } from "./selfheal.js";
12
- import { TaskVerification, VERIFY_REMINDER, NOT_VERIFIED_BANNER } from "./verify-gate.js";
11
+ import { classifyFailure, failureCause, servedContextLimit, outputCeilingLimit, learnOutputCeiling, learnedOutputCeiling, backoffMs, sleep } from "./selfheal.js";
12
+ import { hostOf } from "./net-error.js";
13
+ import { TaskVerification, VERIFY_REMINDER, NOT_VERIFIED_BANNER, unrunCheckBanner, unrunCheckReminder } from "./verify-gate.js";
13
14
  import { detectRefusal, buildAffirmativeRetry, UNRESTRICTED_MAX_RETRIES } from "./unrestricted.js";
14
15
  import { ComputerEventStream, ComputerEventTracker } from "./computer-event.js";
15
- import { LoopRecovery, IDEMPOTENT_TOOLS, LoopGuard, PollSpinGuard, NoWriteProgressGuard, YieldAfterDispatchGuard, loopStopNote, resolveLoopGuardConfig } from "./loop-guard.js";
16
+ import { LoopRecovery, IDEMPOTENT_TOOLS, LoopGuard, PollSpinGuard, NoWriteProgressGuard, YieldAfterDispatchGuard, loopStopNote, resolveLoopGuardConfig, LoopEvidenceTracker, loopRecoveryNote, noEditNudge, repeatedStepNudge, repeatedStepRedirect, reasoningLoopNudge, SELF_LOOP_NUDGE, staleRereadNudge, isSystemNotice, servedTask, CallLedger, callLabel, deadRoundNote, deadRoundStop, loopNudgeKind, refusedResult, resultFailed } from "./loop-guard.js";
17
+ import { inferType } from "./grandmaster.js";
16
18
  import { RunawayStreamWatch, ReasoningBudgetWatch, isDegenerateReply, REPETITION_INTERRUPTED, REASONING_BUDGET_INTERRUPTED } from "./repetition-guard.js";
17
19
  import { isBetaRefusal, privateBetaMessage } from "../auth/beta.js";
20
+ import { OWNER_ACT_MESSAGE, OWNER_ACT_REFUSED, OWNER_ACT_SETTLE_MS, OWNER_ACT_STOP, keptPartial } from "./owner-act.js";
18
21
  const MAX_SELF_HEAL_PER_TURN = 3;
19
22
  // A "loading" 503 (endpoint restarting/warming) is a KNOWN-recoverable WAIT, not a failure — a model reload
20
23
  // is ~30-90s, far longer than the ≤8s exponential self-heal backoff, so it gets its own patient budget that
@@ -26,9 +29,12 @@ const LOOP_GUARD_LIMIT = 5; // identical (name+args) calls in a turn before shor
26
29
  // file is verify-after-fix iteration, not a spin, so it must be unbounded. Only a genuinely repeated call
27
30
  // with NO intervening edit (a true no-progress loop) trips this. Raised 3→5 so even a no-edit re-run has
28
31
  // headroom before the guard fires. The narration/no-progress stalls below are the separate progress-gated stops.
29
- import { DECISION_POINT_NUDGE, isBuildRequest, shouldHoldForDecision } from "./decision-points.js";
32
+ import { DECISION_POINT_NUDGE, PLAN_REVIEW_NUDGE, isBuildRequest, shouldHoldForDecision } from "./decision-points.js";
30
33
  import { MUTATING_TOOLS, mutationLanded } from "../tools/mutating.js"; // single source of truth (see tools/mutating.ts) — a LANDED workspace edit ⇒ prior identical-call counts are stale
31
- import { ANNOUNCE_NUDGE, ANNOUNCE_NUDGE_MAX, DELEGATION_NUDGE, detectAnnouncedDelegation, detectUnfinishedAction, engineNote, detectSelfDialogue, SELF_DIALOGUE_NUDGE, SELF_DIALOGUE_NUDGE_MAX, needsClosingSteer, CLOSING_NUDGE, CLOSING_NUDGE_UNATTENDED, EMPTY_REPLY_NUDGE, emptyReplyStatus, closeStopNote, stopQuestion, stripEngineEcho, isEngineFinal } from "./continuation.js";
34
+ /** The executor's identical-call refusal, exactly (tools/executor.ts): a tool's own output that merely starts with
35
+ * "loop guard:" (a log, a grep of this source) is real output, not a refusal to be counted and replaced. */
36
+ export const EXECUTOR_REPEAT_REFUSAL = /^loop guard: "[^"]+" called \d+x with identical args this turn/;
37
+ import { ANNOUNCE_NUDGE, ANNOUNCE_NUDGE_MAX, DELEGATION_NUDGE, detectAnnouncedDelegation, detectUnfinishedAction, engineNote, detectSelfDialogue, SELF_DIALOGUE_NUDGE, SELF_DIALOGUE_NUDGE_MAX, needsClosingSteer, CLOSING_NUDGE, CLOSING_NUDGE_UNATTENDED, EMPTY_REPLY_NUDGE, fallbackLine, noAnswer, closeStopNote, stopQuestion, stopKind, stripEngineEcho, isEngineFinal } from "./continuation.js";
32
38
  // Poll/status tools are meant to be called repeatedly while waiting on async work — NEVER a spin, so the
33
39
  // loop guard skips them entirely (agent_status polls sub-agents, bash_output polls a background job).
34
40
  const LOOP_GUARD_EXEMPT = new Set(["agent_status", "bash_output"]);
@@ -103,6 +109,11 @@ const NO_PROGRESS_LIMIT = 8; // consecutive tool batches that return NOTHING new
103
109
  // only ever NUDGES once (NO_EDIT_NUDGE); it never stops a turn, so a genuine long read-only task is safe.
104
110
  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;
105
111
  const SELF_LOOP_STOP = 3; // model admits it's looping this many rounds (no file edit between) ⇒ graceful stop
112
+ // The admissions SELF_LOOP_RE misses, in the model's own words of 11/02 — "I've been stuck reading in circles", "I've been
113
+ // reading without writing", "I keep re-reading the same files" (30+ times in the review loop and both replay arms; matched by
114
+ // none of it). First person only: "Atlas is stuck reading, not writing" is about a sub-agent. These nudge (a loop warning, so
115
+ // ignoring one resets the turn) but never count toward the self-loop STOP, which stays on SELF_LOOP_RE.
116
+ const LOOP_ADMISSION_RE = /\bI(?:['’]ve| have) been stuck\b|\bI(?:['’]ve| have) been (?:re-?reading|reading|grepping|searching)\b[^.!?\n]{0,40}?(?:in circles|without\b|too long|the same\b|again\b)|\bI keep (?:re-?reading|reading|grepping|checking|running) the same\b/i;
106
117
  // Converge-or-stop guard: the identical-call guards above can't catch a model that varies its args every round
107
118
  // (a different path / pattern / comment each time) yet never answers and never changes a file. This many
108
119
  // CONSECUTIVE tool rounds with NO new narration from the model and NO landed file change ⇒ it is not converging:
@@ -250,6 +261,30 @@ function observeVerify(v, calls, toolMsgs) {
250
261
  const results = toolMsgs.map((m) => m.content || "");
251
262
  v.observe(names, commands, results);
252
263
  }
264
+ /** Feed one settled tool batch to the turn's loop evidence (reads, writes), index-aligned like observeVerify. */
265
+ function observeLoop(ev, calls, toolMsgs) {
266
+ calls.forEach((c, i) => {
267
+ let args = {};
268
+ try {
269
+ const a = JSON.parse(c.function.arguments || "{}");
270
+ if (a && typeof a === "object")
271
+ args = a;
272
+ }
273
+ catch { /* unparseable — no targets */ }
274
+ ev.observe(c.function.name, args, toolMsgs[i]?.content ?? "");
275
+ });
276
+ }
277
+ // A turn the shell starts to deliver a job notice or a sub-agent report serves the LAST request, not the notice.
278
+ function lastRequest(msgs) {
279
+ for (let i = msgs.length - 1; i >= 0; i--) {
280
+ const c = msgs[i].role === "user" && typeof msgs[i].content === "string" ? msgs[i].content : "";
281
+ if (c && !c.startsWith("[engine note") && !c.startsWith("[Compacted summary") && !isSystemNotice(c))
282
+ return servedTask(c);
283
+ }
284
+ return undefined;
285
+ }
286
+ // A line of the model's own narration worth carrying across a loop reset: something it found, fixed or verified.
287
+ const FINDING_RE = /\b(?:found|fix(?:ed|es)?|issue|bug|error|fail(?:s|ed|ing)?|pass(?:es|ed)?|conflict|missing|broken|wrong|cause)\b/i;
253
288
  /** Thrown by runTurn when the turn is interrupted via AgentOpts.signal (SPEC §9). One type for hosts to catch. */
254
289
  export class TurnAbortedError extends Error {
255
290
  constructor(reason) {
@@ -314,7 +349,8 @@ function parseArgs(raw) {
314
349
  * guard (SPEC §2: identical (name,args) ≥3× this turn is short-circuited) and reporting the
315
350
  * batch via onToolBatch with a real (unrounded) duration.
316
351
  */
317
- async function runToolCalls(toolCalls, tools, callCounts, rca, onToolBatch, onToolStart, onToolResult, signal, guard, onBadArgs) {
352
+ async function runToolCalls(toolCalls, tools, callCounts, rca, onToolBatch, onToolStart, onToolResult, signal, guard, onBadArgs, // black-box: a bad call that IS being dispatched (post-budget, or malformed-not-truncated)
353
+ onToolCallStart) {
318
354
  // One id for this whole round (SPEC parallel-tool-batch) — every call made here, however it
319
355
  // resolves (executed, parse error, loop-guarded), shares it, so a host can box "N tools in
320
356
  // parallel" together even for the calls that never reached the executor. Same id-shape idiom as
@@ -324,11 +360,13 @@ async function runToolCalls(toolCalls, tools, callCounts, rca, onToolBatch, onTo
324
360
  const batchSize = toolCalls.length;
325
361
  const pending = [];
326
362
  const preResolved = new Map(); // id -> result, for parse errors + loop-guarded calls
363
+ const refusedById = new Map(); // id -> why it never ran: the guards below, or the executor chain
327
364
  const parsedArgs = new Map();
328
365
  let loopAbort; // set when a signature blows past LOOP_GUARD_HARD — the turn is aborted (below)
329
366
  let loopAbortCompleted = false; // the RCA gate fired: the action already completed, so recovery does not apply
330
367
  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)
331
368
  const guardReplay = new Set(); // calls the identical-args counter refused: one more repeat for the result guard, nothing else
369
+ const repeatIds = new Set(); // calls refused as repeats (identical args, or a re-worded completed action) — a round of only these is dead
332
370
  toolCalls.forEach((tc, batchIndex) => {
333
371
  const parsed = parseArgs(tc.function.arguments);
334
372
  if (!parsed.ok) {
@@ -342,7 +380,12 @@ async function runToolCalls(toolCalls, tools, callCounts, rca, onToolBatch, onTo
342
380
  const capped = guard?.beforeCall(tc.function.name, parsed.args);
343
381
  if (capped?.action === "halt") { // per-turn cap or a replay the result guard already knows is futile: refuse, the turn ends after this batch
344
382
  preResolved.set(tc.id, `Blocked ${tc.function.name}: ${capped.message}. Work with what you already have and give the user your answer.`);
383
+ refusedById.set(tc.id, "blocked");
345
384
  guardSkip.add(tc.id);
385
+ // a replay the result guard knows is futile (the same failure again, a read returning the same again) is a repeat:
386
+ // a round of only these is a dead round, recovered, not a stop. The web and sub-agent caps stay halts.
387
+ if (capped.code === "exact_failure" || capped.code === "no_progress")
388
+ repeatIds.add(tc.id);
346
389
  return;
347
390
  }
348
391
  // Poll/status tools (agent_status, bash_output) are DESIGNED to be called repeatedly with identical
@@ -366,7 +409,9 @@ async function runToolCalls(toolCalls, tools, callCounts, rca, onToolBatch, onTo
366
409
  }
367
410
  preResolved.set(tc.id, `Loop guard: "${tc.function.name}" already returned your status this turn and it has not changed. Do ` +
368
411
  `NOT call it again — answer the user, or ask them what you should do next.`);
412
+ refusedById.set(tc.id, "blocked");
369
413
  guardReplay.add(tc.id);
414
+ repeatIds.add(tc.id);
370
415
  return;
371
416
  }
372
417
  if (count >= LOOP_GUARD_LIMIT) { // SPEC §2: short-circuit the Nth identical call (matches executor's guard)
@@ -379,7 +424,9 @@ async function runToolCalls(toolCalls, tools, callCounts, rca, onToolBatch, onTo
379
424
  }
380
425
  preResolved.set(tc.id, `Loop guard: "${tc.function.name}" has been called ${count} times this turn with identical ` +
381
426
  `arguments. Try a different approach instead of repeating this call.`);
427
+ refusedById.set(tc.id, "blocked");
382
428
  guardReplay.add(tc.id);
429
+ repeatIds.add(tc.id);
383
430
  return;
384
431
  }
385
432
  // RCA gate (see RCA_STOP above): division of labour with the guard above — EXACT repeats are LOOP_GUARD's
@@ -396,7 +443,9 @@ async function runToolCalls(toolCalls, tools, callCounts, rca, onToolBatch, onTo
396
443
  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.`;
397
444
  }
398
445
  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.`);
446
+ refusedById.set(tc.id, "blocked");
399
447
  guardSkip.add(tc.id);
448
+ repeatIds.add(tc.id);
400
449
  return;
401
450
  }
402
451
  pending.push({ id: tc.id, name: tc.function.name, args: parsed.args, batchId, batchSize, batchIndex });
@@ -413,7 +462,11 @@ async function runToolCalls(toolCalls, tools, callCounts, rca, onToolBatch, onTo
413
462
  onToolStart?.(pending);
414
463
  const started = performance.now();
415
464
  const executed = pending.length
416
- ? await tools.executeParallel(pending, onToolResult ? (i, r) => onToolResult(pending[i].id, r, batchId) : undefined, signal)
465
+ ? await tools.executeParallel(pending, (i, r, why) => {
466
+ if (why)
467
+ refusedById.set(pending[i].id, why);
468
+ onToolResult?.(pending[i].id, r, batchId, why);
469
+ }, signal, onToolCallStart ? (i) => onToolCallStart(pending[i].id, batchId) : undefined)
417
470
  : [];
418
471
  const durationMs = performance.now() - started;
419
472
  const resultById = new Map(preResolved);
@@ -465,10 +518,42 @@ async function runToolCalls(toolCalls, tools, callCounts, rca, onToolBatch, onTo
465
518
  batchId,
466
519
  batchSize,
467
520
  batchIndex,
521
+ ...(refusedById.has(tc.id) ? { refused: refusedById.get(tc.id) } : {}),
468
522
  }));
469
523
  onToolBatch(events, durationMs);
470
524
  }
471
- return toolCalls.map((tc) => ({ role: "tool", content: resultById.get(tc.id) ?? "", tool_call_id: tc.id }));
525
+ pending.forEach((p, i) => { if (EXECUTOR_REPEAT_REFUSAL.test(executed[i] ?? ""))
526
+ repeatIds.add(p.id); }); // the executor's own identical-call guard
527
+ return {
528
+ msgs: toolCalls.map((tc) => ({ role: "tool", content: resultById.get(tc.id) ?? "", tool_call_id: tc.id })),
529
+ repeats: toolCalls.filter((tc) => repeatIds.has(tc.id)).map((tc) => ({ name: tc.function.name, args: parsedArgs.get(tc.id) ?? {} })),
530
+ ran: pending.flatMap((p, i) => (repeatIds.has(p.id) ? [] : [{ name: p.name, args: p.args, result: executed[i] ?? "" }])),
531
+ };
532
+ }
533
+ /** Where a dead round's looping rounds start (runTurn recoverDeadRound). Walking back from the end: every round whose calls
534
+ * are all in the loop, its results, and the loop warnings between those rounds (a loop-family nudge, the self-dialogue
535
+ * nudge) — up to anything else: the turn's own message, an answer, a round with another call, any other engine note (an
536
+ * earlier recovery's note, a reset's digest, a steer). Whole rounds only, so no call is left without its result. */
537
+ function loopingRun(all, userInput, inLoop) {
538
+ let start = all.length;
539
+ let rounds = 0;
540
+ for (let i = all.length - 1; i >= 0; i--) {
541
+ const m = all[i];
542
+ if (m.role === "tool")
543
+ continue;
544
+ const calls = m.role === "assistant" ? m.tool_calls ?? [] : [];
545
+ if (calls.length && calls.every((c) => { const a = parseArgs(c.function?.arguments ?? ""); return inLoop({ name: c.function?.name ?? "", args: a.ok ? a.args : {} }); })) {
546
+ start = i;
547
+ rounds++;
548
+ continue;
549
+ }
550
+ if (m.role === "user" && m.content !== userInput && (loopNudgeKind(m.content) !== undefined || m.content === engineNote(SELF_DIALOGUE_NUDGE))) {
551
+ start = i;
552
+ continue;
553
+ }
554
+ break;
555
+ }
556
+ return { start, rounds };
472
557
  }
473
558
  // Rehydration (enterprise compaction, continuity half). A compaction summarizes away raw tool outputs — a
474
559
  // file the model read 20 turns ago now survives only as a lossy summary, so a later edit can act on STALE
@@ -505,10 +590,13 @@ export function rehydrationNote(touched) {
505
590
  }
506
591
  /** Streaming half of the repetition guard: wraps the delta callbacks and the abort signal handed to chat() so a
507
592
  * reply that has become a runaway loop is torn down mid-stream (the transport closes the fetch) instead of
508
- * streaming until the output cap. A host abort still aborts. `tripped` tells the caller which one it was. */
593
+ * streaming until the output cap. A host abort still aborts. `tripped` tells the caller which one it was. The same
594
+ * controller serves ctrl+y (owner-act.ts): a request cuts a live stream at once, or — while the prompt is still being
595
+ * read — arms and cuts on the first token; `partial` is what had streamed, kept for the act round. */
509
596
  function watchRepetition(opts, on) {
510
- if (!on)
511
- return { signal: opts.signal, onDelta: opts.onDelta, onReasoning: opts.onReasoning, tripped: false, dispose: () => { } };
597
+ const owner = opts.ownerAct;
598
+ if (!on && !owner)
599
+ return { signal: opts.signal, onDelta: opts.onDelta, onReasoning: opts.onReasoning, tripped: false, armedTrip: false, partial: { text: "", reasoning: "" }, dispose: () => { } };
512
600
  const ctl = new AbortController();
513
601
  const link = () => ctl.abort();
514
602
  if (opts.signal?.aborted)
@@ -518,32 +606,59 @@ function watchRepetition(opts, on) {
518
606
  const text = new RunawayStreamWatch();
519
607
  const thought = new RunawayStreamWatch(); // reasoning that REPEATS a fragment
520
608
  const thoughtBudget = new ReasoningBudgetWatch(); // reasoning that goes LONG without acting ("in circles")
609
+ let streamed = false;
610
+ let armed = false; // ctrl+y while the server still reads the prompt: cut on the first token, so the read is not wasted
521
611
  const w = {
522
612
  signal: ctl.signal,
523
613
  tripped: false,
524
- onDelta: (c) => { opts.onDelta?.(c); if (!w.tripped && text.feed(c)) {
525
- w.tripped = true;
526
- w.tripReason = "repetition";
527
- ctl.abort();
528
- } },
614
+ armedTrip: false,
615
+ partial: { text: "", reasoning: "" },
616
+ onDelta: (c) => {
617
+ opts.onDelta?.(c);
618
+ if (owner)
619
+ w.partial.text += c;
620
+ streamed = true;
621
+ if (w.tripped)
622
+ return;
623
+ if (armed) {
624
+ w.armedTrip = true;
625
+ trip("owner");
626
+ return;
627
+ }
628
+ if (on && text.feed(c))
629
+ trip("repetition");
630
+ },
529
631
  onReasoning: (c) => {
530
632
  opts.onReasoning?.(c);
633
+ if (owner)
634
+ w.partial.reasoning += c;
635
+ streamed = true;
531
636
  if (w.tripped)
532
637
  return;
533
- if (thought.feed(c)) {
534
- w.tripped = true;
535
- w.tripReason = "repetition";
536
- ctl.abort();
638
+ if (armed) {
639
+ w.armedTrip = true;
640
+ trip("owner");
537
641
  return;
538
642
  }
539
- if (thoughtBudget.feed(c)) {
540
- w.tripped = true;
541
- w.tripReason = "budget";
542
- ctl.abort();
643
+ if (!on)
644
+ return;
645
+ if (thought.feed(c)) {
646
+ trip("repetition");
647
+ return;
543
648
  }
649
+ if (thoughtBudget.feed(c))
650
+ trip("budget");
544
651
  },
545
- dispose: () => opts.signal?.removeEventListener("abort", link),
652
+ dispose: () => { opts.signal?.removeEventListener("abort", link); owner?.listen(undefined); },
546
653
  };
654
+ const trip = (why) => { w.tripped = true; w.tripReason = why; ctl.abort(); };
655
+ owner?.listen(() => { if (w.tripped)
656
+ return; if (streamed)
657
+ trip("owner");
658
+ else
659
+ armed = true; });
660
+ if (owner?.pending())
661
+ armed = true; // asked for in the gap between the round's top and this request
547
662
  return w;
548
663
  }
549
664
  /** Runs one user turn to completion: compacts, loops model↔tools ≤maxRounds, self-heals, finalizes. */
@@ -563,6 +678,22 @@ export function authError(err, base) {
563
678
  return new Error(`${msg}\n${why}; or set a failover endpoint that needs no token (settings endpoints.failover)`);
564
679
  }
565
680
  export async function runTurn(userInput, conversation, opts) {
681
+ // One compact() with its host signals around the summarizer round-trip — the slow part a UI shows. A compact() with
682
+ // nothing to evict calls no summarizer and signals nothing, so a host never flashes a compaction that did not happen.
683
+ const compactSignalled = async (msgs, cOpts, before) => {
684
+ let started = false;
685
+ const summarize = async (span) => {
686
+ if (!started) {
687
+ started = true;
688
+ opts.onCompactionStart?.({ before });
689
+ }
690
+ return cOpts.summarize(span);
691
+ };
692
+ const out = await compact(msgs, { ...cOpts, summarize });
693
+ if (started)
694
+ opts.onCompactionEnd?.({ before, after: fullRequestEstimate(out, cOpts) });
695
+ return out;
696
+ };
566
697
  const softRounds = opts.maxRounds ?? 10;
567
698
  const absCeiling = Math.max(softRounds + 1, opts.maxRoundsHard ?? 400); // absolute safety stop; progress-aware below
568
699
  const turnStart = Date.now(); // for the per-turn wall-clock budget (opts.maxTurnWallClockMs) — the only bound on TIME
@@ -574,6 +705,25 @@ export async function runTurn(userInput, conversation, opts) {
574
705
  const yieldGuard = guardCfg.enabled ? new YieldAfterDispatchGuard(undefined, undefined, (opts.liveSubAgents?.() ?? 0) > 0) : undefined; // after spawn_agent (or from round one of a wake turn with sub-agents live): non-mutating rounds are waiting-with-busywork — yield so the reports resume the turn
575
706
  const noWriteProgress = guardCfg.enabled ? new NoWriteProgressGuard(guardCfg.warnInvestigateLoop, guardCfg.stopInvestigateLoop, guardCfg.hardStop && guardCfg.stopOnNoWrite) : undefined; // investigate-loop detector — catches rounds with zero mutating calls
576
707
  const rca = { succeeded: new Map(), refused: new Map() }; // normalized-fingerprint → completed exact spellings; + refusal tally (see RCA_STOP)
708
+ // Loop reset (loop-guard.ts "Loop evidence"): every loop-family nudge is counted; the Nth one the model has seen and
709
+ // answered with no landed write since, while the turn repeats itself (a warning ignored), is not injected — before
710
+ // the next request this turn's rounds become ONE digest note (what it read, with the latest output of each file;
711
+ // what it changed; its findings; the next action). Deterministic, no model call; earlier turns are untouched.
712
+ // Bounded per turn; past it the nudges go in as before (interactive warns, unattended keeps the hard stop and
713
+ // LoopRecovery).
714
+ const loopEv = new LoopEvidenceTracker();
715
+ const loopResetOn = guardCfg.enabled && guardCfg.compactAfterNudges > 0;
716
+ let loopReset; // a reset is due before the next request
717
+ let loopResets = 0;
718
+ const request = opts.request ?? (isSystemNotice(userInput) ? lastRequest(conversation.all) ?? userInput : servedTask(userInput));
719
+ const answerFirst = ["review", "search", "research", "plan"].includes(inferType(request));
720
+ const turnNotes = []; // the model's own narration this turn (first lines, deduped) — its findings survive a reset
721
+ const noteSigs = new Set();
722
+ // Dead rounds (loop-guard.ts "Dead rounds"): a round whose every call was refused as a repeat is recovered — the looping
723
+ // rounds become ONE note of what those calls returned (the ledger) and a review directive — and the turn goes on, within
724
+ // LoopRecovery's budget. The step that follows a recovery is reported once (the mentor pair's second half).
725
+ const ledger = new CallLedger();
726
+ let proceedAfter;
577
727
  const contentSigs = new Map(); // per-round prose fingerprints → the narration loop guard
578
728
  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)
579
729
  let progressed = true; // did the PREVIOUS tool batch advance? gates the guard (progress clears it)
@@ -596,6 +746,7 @@ export async function runTurn(userInput, conversation, opts) {
596
746
  const verifyEnabled = opts.verifyGate?.enabled !== false;
597
747
  const verifyMaxNudges = Math.max(0, opts.verifyGate?.maxNudges ?? 1);
598
748
  let verifyNudges = 0;
749
+ let unrunNudged = false; // the reported-check reminder fires at most once per turn
599
750
  const unrestrictedEnabled = opts.unrestricted !== false; // default on — owner's private system
600
751
  // 0perator Computer feed (opt-in, additive): when the host wants a typed action stream, compose the two
601
752
  // tool callbacks here so runToolCalls stays untouched. The tracker pushes normalized start/end events into
@@ -611,7 +762,7 @@ export async function runTurn(userInput, conversation, opts) {
611
762
  const origStart = opts.onToolStart;
612
763
  const origResult = opts.onToolResult;
613
764
  onToolStartFx = (calls) => { origStart?.(calls); ceTracker.onToolStart(calls); };
614
- onToolResultFx = (id, result, batchId) => { origResult?.(id, result, batchId); ceTracker.onToolResult(id, result); };
765
+ onToolResultFx = (id, result, batchId, refused) => { origResult?.(id, result, batchId, refused); ceTracker.onToolResult(id, result); };
615
766
  }
616
767
  // Turn-continuation: nudge a model that ends on an unperformed action announcement to actually do it (bounded).
617
768
  const continuationEnabled = opts.turnContinuation?.enabled !== false && (opts.toolSchemas?.length ?? 0) > 0;
@@ -625,9 +776,10 @@ export async function runTurn(userInput, conversation, opts) {
625
776
  let lastReasoning = ""; // the reasoning channel of an empty round — a model that answers there still answered
626
777
  const hasAskTool = (opts.toolSchemas ?? []).some((s) => s?.function?.name === "ask_user");
627
778
  const decisionGate = opts.decisionPoints?.enabled === true && hasAskTool;
628
- const buildTurn = decisionGate && isBuildRequest(userInput);
779
+ const buildTurn = decisionGate && isBuildRequest(opts.ownerText ?? userInput);
629
780
  let askedThisTurn = false; // ask_user ran this turn — the owner already chose a direction
630
781
  let decisionNudged = false; // the decision-point hold fires at most once per turn
782
+ const decisionNudge = opts.decisionPoints?.planReview === true ? PLAN_REVIEW_NUDGE : DECISION_POINT_NUDGE; // Autonomous: a plan review replaces the options
631
783
  let repliesSinceOwner = 0; // non-empty model replies since the owner last spoke (turn start, or an ask_user answer) — the first is never self-dialogue
632
784
  let emptyNudged = false; // the reframe nudge goes in on the FIRST genuine empty, whatever the retry counter says
633
785
  let malformedCallNudges = 0; // bounded re-prompts for an unparseable text tool call
@@ -652,7 +804,174 @@ export async function runTurn(userInput, conversation, opts) {
652
804
  const stopTurn = (note, roundsRun, stopReason) => {
653
805
  const text = closeStopNote(note, opts.preservedState?.()); // never a bare stop: the open items + how to steer
654
806
  conversation.assistant(text);
655
- return { content: text, display: stopQuestion(note, opts.preservedState?.()), rounds: roundsRun, toolCalls: toolCallTotal, stopReason, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal };
807
+ return { content: text, display: stopQuestion(note, opts.preservedState?.()), stopKind: stopKind(note), rounds: roundsRun, toolCalls: toolCallTotal, stopReason, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal, loop: loopEv.evidence() };
808
+ };
809
+ // Never silent (11/04): a router's legs are each tried once per round. When all of them fail, or the model keeps
810
+ // finishing with nothing in its reply, the model's fallback (TurnModel) takes the rest of THIS turn; a turn nothing
811
+ // answers ends naming each leg's cause and the next step (noAnswer).
812
+ let router = opts.router;
813
+ let fallback;
814
+ let fallbackPending; // reported when the fallback's first reply with something in it lands
815
+ const legFailures = []; // this turn's failed legs, in the order tried
816
+ const failedLeg = (ep, cause, detail) => {
817
+ const model = fallback?.name ?? opts.model?.name ?? ep.label ?? ep.model;
818
+ const host = hostOf(ep.base);
819
+ const seen = legFailures.find((l) => l.model === model && l.host === host);
820
+ if (seen)
821
+ return Object.assign(seen, { cause, detail, tries: seen.tries + 1 });
822
+ const leg = { model, host, cause, detail, tries: 1 };
823
+ legFailures.push(leg);
824
+ return leg;
825
+ };
826
+ const serverFailed = (ep, err) => {
827
+ const inBand = err instanceof StreamServerError; // the server's own error, sent with a 200
828
+ return failedLeg(ep, failureCause(err) + (inBand && ep.provider ? ` on ${ep.provider}` : ""), inBand && err.via !== "empty" ? "inside an HTTP 200" : undefined);
829
+ };
830
+ /** Hand the rest of the turn to the model's fallback, once: its router and a fresh self-heal budget. */
831
+ const takeFallback = (reason, silent) => {
832
+ const fb = fallback || !opts.model?.fallback ? undefined : opts.model.fallback();
833
+ if (!fb || !opts.model)
834
+ return undefined;
835
+ const from = opts.model.name;
836
+ const legs = legFailures.filter((l) => l.model === from).map((l) => ({ ...l }));
837
+ const cause = [...new Set(legs.map((l) => l.cause))].join("; ");
838
+ fallbackPending = { from, to: fb.name, reason, line: fallbackLine({ from, to: fb.name, cause, silent }), legs };
839
+ fallback = fb;
840
+ router = fb.router;
841
+ selfHealBudget = MAX_SELF_HEAL_PER_TURN;
842
+ return router.select(buildMessages(opts.systemPrompt, conversation.all), opts.toolSchemas);
843
+ };
844
+ const fallbackLanded = () => {
845
+ if (!fallbackPending)
846
+ return;
847
+ opts.onFallback?.(fallbackPending);
848
+ fallbackPending = undefined;
849
+ };
850
+ const unanswered = (roundsRun) => {
851
+ const na = noAnswer({ tried: legFailures, owner: opts.model?.name ?? legFailures[0]?.model ?? "the model", fallback: fallback?.name, tasks: opts.preservedState?.() });
852
+ conversation.assistant(na.note);
853
+ return { content: na.note, display: na.display, stopKind: "unanswered", rounds: roundsRun, toolCalls: toolCallTotal, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal, loop: loopEv.evidence() };
854
+ };
855
+ /** A loop-family nudge: injected, or — when it is the Nth ignored one — replaced by a loop reset before the next
856
+ * request. While a reset is pending, further nudges are absorbed: its note supersedes them. */
857
+ const loopNudge = (kind, text) => {
858
+ const { unheeded, repeating } = loopEv.nudge(kind);
859
+ if (loopReset)
860
+ return;
861
+ if (loopResetOn && repeating && unheeded >= guardCfg.compactAfterNudges && loopResets < guardCfg.maxLoopCompactions) {
862
+ loopReset = kind;
863
+ return;
864
+ }
865
+ engineUser(text);
866
+ };
867
+ const noteNarration = (content) => {
868
+ const line = content.split("\n").map((l) => l.trim()).find(Boolean) ?? "";
869
+ const sig = contentSignature(line);
870
+ if (!sig || noteSigs.has(sig) || /^(?:you'?re right|good point)\b/i.test(line))
871
+ return;
872
+ noteSigs.add(sig);
873
+ turnNotes.push(line.length > 200 ? line.slice(0, 200) + "…" : line);
874
+ };
875
+ /** The reset itself — deterministic, no model call: this turn's rounds (everything after the turn's own message) become
876
+ * ONE engine note built from what the engine saw them do (loopRecoveryNote). Earlier turns stay as they are; the
877
+ * proactive compaction right after it handles their size under the normal rules. The repeat counters that compared
878
+ * against the replaced results start over, so the one re-read the note allows comes back whole. */
879
+ const resetLoop = (kind, cOpts) => {
880
+ loopResets++;
881
+ const ev = loopEv.evidence();
882
+ const digest = loopEv.digest();
883
+ const before = fullRequestEstimate(conversation.all, cOpts);
884
+ const all = conversation.all;
885
+ let start = all.length - 1;
886
+ while (start >= 0 && !(all[start].role === "user" && all[start].content === userInput))
887
+ start--;
888
+ const replaced = start >= 0 ? all.length - start - 1 : 0;
889
+ if (replaced > 0) {
890
+ conversation.replaceAll(all.slice(0, start + 1));
891
+ callCounts.clear();
892
+ rca.succeeded.clear();
893
+ rca.refused.clear();
894
+ guard?.forgetResults();
895
+ touchedFiles.length = 0; // the digest carries them; a later rehydration note must not send the model back to them
896
+ }
897
+ loopEv.recovered(replaced > 0);
898
+ // A fresh runway: the streaks that would re-nudge or stop this turn count again from the reset.
899
+ selfLoopStreak = 0;
900
+ thinkSpiralStreak = 0;
901
+ convergeStreak = 0;
902
+ noEditStreak = 0;
903
+ contentSigs.clear();
904
+ engineUser(loopRecoveryNote({ replaced, evidence: ev, digest, findings: turnNotes.filter((l) => FINDING_RE.test(l)).slice(-8), tasks: cOpts.preservedState, request, answer: answerFirst }));
905
+ restoreOwnerSaid(); // a steer (or the ctrl+y ask) typed during the replaced rounds is the owner's word: it stays
906
+ opts.onLoopCompaction?.({ attempt: loopResets, kind, nudges: ev.nudges, before, after: fullRequestEstimate(conversation.all, cOpts), files: digest.files.length, replaced });
907
+ };
908
+ /** The step a dead-round recovery was waiting for: reported once, with the calls the loop repeated. */
909
+ const proceeded = (forward, answer) => {
910
+ const p = proceedAfter;
911
+ if (!p)
912
+ return;
913
+ proceedAfter = undefined;
914
+ opts.onLoopProceed?.({ attempt: p.attempt, request, repeated: p.repeated, forward, ...(answer ? { answer } : {}) });
915
+ };
916
+ /** A dead round — every call in it refused as a repeat. One recovery from LoopRecovery's budget: the looping rounds (this
917
+ * one and the rounds before it whose every call was one of these, with the warnings between them) become ONE note of what
918
+ * those calls returned and a review directive, and the turn goes on. The budget spent, the turn ends with the loop
919
+ * guard's stop note. The repeat counters keep counting — a call the note already answered is refused again. */
920
+ const recoverDeadRound = (round) => {
921
+ // the dead round's calls, and every other action repeating since the last landed write: an alternating loop is
922
+ // replaced whole, with each member's result in the note
923
+ const fps = new Set([...round.repeats.map((c) => actionFingerprint(c.name, c.args)), ...ledger.repeating(LOOP_GUARD_LIMIT - 1)]);
924
+ const calls = ledger.calls(fps);
925
+ const attempt = recovery.spend();
926
+ if (attempt === undefined) {
927
+ const d = guard?.halt ?? deadRoundStop(calls, Math.max(0, ...round.repeats.map((c) => callCounts.get(callSignature(c.name, c.args)) ?? 0)));
928
+ return stopTurn(loopStopNote({ ...d, message: d.message + (recovery.attempts ? `; ${recovery.attempts} recovery attempts used` : "") }), rounds + 1);
929
+ }
930
+ guard?.resume(); // this batch's halt (a hard limit, a re-worded completed action) is what the recovery answers
931
+ guard?.forgetResults(); // the results it compares against leave the context: a later duplicate is no stub pointing at them
932
+ const run = loopingRun(conversation.all, userInput, (c) => fps.has(actionFingerprint(c.name, c.args)));
933
+ const replaced = conversation.all.length - run.start;
934
+ conversation.replaceAll(conversation.all.slice(0, run.start));
935
+ loopEv.recoveredDeadRound();
936
+ loopReset = undefined; // the note answers the warnings a reset was pending on
937
+ selfLoopStreak = 0;
938
+ thinkSpiralStreak = 0;
939
+ convergeStreak = 0;
940
+ noEditStreak = 0;
941
+ contentSigs.clear();
942
+ const repeated = calls.map((c) => ({ call: c.labels[0], name: c.name, args: c.args, ran: c.ran }));
943
+ engineUser(deadRoundNote({ attempt, max: recovery.max, rounds: run.rounds, calls, request, tasks: opts.preservedState?.(), answer: answerFirst }));
944
+ restoreOwnerSaid(); // a steer typed during the looping rounds survives their rewrite, after the note
945
+ proceedAfter = { attempt, fps, repeated };
946
+ opts.onLoopRecovery?.({ attempt, max: recovery.max, rounds: run.rounds, replaced, repeated });
947
+ return true;
948
+ };
949
+ /** After every settled batch: the ledger learns what ran (a landed write clears it), the step a recovery was waiting for
950
+ * is reported, and a dead round is recovered (true: go to the next round) or ends the turn (its result). */
951
+ const settleRound = (round) => {
952
+ const dead = guardCfg.enabled && round.msgs.length > 0 && round.repeats.length === round.msgs.length;
953
+ if (!dead && proceedAfter) {
954
+ const fps = proceedAfter.fps;
955
+ const forward = round.ran.filter((c) => !fps.has(actionFingerprint(c.name, c.args)) && !refusedResult(c.result) && !resultFailed(c.name, c.result));
956
+ if (forward.length)
957
+ proceeded(forward.map((c) => ({ call: callLabel(c.name, c.args), name: c.name, args: c.args })));
958
+ }
959
+ if (round.ran.some((c) => mutationLanded(c.name, c.result)))
960
+ ledger.clear();
961
+ else
962
+ for (const c of round.ran)
963
+ ledger.ran(actionFingerprint(c.name, c.args), c.name, c.args, c.result);
964
+ for (const c of round.repeats)
965
+ ledger.refused(actionFingerprint(c.name, c.args), c.name, c.args);
966
+ return dead ? recoverDeadRound(round) : undefined;
967
+ };
968
+ /** After ctrl+y and its one next call, a further call does not run: it is recorded as refused (so the next turn knows it
969
+ * was asked for) and the turn ends on the owner's stop, which asks how to go on. */
970
+ const refuseAfterOwnerAct = (content, calls) => {
971
+ conversation.assistant(cleanAssistantProse(content), calls);
972
+ for (const c of calls)
973
+ conversation.tool(c.id, OWNER_ACT_REFUSED);
974
+ return stopTurn(OWNER_ACT_STOP, rounds + 1);
656
975
  };
657
976
  /** Feed one settled tool batch to the converge guard; true ⇒ the turn has stalled and must stop. */
658
977
  const stalledNotConverging = (calls, toolMsgs, content) => {
@@ -672,6 +991,7 @@ export async function runTurn(userInput, conversation, opts) {
672
991
  `from me and no file change that landed, so I'm handing back rather than burn more time. Nothing was lost — ` +
673
992
  `tell me how you'd like to proceed, or ask me to continue and I'll pick up from here with a different approach.]`;
674
993
  };
994
+ const thinkingNow = () => (typeof opts.thinking === "function" ? opts.thinking() : opts.thinking === true);
675
995
  conversation.user(userInput);
676
996
  /** Every mid-turn message the engine injects rides in the user role; the marker is what lets the model tell it from
677
997
  * the owner (continuation.ts, owner-facing turns). */
@@ -687,7 +1007,51 @@ export async function runTurn(userInput, conversation, opts) {
687
1007
  let truncRetries = 0; // chunk-write nudges spent recovering a truncated-tool-call 500 (truncatedToolNudge)
688
1008
  let truncDispatched = 0; // cut-off calls let through to dispatch after the retry budget; a 2nd means the loop isn't converging → hand back
689
1009
  let loadingRetries = 0; // patient waits spent while an endpoint reports it's still (re)loading its model
690
- for (; rounds < absCeiling; rounds++) {
1010
+ opts.onTurnState?.(() => ({ rounds, toolCalls: toolCallTotal, tokens: tokensTotal, loop: loopEv.evidence() }));
1011
+ // What the owner says mid-turn (a steer, the ctrl+y ask) goes in as a plain owner message. A loop rewrite of this turn's
1012
+ // rounds must not lose one: resetLoop replaces every round after the turn's own message, so restoreOwnerSaid puts back,
1013
+ // after the rewrite's note and in the order said, each one no longer there (recoverDeadRound's walk-back already stops
1014
+ // at an owner message; the call there is the same guarantee).
1015
+ const ownerSaid = [];
1016
+ const ownerUser = (text) => { conversation.user(text); ownerSaid.push(text); repliesSinceOwner = 0; };
1017
+ const restoreOwnerSaid = () => {
1018
+ const all = conversation.all;
1019
+ let from = all.length - 1;
1020
+ while (from >= 0 && !(all[from].role === "user" && all[from].content === userInput))
1021
+ from--;
1022
+ const left = new Map();
1023
+ for (const m of all.slice(from + 1))
1024
+ if (m.role === "user")
1025
+ left.set(m.content, (left.get(m.content) ?? 0) + 1);
1026
+ for (const t of ownerSaid) {
1027
+ const n = left.get(t) ?? 0;
1028
+ if (n) {
1029
+ left.set(t, n - 1);
1030
+ continue;
1031
+ }
1032
+ if (t === userInput)
1033
+ continue; // the turn's own words are there
1034
+ conversation.user(t);
1035
+ repliesSinceOwner = 0;
1036
+ }
1037
+ };
1038
+ // ctrl+y (owner-act.ts): 1 = the act round may make its one next call; 2 = any further call ends the turn on the
1039
+ // owner's stop. The rest of the turn runs think-off; the system prompt and tools array are untouched (cache holds).
1040
+ let ownerActStage = 0;
1041
+ const actNow = (phase, actRound, partial) => {
1042
+ if (ownerActStage > 0)
1043
+ return; // one act per turn (OwnerAct refuses later presses; this is the engine's own guard)
1044
+ opts.ownerAct?.acted();
1045
+ const kept = partial ? keptPartial(partial.reasoning, partial.text) : "";
1046
+ if (kept)
1047
+ conversation.assistant(kept); // what it had is kept in context — it answers from that
1048
+ const steered = opts.ownerSteer?.(actRound); // a typed steer IS the owner's message; else the plain ask
1049
+ ownerUser(steered ?? OWNER_ACT_MESSAGE);
1050
+ thinkLatched = true;
1051
+ ownerActStage = 1;
1052
+ opts.onOwnerAct?.({ round: actRound, phase, steered: !!steered });
1053
+ };
1054
+ roundLoop: for (; rounds < absCeiling; rounds++) {
691
1055
  throwIfAborted(opts.signal); // stop before spending another round (covers compaction below too)
692
1056
  const steerMsg = rounds > 0 ? opts.steer?.() : undefined;
693
1057
  if (steerMsg)
@@ -739,12 +1103,11 @@ export async function runTurn(userInput, conversation, opts) {
739
1103
  // stop; a legitimate long read-only task is valid) to convert insight into action or surface a blocker.
740
1104
  if (!noEditNudged && noEditStreak >= NO_EDIT_NUDGE) {
741
1105
  noEditNudged = true;
742
- engineUser(`You've run ${noEditStreak} rounds of tools without changing a file. If you've found the root cause, ` +
743
- `make the change now and verify it. If you're still gathering context that's fine — but if you're ` +
744
- `going in circles, say so and switch to a genuinely different approach.`);
1106
+ loopNudge("no_edit_streak", noEditNudge(noEditStreak));
745
1107
  }
746
- let endpoint = opts.router.select(buildMessages(opts.systemPrompt, conversation.all), opts.toolSchemas);
1108
+ let endpoint = router.select(buildMessages(opts.systemPrompt, conversation.all), opts.toolSchemas);
747
1109
  opts.onRoute?.(endpoint);
1110
+ const failedThisRound = new Set(); // legs (bases) whose request failed in this round's failover
748
1111
  // Endpoint-aware (SPEC §5): rebuild against whichever endpoint is current, since self-heal
749
1112
  // failover below can swap endpoints mid-round and each has its own ctx_window.
750
1113
  const compactionOptsFor = (ep) => ({
@@ -772,6 +1135,12 @@ export async function runTurn(userInput, conversation, opts) {
772
1135
  // route change can send an over-budget request; and since every surface (CLI, web, mobile/RC,
773
1136
  // ACP, headless) drives turns through this one runTurn, compaction is guaranteed fleet-wide.
774
1137
  const cOpts = compactionOptsFor(endpoint);
1138
+ const resetNow = loopReset !== undefined;
1139
+ if (loopReset) {
1140
+ const kind = loopReset;
1141
+ loopReset = undefined;
1142
+ resetLoop(kind, cOpts);
1143
+ }
775
1144
  if (shouldProactivelyCompact(conversation.all, cOpts)) {
776
1145
  // Compact (evict + summarize old turns), then GUARANTEE fit: when the bulk is inside the kept recent
777
1146
  // turns (one turn that dumped huge tool output), fitToWindow elides the largest tool outputs in place
@@ -783,7 +1152,7 @@ export async function runTurn(userInput, conversation, opts) {
783
1152
  const before = fullRequestEstimate(conversation.all, cOpts);
784
1153
  const overWindow = needsCompaction(conversation.all, cOpts);
785
1154
  let skipped = overWindow ? undefined : ceilingSummaryFailed;
786
- const evicted = skipped ? conversation.all : await compact(conversation.all, { ...cOpts, onSkip: (r) => { skipped = r; } });
1155
+ const evicted = skipped ? conversation.all : await compactSignalled(conversation.all, { ...cOpts, onSkip: (r) => { skipped = r; } }, before);
787
1156
  if (!overWindow)
788
1157
  ceilingSummaryFailed = skipped;
789
1158
  conversation.replaceAll(fitToWindow(evicted, cOpts));
@@ -792,8 +1161,8 @@ export async function runTurn(userInput, conversation, opts) {
792
1161
  opts.onCompaction?.({ before, after, ceiling: effectiveCeilingTokens(cOpts), skipped });
793
1162
  // Rehydrate: if compaction actually evicted turns, re-surface the plan + recently-touched files so the
794
1163
  // model re-reads current state instead of acting on the now-summarized (stale) earlier reads.
795
- if (conversation.all.length < beforeLen)
796
- engineUser(rehydrationNote(touchedFiles));
1164
+ if (conversation.all.length < beforeLen && !resetNow)
1165
+ engineUser(rehydrationNote(touchedFiles)); // after a reset its digest is this turn's current account — "re-read everything" would undo it
797
1166
  }
798
1167
  // Intra-turn output-headroom guard (task #14's third leg — _ai-docs 2026-10-19): the proactive gate
799
1168
  // above keeps the PROMPT under threshold, but near the window (or on a small endpoint) the leftover
@@ -821,6 +1190,15 @@ export async function runTurn(userInput, conversation, opts) {
821
1190
  else {
822
1191
  compactionFailStreak = 0;
823
1192
  }
1193
+ // What the owner did while the last round ran goes in now, past every round-top stop, so a steer is never "steered
1194
+ // in" to a round that does not run (review F6): ctrl+y during a tool batch, then a typed steer. Round 1 is the
1195
+ // turn's own message; from its request on, ctrl+y has something to use (opened).
1196
+ if (opts.ownerAct?.consume())
1197
+ actNow("between", rounds + 1);
1198
+ const ownerMsg = rounds > 0 ? opts.ownerSteer?.(rounds + 1) : undefined;
1199
+ if (ownerMsg)
1200
+ ownerUser(ownerMsg);
1201
+ opts.ownerAct?.opened();
824
1202
  const messages = buildMessages(opts.systemPrompt, conversation.all);
825
1203
  // Clamp generation to the room left after the real prompt (incl. tool_calls args + schemas) so a
826
1204
  // deep-session request never overflows the window into a truncated reply. See clampMaxTokens.
@@ -842,13 +1220,14 @@ export async function runTurn(userInput, conversation, opts) {
842
1220
  // sampling to escape it. One-shot — consumed right after this call so the normal path stays greedy.
843
1221
  temperature: retryTempOverride > 0 ? retryTempOverride : opts.temperature,
844
1222
  tools: opts.toolSchemas,
845
- 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
1223
+ thinking: (truncatedThisTurn || thinkLatched) ? false : thinkingNow(), // read LIVE: task #14 truncation latch OR the think-spiral latch disables native reasoning for the rest of the turn
846
1224
  signal: watch.signal,
847
1225
  background: opts.background, // endpoint gate: sub-agents yield the shared slot to the interactive main turn
848
1226
  onDelta: watch.onDelta,
849
1227
  onReasoning: watch.onReasoning,
850
1228
  onServed: opts.onServed,
851
1229
  onPromptProgress: opts.onPromptProgress,
1230
+ owner: opts.owner, onQueued: opts.onQueued, onSent: opts.onSent, onToolDraft: opts.onToolDraft,
852
1231
  });
853
1232
  watch.dispose();
854
1233
  retryTempOverride = 0; // one-shot consumed: this request has read the perturbed temperature
@@ -878,6 +1257,13 @@ export async function runTurn(userInput, conversation, opts) {
878
1257
  }
879
1258
  catch (err) {
880
1259
  watch.dispose();
1260
+ // ctrl+y cut this stream: keep what it had, add the owner's ask, and go straight to the act round (think-off).
1261
+ if (watch.tripped && watch.tripReason === "owner" && !opts.signal?.aborted) {
1262
+ opts.ownerAct?.consume();
1263
+ actNow(watch.armedTrip ? "read" : "stream", rounds + 2, watch.partial);
1264
+ await sleep(OWNER_ACT_SETTLE_MS, opts.signal, () => new TurnAbortedError()); // let the server free the cut slot (owner-act.ts)
1265
+ continue roundLoop;
1266
+ }
881
1267
  // The stream became a runaway repetition loop and the watch tore it down: end the turn here, before any
882
1268
  // retry or continue-nudge could re-seed it. The partial is dropped; history keeps only the marker.
883
1269
  if (watch.tripped && !opts.signal?.aborted)
@@ -909,7 +1295,7 @@ export async function runTurn(userInput, conversation, opts) {
909
1295
  "(python3 -c / bash -c) kept breaking the tool-call JSON. I'll write scripts to a file and run " +
910
1296
  "the file from here. Send your next message and I'll continue.]";
911
1297
  conversation.assistant(msg);
912
- return { content: msg, rounds: rounds + 1, toolCalls: toolCallTotal, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal };
1298
+ return { content: msg, rounds: rounds + 1, toolCalls: toolCallTotal, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal, loop: loopEv.evidence() };
913
1299
  }
914
1300
  truncRetries += 1;
915
1301
  opts.onSelfHeal?.("server_error", truncRetries); // footer ↻ — a recovery is in flight
@@ -947,7 +1333,7 @@ export async function runTurn(userInput, conversation, opts) {
947
1333
  // model that needs no token) can still answer — JL1 over SSH has a locked keychain, so no token loads and
948
1334
  // the gateway says 401 while Cortana sits on localhost. One hop per turn; then fail with the cause.
949
1335
  if (recovery === "auth") {
950
- const next = authFailedOver ? null : opts.router.recover(endpoint, "unavailable");
1336
+ const next = authFailedOver ? null : router.recover(endpoint, "unavailable");
951
1337
  if (next) {
952
1338
  authFailedOver = true;
953
1339
  endpoint = next;
@@ -958,8 +1344,21 @@ export async function runTurn(userInput, conversation, opts) {
958
1344
  }
959
1345
  // Non-retryable: a malformed request (a bad tool call) won't be fixed by resending — fail fast rather
960
1346
  // than spin (that futile-retry storm is what burned minutes).
961
- if (recovery === "bad_request" || selfHealBudget <= 0)
1347
+ if (recovery === "bad_request")
962
1348
  throw err;
1349
+ if (selfHealBudget <= 0) {
1350
+ if (recovery !== "transient")
1351
+ throw err;
1352
+ const failed = { ...serverFailed(endpoint, err) };
1353
+ const fb = takeFallback("server");
1354
+ if (!fb)
1355
+ return unanswered(rounds + 1);
1356
+ opts.onSelfHeal?.("server_error", 1, { failed, next: { kind: "fallback", to: fallback.name } });
1357
+ endpoint = fb;
1358
+ failedThisRound.clear();
1359
+ opts.onRoute?.(endpoint);
1360
+ continue;
1361
+ }
963
1362
  const attempt = MAX_SELF_HEAL_PER_TURN - selfHealBudget; // 0-based
964
1363
  selfHealBudget -= 1;
965
1364
  if (recovery === "context") {
@@ -969,14 +1368,14 @@ export async function runTurn(userInput, conversation, opts) {
969
1368
  // both the routing choice and the compaction below size to the truth, not the roster's lie.
970
1369
  const served = servedContextLimit(err);
971
1370
  if (served !== undefined) {
972
- opts.router.observeContext?.(endpoint, served); // persist the learned window for the rest of the session
1371
+ router.observeContext?.(endpoint, served); // persist the learned window for the rest of the session
973
1372
  if (served < endpoint.ctxWindow)
974
1373
  endpoint = { ...endpoint, ctxWindow: served };
975
1374
  }
976
1375
  opts.onSelfHeal?.("context_exceeded", attempt + 1);
977
1376
  // Prefer a genuinely BIGGER healthy endpoint; ignore a "recovery" that isn't larger (escalate can
978
1377
  // hand back a same-size endpoint, which would just overflow again).
979
- const bigger = opts.router.recover(endpoint, "context_exceeded");
1378
+ const bigger = router.recover(endpoint, "context_exceeded");
980
1379
  if (bigger && bigger.ctxWindow > endpoint.ctxWindow) {
981
1380
  endpoint = bigger;
982
1381
  opts.onRoute?.(endpoint);
@@ -987,7 +1386,7 @@ export async function runTurn(userInput, conversation, opts) {
987
1386
  // eviction alone can't shed. Give up only if we genuinely couldn't shrink the request at all.
988
1387
  const before = conversation.all;
989
1388
  const cOpts = compactionOptsFor(endpoint);
990
- const shrunk = fitToWindow(await compact(before, cOpts), cOpts);
1389
+ const shrunk = fitToWindow(await compactSignalled(before, cOpts, fullRequestEstimate(before, cOpts)), cOpts);
991
1390
  conversation.replaceAll(shrunk);
992
1391
  const chars = (ms) => ms.reduce((n, m) => n + m.content.length, 0);
993
1392
  if (chars(shrunk) >= chars(before))
@@ -996,19 +1395,37 @@ export async function runTurn(userInput, conversation, opts) {
996
1395
  engineUser(rehydrationNote(touchedFiles)); // rehydrate after a forced compaction
997
1396
  continue;
998
1397
  }
999
- // transient (429 / 5xx / network drop): a busy or unhealthy backend, NOT a context problem.
1000
- // Fail over to a healthy endpoint AND back off (exponential + jitter) so we don't storm a server
1001
- // that's already struggling. NEVER compact here — that was the "compacted at 0%" wasted work.
1002
- opts.onSelfHeal?.("server_error", attempt + 1);
1003
- const healthy = opts.router.recover(endpoint, "server_error");
1398
+ // transient (429 / 5xx / network drop / a server error inside a 200): a busy or unhealthy backend, NOT a
1399
+ // context problem. Fail over to a leg not yet tried this round AND back off (exponential + jitter) so we
1400
+ // don't storm a server that's already struggling — two legs can reach the same box. When every leg has
1401
+ // failed, the fallback answers instead of another request to a broken upstream; only a router with one
1402
+ // leg retries it. NEVER compact here — that was the "compacted at 0%" wasted work.
1403
+ const failed = { ...serverFailed(endpoint, err) };
1404
+ failedThisRound.add(endpoint.base);
1405
+ const healthy = router.recover(endpoint, "server_error");
1406
+ if (healthy && failedThisRound.has(healthy.base)) {
1407
+ const fb = takeFallback("server");
1408
+ if (!fb)
1409
+ return unanswered(rounds + 1);
1410
+ opts.onSelfHeal?.("server_error", attempt + 1, { failed, next: { kind: "fallback", to: fallback.name } });
1411
+ endpoint = fb;
1412
+ failedThisRound.clear();
1413
+ opts.onRoute?.(endpoint);
1414
+ continue;
1415
+ }
1416
+ const wait = backoffMs(attempt, err);
1417
+ opts.onSelfHeal?.("server_error", attempt + 1, { failed, next: healthy ? { kind: "leg", host: hostOf(healthy.base) } : { kind: "retry", waitMs: wait } });
1004
1418
  if (healthy) {
1005
1419
  endpoint = healthy;
1006
1420
  opts.onRoute?.(endpoint);
1007
1421
  }
1008
- await sleep(backoffMs(attempt, err), opts.signal, () => new TurnAbortedError());
1422
+ await sleep(wait, opts.signal, () => new TurnAbortedError());
1009
1423
  continue;
1010
1424
  }
1011
1425
  }
1426
+ loopEv.responded(); // the warnings injected before this request have been seen
1427
+ if (response.content?.trim() || response.toolCalls?.length)
1428
+ fallbackLanded();
1012
1429
  // Unrestricted mode (engine/unrestricted.ts, owner's private system): this round's `response` just came
1013
1430
  // back clean (no self-heal error) — if it has no tool calls AND its text/stopReason reads as a
1014
1431
  // POLICY/MORAL refusal (not a capability limit), re-issue the SAME request with an affirmative-prefill
@@ -1039,13 +1456,14 @@ export async function runTurn(userInput, conversation, opts) {
1039
1456
  maxTokens: clampMaxTokens(retryMessages, compactionOptsFor(endpoint), opts.maxTokens ?? 8192),
1040
1457
  temperature: opts.temperature,
1041
1458
  tools: opts.toolSchemas,
1042
- 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
1459
+ thinking: (truncatedThisTurn || thinkLatched) ? false : thinkingNow(), // read LIVE: task #14 truncation latch OR the think-spiral latch disables native reasoning for the rest of the turn
1043
1460
  signal: opts.signal,
1044
1461
  background: opts.background,
1045
1462
  onDelta: opts.onDelta,
1046
1463
  onReasoning: opts.onReasoning,
1047
1464
  onServed: opts.onServed,
1048
1465
  onPromptProgress: opts.onPromptProgress,
1466
+ owner: opts.owner, onQueued: opts.onQueued, onSent: opts.onSent, onToolDraft: opts.onToolDraft,
1049
1467
  });
1050
1468
  }
1051
1469
  }
@@ -1098,7 +1516,7 @@ export async function runTurn(userInput, conversation, opts) {
1098
1516
  "section, then file_edit to append each next part, a few hundred lines per call), or paste the " +
1099
1517
  "content and I'll place it.]";
1100
1518
  conversation.assistant(msg);
1101
- return { content: msg, rounds: rounds + 1, toolCalls: toolCallTotal, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal };
1519
+ return { content: msg, rounds: rounds + 1, toolCalls: toolCallTotal, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal, loop: loopEv.evidence() };
1102
1520
  }
1103
1521
  truncDispatched += 1; // fall through to dispatch; onBadArgs fires the evidence (recovered:false)
1104
1522
  }
@@ -1133,10 +1551,7 @@ export async function runTurn(userInput, conversation, opts) {
1133
1551
  // 09-27). NUDGE it to try something different and CONTINUE; keep counting so a model that ignores
1134
1552
  // the nudge escalates. A bare user-role nudge is safe here (no leak).
1135
1553
  opts.onSelfHeal?.("server_error", seen - CONTENT_LOOP_LIMIT + 1); // footer ↻ — breaking a stall
1136
- engineUser(`You've repeated the same step ${seen}× with the same result — that approach is not working. Do NOT ` +
1137
- `end the turn or ask the owner how to proceed. STOP repeating it and try a genuinely DIFFERENT approach: a ` +
1138
- `different command, tool, path, or angle; if a tool seems broken, work around it. If you already ` +
1139
- `know the fix (you often do — you just described one), do it now.`);
1554
+ loopNudge("repeated_step", repeatedStepNudge(seen));
1140
1555
  continue;
1141
1556
  }
1142
1557
  if (forcedRedirects < CONTENT_LOOP_REDIRECT_MAX) {
@@ -1150,17 +1565,7 @@ export async function runTurn(userInput, conversation, opts) {
1150
1565
  forcedRedirects += 1;
1151
1566
  contentSigs.set(rsig, 0); // fresh runway for this signature after the forced redirect
1152
1567
  opts.onSelfHeal?.("server_error", forcedRedirects); // footer ↻ — a forced self-correction
1153
- engineUser(`You have repeated the SAME step ${seen}× and it is STILL not working — repeating it again will not ` +
1154
- `help. Stop and do this explicitly, in order:\n` +
1155
- `1. In ONE line, state exactly WHAT you keep doing and WHY it isn't making progress (what you ` +
1156
- `expected vs what actually happened).\n` +
1157
- `2. Then pick ONE and do it immediately:\n` +
1158
- ` (a) BREAK IT DOWN — split the stuck step into a smaller, concrete sub-action and do just that ` +
1159
- `one thing now; or\n` +
1160
- ` (b) SWITCH APPROACH — a genuinely different tool, command, path, or order of operations; if a ` +
1161
- `tool or command seems broken, work around it.\n` +
1162
- `Do NOT reproduce your previous output, do NOT end the turn, and do NOT ask me how to proceed — ` +
1163
- `decide and act on the smallest next concrete step.`);
1568
+ loopNudge("repeated_step", repeatedStepRedirect(seen));
1164
1569
  continue;
1165
1570
  }
1166
1571
  // Exhausted the forced redirects on a still-unbroken loop — genuinely intractable. Hand back cleanly
@@ -1179,7 +1584,7 @@ export async function runTurn(userInput, conversation, opts) {
1179
1584
  // fixing (no file edit) and are reasoning HEAVILY — a round that answers or edits never counts. After
1180
1585
  // THINK_SPIRAL_ROUNDS, latch native thinking OFF for the rest of the turn and push the model to act or
1181
1586
  // answer. Reversible (per-turn), never a hard stop.
1182
- if (opts.thinking && !thinkLatched) {
1587
+ if (thinkingNow() && !thinkLatched) {
1183
1588
  const heavyReasoning = (response.reasoningContent?.length ?? 0) >= THINK_SPIRAL_MIN_REASON_CHARS;
1184
1589
  const mutating = response.toolCalls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? ""));
1185
1590
  if (response.toolCalls.length > 0 && !mutating && heavyReasoning) {
@@ -1187,10 +1592,7 @@ export async function runTurn(userInput, conversation, opts) {
1187
1592
  if (thinkSpiralStreak >= THINK_SPIRAL_ROUNDS) {
1188
1593
  thinkLatched = true;
1189
1594
  opts.onSelfHeal?.("server_error", thinkSpiralStreak); // footer ↻ — breaking a reasoning spiral
1190
- engineUser(`You've spent ${thinkSpiralStreak} rounds thinking at length while only polling/reading — no file ` +
1191
- `changed and no answer given. That is a reasoning loop. Stop deliberating: if you know the next ` +
1192
- `concrete action, take it now with a tool; if you have enough to answer, answer directly and ` +
1193
- `concisely. Extended thinking is now off for the rest of this turn.`);
1595
+ loopNudge("reasoning_loop", reasoningLoopNudge(thinkSpiralStreak));
1194
1596
  continue; // re-prompt with thinking disabled; don't dispatch this spiral round's calls
1195
1597
  }
1196
1598
  }
@@ -1204,8 +1606,9 @@ export async function runTurn(userInput, conversation, opts) {
1204
1606
  // round that admits-and-fixes, both pass through untouched. A file edit clears the streak (broke out).
1205
1607
  {
1206
1608
  const mutatingThisRound = response.toolCalls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? ""));
1207
- if (response.toolCalls.length > 0 && !mutatingThisRound && SELF_LOOP_RE.test(response.content)) {
1208
- selfLoopStreak += 1;
1609
+ const admitted = SELF_LOOP_RE.test(response.content);
1610
+ if (response.toolCalls.length > 0 && !mutatingThisRound && (admitted || LOOP_ADMISSION_RE.test(response.content))) {
1611
+ selfLoopStreak = admitted ? selfLoopStreak + 1 : 0; // only SELF_LOOP_RE's admissions build toward the stop
1209
1612
  if (selfLoopStreak >= SELF_LOOP_STOP) {
1210
1613
  const gist = response.content.trim().split("\n").find((l) => l.trim())?.slice(0, 200) ?? "";
1211
1614
  const stuck = `[stopped — I said I was going in circles ${selfLoopStreak}× without making a change that broke ` +
@@ -1213,24 +1616,24 @@ export async function runTurn(userInput, conversation, opts) {
1213
1616
  `to proceed — a different angle, or I can apply the fix I've been circling if you confirm it.]`;
1214
1617
  return stopTurn(stuck, rounds + 1);
1215
1618
  }
1216
- opts.onSelfHeal?.("server_error", selfLoopStreak); // footer ↻ — breaking a self-declared loop
1217
- engineUser(`You just said you're stuck or looping — that is the moment to CHANGE something concrete, not run the ` +
1218
- `same investigation again. If you understand the root cause, apply the fix NOW with file_edit/file_write ` +
1219
- `and verify it. If a tool, path, or approach isn't working, switch to a genuinely different one. If you ` +
1220
- `are truly blocked, STOP and give the owner one line naming exactly what is blocking you and what you would try next.`);
1619
+ opts.onSelfHeal?.("server_error", Math.max(1, selfLoopStreak)); // footer ↻ — breaking a self-declared loop
1620
+ loopNudge("self_loop", SELF_LOOP_NUDGE);
1221
1621
  continue; // let the model act on the nudge; don't dispatch this round's repeated calls
1222
1622
  }
1223
1623
  selfLoopStreak = 0; // a round that fixes, doesn't act, or doesn't admit looping clears the streak
1224
1624
  }
1225
1625
  // Decision points: a build turn's first change, with no direction chosen yet, is held back once so the owner
1226
- // gets a plan + options (ask_user) instead of a silently picked approach. This round's calls are not dispatched.
1626
+ // gets a plan + options (ask_user), or in Autonomous mode a plan review, instead of a silently picked approach.
1627
+ // This round's calls are not dispatched.
1227
1628
  if (response.toolCalls.length > 0 && shouldHoldForDecision({ enabled: decisionGate, buildTurn, askedThisTurn, nudged: decisionNudged, calls: response.toolCalls.map((c) => ({ name: c.function?.name, args: c.function?.arguments })) })) {
1228
1629
  decisionNudged = true;
1229
1630
  if (response.content.trim())
1230
1631
  conversation.assistant(cleanAssistantProse(response.content));
1231
- engineUser(DECISION_POINT_NUDGE);
1632
+ engineUser(decisionNudge);
1232
1633
  continue;
1233
1634
  }
1635
+ if (response.toolCalls.length > 0 && ownerActStage === 2)
1636
+ return refuseAfterOwnerAct(response.content, response.toolCalls);
1234
1637
  if (response.toolCalls.length > 0) {
1235
1638
  throwIfAborted(opts.signal); // don't dispatch a tool batch for a turn the user already cancelled
1236
1639
  // Strip any leaked tool-call/thinking delimiter tags the model emitted into content ALONGSIDE the
@@ -1244,11 +1647,24 @@ export async function runTurn(userInput, conversation, opts) {
1244
1647
  finishReason: response.finishReason, maxTokensSent: lastMaxTokens, promptTokens: response.promptTokens,
1245
1648
  genTokens: response.tokens, endpoint: endpoint.base, model: endpoint.model,
1246
1649
  });
1247
- const toolMsgs = await abortable(runToolCalls(response.toolCalls, opts.tools, callCounts, rca, opts.onToolBatch, onToolStartFx, onToolResultFx, opts.signal, guard, onBadArgs), opts.signal);
1650
+ const round = await abortable(runToolCalls(response.toolCalls, opts.tools, callCounts, rca, opts.onToolBatch, onToolStartFx, onToolResultFx, opts.signal, guard, onBadArgs, opts.onToolCallStart), opts.signal);
1651
+ const toolMsgs = round.msgs;
1248
1652
  for (const tm of capToolRound(toolMsgs))
1249
1653
  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
1250
1654
  observeVerify(verify, response.toolCalls, toolMsgs); // verify-before-done: record mutation / verify signal
1655
+ observeLoop(loopEv, response.toolCalls, toolMsgs);
1656
+ noteNarration(cleanAssistantProse(response.content));
1251
1657
  toolCallTotal += response.toolCalls.length;
1658
+ if (ownerActStage === 1)
1659
+ ownerActStage = 2; // that was the one next call, refused repeat or not
1660
+ const settled = settleRound(round); // a dead round is recovered here (or, past the budget, ends the turn)
1661
+ if (settled === true)
1662
+ continue;
1663
+ if (settled)
1664
+ return settled;
1665
+ const reread = loopEv.staleRereadDue(); // the same unchanged files again: the re-read warning (or, ignored, the reset)
1666
+ if (reread)
1667
+ loopNudge("stale_reread", staleRereadNudge(reread));
1252
1668
  if (guard?.halt) {
1253
1669
  const note = recovery.next(guard.halt);
1254
1670
  if (!note)
@@ -1309,7 +1725,7 @@ export async function runTurn(userInput, conversation, opts) {
1309
1725
  if (nwp.action === "halt")
1310
1726
  return stopTurn(nwp.message, rounds + 1);
1311
1727
  if (nwp.action === "warn") {
1312
- engineUser(nwp.message); // tool messages were already copied into history; mutate neither a stale copy nor the system prompt
1728
+ loopNudge("no_write_progress", nwp.message); // tool messages were already copied into history; mutate neither a stale copy nor the system prompt
1313
1729
  }
1314
1730
  }
1315
1731
  if (stalledNotConverging(response.toolCalls, toolMsgs, response.content))
@@ -1329,17 +1745,32 @@ export async function runTurn(userInput, conversation, opts) {
1329
1745
  decisionNudged = true;
1330
1746
  if (recovered.cleanedContent.trim())
1331
1747
  conversation.assistant(recovered.cleanedContent);
1332
- engineUser(DECISION_POINT_NUDGE);
1748
+ engineUser(decisionNudge);
1333
1749
  continue;
1334
1750
  }
1751
+ if (recovered.calls.length > 0 && ownerActStage === 2)
1752
+ return refuseAfterOwnerAct(recovered.cleanedContent, recovered.calls);
1335
1753
  if (recovered.calls.length > 0) {
1336
1754
  throwIfAborted(opts.signal);
1337
1755
  conversation.assistant(recovered.cleanedContent, recovered.calls);
1338
- const toolMsgs = await abortable(runToolCalls(recovered.calls, opts.tools, callCounts, rca, opts.onToolBatch, onToolStartFx, onToolResultFx, opts.signal, guard), opts.signal);
1756
+ const round = await abortable(runToolCalls(recovered.calls, opts.tools, callCounts, rca, opts.onToolBatch, onToolStartFx, onToolResultFx, opts.signal, guard, undefined, opts.onToolCallStart), opts.signal);
1757
+ const toolMsgs = round.msgs;
1339
1758
  for (const tm of capToolRound(toolMsgs))
1340
1759
  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
1341
1760
  observeVerify(verify, recovered.calls, toolMsgs); // verify-before-done: record mutation / verify signal
1761
+ observeLoop(loopEv, recovered.calls, toolMsgs);
1762
+ noteNarration(recovered.cleanedContent);
1342
1763
  toolCallTotal += recovered.calls.length;
1764
+ if (ownerActStage === 1)
1765
+ ownerActStage = 2; // that was the one next call, refused repeat or not
1766
+ const settled = settleRound(round);
1767
+ if (settled === true)
1768
+ continue;
1769
+ if (settled)
1770
+ return settled;
1771
+ const reread = loopEv.staleRereadDue();
1772
+ if (reread)
1773
+ loopNudge("stale_reread", staleRereadNudge(reread));
1343
1774
  if (guard?.halt) {
1344
1775
  const note = recovery.next(guard.halt);
1345
1776
  if (!note)
@@ -1388,7 +1819,7 @@ export async function runTurn(userInput, conversation, opts) {
1388
1819
  if (nwp.action === "halt")
1389
1820
  return stopTurn(nwp.message, rounds + 1);
1390
1821
  if (nwp.action === "warn") {
1391
- engineUser(nwp.message);
1822
+ loopNudge("no_write_progress", nwp.message);
1392
1823
  continue;
1393
1824
  }
1394
1825
  }
@@ -1415,7 +1846,8 @@ export async function runTurn(userInput, conversation, opts) {
1415
1846
  // TRUNCATION, not a dud. Free output room by compacting, then retry the SAME request. If nothing
1416
1847
  // can be shed, fall through to finalize with the reasoning we did capture.
1417
1848
  const before = conversation.all.length;
1418
- conversation.replaceAll(await compact(conversation.all, compactionOptsFor(endpoint)));
1849
+ const eOpts = compactionOptsFor(endpoint);
1850
+ conversation.replaceAll(await compactSignalled(conversation.all, eOpts, fullRequestEstimate(conversation.all, eOpts)));
1419
1851
  if (conversation.all.length < before)
1420
1852
  continue;
1421
1853
  }
@@ -1437,6 +1869,16 @@ export async function runTurn(userInput, conversation, opts) {
1437
1869
  continue;
1438
1870
  }
1439
1871
  }
1872
+ // Still nothing after the retries — not in the reply, its reasoning, or an earlier empty round's: the model's own
1873
+ // silence. Its fallback answers the rest of this turn; with none, the turn ends saying what was tried.
1874
+ if (!final && response.stopReason !== "length" && !stripScratchpad(response.reasoningContent ?? "") && !stripScratchpad(lastReasoning)) {
1875
+ failedLeg(endpoint, `${emptyRetries + 1} replies with nothing in them`);
1876
+ if (takeFallback("silence", emptyRetries + 1)) {
1877
+ emptyRetries = 0;
1878
+ continue;
1879
+ }
1880
+ return unanswered(rounds + 1);
1881
+ }
1440
1882
  // Turn-continuation: a text-only round whose tail is an unperformed action announcement ("Let me implement
1441
1883
  // these now.") is NOT a finished turn — finalizing here would leave the work undone and make the owner type
1442
1884
  // "continue". Record the model's text, nudge it (user role — real content + tool context exist, so it is
@@ -1488,6 +1930,16 @@ export async function runTurn(userInput, conversation, opts) {
1488
1930
  engineUser(VERIFY_REMINDER);
1489
1931
  continue;
1490
1932
  }
1933
+ // Reported-check gate: an answer that reports a clean type-check or passing tests, in a turn that did work but never ran
1934
+ // that check, gets ONE reminder to run it (11/02: "✅ No TypeScript errors" after vite builds, tsc never run).
1935
+ // only a turn that changed files owes its reported checks: a read-only turn reporting CI or a log is quoting it
1936
+ const unrunChecks = verifyEnabled && final && !isEngineFinal(final) && toolCallTotal > 0 && verify.changedFiles() ? verify.unrun(final) : [];
1937
+ if (unrunChecks.length && !unrunNudged) {
1938
+ unrunNudged = true;
1939
+ conversation.assistant(final);
1940
+ engineUser(unrunCheckReminder(unrunChecks));
1941
+ continue;
1942
+ }
1491
1943
  // Owner-facing: a final that leaves open task-list items with neither a question nor a status is a bare stop —
1492
1944
  // one nudge to continue or to close with a status line per item and ONE steering question.
1493
1945
  if (final && response.stopReason !== "length" && !closingNudged && !opts.background && !isEngineFinal(final) && needsClosingSteer(final, !!opts.preservedState?.())) {
@@ -1497,14 +1949,17 @@ export async function runTurn(userInput, conversation, opts) {
1497
1949
  continue;
1498
1950
  }
1499
1951
  const unverified = verifyEnabled && verify.gate(); // changed files, still no passing check after the nudge
1500
- const answer = (unverified ? NOT_VERIFIED_BANNER : "") +
1952
+ const answer = (unverified ? NOT_VERIFIED_BANNER : unrunChecks.length ? unrunCheckBanner(unrunChecks) : "") +
1501
1953
  (final || stripScratchpad(response.reasoningContent ?? "") || stripScratchpad(lastReasoning) ||
1502
- (response.stopReason === "length"
1503
- ? "(hit the output limit before an answer landed — ask me to continue and I'll pick up where I left off.)"
1504
- : emptyReplyStatus(opts.preservedState?.(), emptyRetries + 1)));
1954
+ "(hit the output limit before an answer landed — ask me to continue and I'll pick up where I left off.)");
1955
+ fallbackLanded(); // an answer from the fallback's reasoning channel
1505
1956
  conversation.assistant(answer);
1957
+ // a recovered loop moved on to an answer: reported here, where the answer is final — an announcement the continuation
1958
+ // check sent back, or a closing the nudge rewrote, never became the step that moved the turn on
1959
+ if (final && !isEngineFinal(final))
1960
+ proceeded([], final);
1506
1961
  const display = final ? undefined : stopQuestion(answer, opts.preservedState?.()); // the engine's own empty/length status, said plainly
1507
- return { content: answer, display, rounds: rounds + 1, toolCalls: toolCallTotal, stopReason: response.stopReason, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal, unverified: unverified || undefined };
1962
+ return { content: answer, display, stopKind: display ? stopKind(answer) : undefined, rounds: rounds + 1, toolCalls: toolCallTotal, stopReason: response.stopReason, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal, unverified: unverified || unrunChecks.length > 0 || undefined, loop: loopEv.evidence() };
1508
1963
  }
1509
1964
  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]`;
1510
1965
  return stopTurn(timeoutMsg, rounds);