@0perator/operator 0.1.351 → 0.1.353
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/acp/agent.js +2 -2
- package/dist/acp/tool-map.js +5 -4
- package/dist/autonomy/delegate.js +54 -1
- package/dist/autonomy/headless.js +2 -0
- package/dist/autonomy/session-factory.js +1 -0
- package/dist/background/index.js +86 -10
- package/dist/background/notices.js +16 -4
- package/dist/cli.js +1073 -177
- package/dist/config/home.js +6 -0
- package/dist/config/memory-sections.js +92 -0
- package/dist/config/persona.js +144 -26
- package/dist/config/settings.js +15 -4
- package/dist/consolidation/scheduler.js +9 -2
- package/dist/consolidation/sleep.js +39 -278
- package/dist/engine/agent.js +444 -76
- package/dist/engine/anthropic-chat.js +13 -2
- package/dist/engine/aurora.js +66 -19
- package/dist/engine/batch-scheduler.js +27 -3
- package/dist/engine/compaction.js +12 -5
- package/dist/engine/continuation.js +14 -12
- package/dist/engine/contract.js +1 -1
- package/dist/engine/decision-points.js +7 -1
- package/dist/engine/front-door.js +59 -0
- package/dist/engine/grandmaster.js +13 -1
- package/dist/engine/loop-guard.js +694 -0
- package/dist/engine/owner-act.js +52 -0
- package/dist/engine/verify-gate.js +52 -0
- package/dist/flywheel/processor.js +3 -1
- package/dist/flywheel/srft.js +8 -4
- package/dist/hooks/index.js +12 -8
- package/dist/mcp/index.js +9 -4
- package/dist/permissions/index.js +32 -11
- package/dist/permissions/modes.js +42 -0
- package/dist/permissions/plan-review.js +100 -0
- package/dist/permissions/policy.js +16 -5
- package/dist/permissions/signature.js +8 -3
- package/dist/remote/safe-commands.js +1 -1
- package/dist/router/read-rates.js +152 -0
- package/dist/selfimprove/backfill.js +174 -0
- package/dist/selfimprove/index.js +146 -57
- package/dist/selfimprove/lessons.js +429 -0
- package/dist/selfimprove/sync.js +58 -0
- package/dist/session.js +362 -33
- package/dist/skills/finder.js +219 -0
- package/dist/toolchain/toolchain.py +528 -112
- package/dist/tools/deferred.js +28 -18
- package/dist/tools/executor.js +7 -3
- package/dist/tools/registry.js +68 -7
- package/dist/tools/result-cap.js +1 -1
- package/dist/ui/ActivitySpinner.js +21 -12
- package/dist/ui/App.js +107 -30
- package/dist/ui/ApprovalPrompt.js +5 -3
- package/dist/ui/ArtifactPicker.js +3 -3
- package/dist/ui/BgPanel.js +105 -5
- package/dist/ui/Composer.js +85 -9
- package/dist/ui/PlanPane.js +72 -8
- package/dist/ui/QuestionPrompt.js +6 -4
- package/dist/ui/SecretPrompt.js +8 -3
- package/dist/ui/SessionPicker.js +2 -2
- package/dist/ui/SkillFinder.js +153 -0
- package/dist/ui/StatusRule.js +5 -2
- package/dist/ui/SummaryCard.js +3 -1
- package/dist/ui/ThinkingSpinner.js +11 -2
- package/dist/ui/ToolBatch.js +11 -2
- package/dist/ui/ToolStep.js +36 -13
- package/dist/ui/Transcript.js +13 -2
- package/dist/ui/actNow.js +61 -0
- package/dist/ui/batchLine.js +165 -0
- package/dist/ui/conversations.js +154 -0
- package/dist/ui/decodeHealth.js +77 -0
- package/dist/ui/expand.js +17 -0
- package/dist/ui/fit.js +40 -0
- package/dist/ui/fitTail.js +14 -0
- package/dist/ui/fold.js +149 -0
- package/dist/ui/format.js +46 -2
- package/dist/ui/liveTools.js +163 -13
- package/dist/ui/modelPicker.js +78 -6
- package/dist/ui/nextStep.js +103 -0
- package/dist/ui/pending.js +57 -0
- package/dist/ui/phase.js +105 -0
- package/dist/ui/planExit.js +0 -5
- package/dist/ui/progressbar.js +4 -26
- package/dist/ui/readForecast.js +44 -0
- package/dist/ui/readProgress.js +119 -0
- package/dist/ui/reportLine.js +62 -0
- package/dist/ui/slashCommands.js +1 -1
- package/dist/ui/theme.js +1 -0
- package/dist/ui/turnFlow.js +72 -0
- package/dist/ui/turnLedger.js +121 -0
- package/dist/ui/turnScope.js +11 -0
- package/dist/util/slash.js +18 -0
- package/package.json +1 -1
package/dist/engine/agent.js
CHANGED
|
@@ -9,12 +9,14 @@ 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
11
|
import { classifyFailure, servedContextLimit, outputCeilingLimit, learnOutputCeiling, learnedOutputCeiling, backoffMs, sleep } from "./selfheal.js";
|
|
12
|
-
import { TaskVerification, VERIFY_REMINDER, NOT_VERIFIED_BANNER } from "./verify-gate.js";
|
|
12
|
+
import { TaskVerification, VERIFY_REMINDER, NOT_VERIFIED_BANNER, unrunCheckBanner, unrunCheckReminder } 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 { LoopRecovery, IDEMPOTENT_TOOLS, LoopGuard, PollSpinGuard, NoWriteProgressGuard, YieldAfterDispatchGuard, loopStopNote, resolveLoopGuardConfig } from "./loop-guard.js";
|
|
15
|
+
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";
|
|
16
|
+
import { inferType } from "./grandmaster.js";
|
|
16
17
|
import { RunawayStreamWatch, ReasoningBudgetWatch, isDegenerateReply, REPETITION_INTERRUPTED, REASONING_BUDGET_INTERRUPTED } from "./repetition-guard.js";
|
|
17
18
|
import { isBetaRefusal, privateBetaMessage } from "../auth/beta.js";
|
|
19
|
+
import { OWNER_ACT_MESSAGE, OWNER_ACT_REFUSED, OWNER_ACT_SETTLE_MS, OWNER_ACT_STOP, keptPartial } from "./owner-act.js";
|
|
18
20
|
const MAX_SELF_HEAL_PER_TURN = 3;
|
|
19
21
|
// A "loading" 503 (endpoint restarting/warming) is a KNOWN-recoverable WAIT, not a failure — a model reload
|
|
20
22
|
// is ~30-90s, far longer than the ≤8s exponential self-heal backoff, so it gets its own patient budget that
|
|
@@ -26,9 +28,12 @@ const LOOP_GUARD_LIMIT = 5; // identical (name+args) calls in a turn before shor
|
|
|
26
28
|
// file is verify-after-fix iteration, not a spin, so it must be unbounded. Only a genuinely repeated call
|
|
27
29
|
// with NO intervening edit (a true no-progress loop) trips this. Raised 3→5 so even a no-edit re-run has
|
|
28
30
|
// 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";
|
|
31
|
+
import { DECISION_POINT_NUDGE, PLAN_REVIEW_NUDGE, isBuildRequest, shouldHoldForDecision } from "./decision-points.js";
|
|
30
32
|
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
|
-
|
|
33
|
+
/** The executor's identical-call refusal, exactly (tools/executor.ts): a tool's own output that merely starts with
|
|
34
|
+
* "loop guard:" (a log, a grep of this source) is real output, not a refusal to be counted and replaced. */
|
|
35
|
+
export const EXECUTOR_REPEAT_REFUSAL = /^loop guard: "[^"]+" called \d+x with identical args this turn/;
|
|
36
|
+
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, stopKind, stripEngineEcho, isEngineFinal } from "./continuation.js";
|
|
32
37
|
// Poll/status tools are meant to be called repeatedly while waiting on async work — NEVER a spin, so the
|
|
33
38
|
// loop guard skips them entirely (agent_status polls sub-agents, bash_output polls a background job).
|
|
34
39
|
const LOOP_GUARD_EXEMPT = new Set(["agent_status", "bash_output"]);
|
|
@@ -103,6 +108,11 @@ const NO_PROGRESS_LIMIT = 8; // consecutive tool batches that return NOTHING new
|
|
|
103
108
|
// only ever NUDGES once (NO_EDIT_NUDGE); it never stops a turn, so a genuine long read-only task is safe.
|
|
104
109
|
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
110
|
const SELF_LOOP_STOP = 3; // model admits it's looping this many rounds (no file edit between) ⇒ graceful stop
|
|
111
|
+
// 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
|
|
112
|
+
// reading without writing", "I keep re-reading the same files" (30+ times in the review loop and both replay arms; matched by
|
|
113
|
+
// none of it). First person only: "Atlas is stuck reading, not writing" is about a sub-agent. These nudge (a loop warning, so
|
|
114
|
+
// ignoring one resets the turn) but never count toward the self-loop STOP, which stays on SELF_LOOP_RE.
|
|
115
|
+
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
116
|
// Converge-or-stop guard: the identical-call guards above can't catch a model that varies its args every round
|
|
107
117
|
// (a different path / pattern / comment each time) yet never answers and never changes a file. This many
|
|
108
118
|
// CONSECUTIVE tool rounds with NO new narration from the model and NO landed file change ⇒ it is not converging:
|
|
@@ -250,6 +260,30 @@ function observeVerify(v, calls, toolMsgs) {
|
|
|
250
260
|
const results = toolMsgs.map((m) => m.content || "");
|
|
251
261
|
v.observe(names, commands, results);
|
|
252
262
|
}
|
|
263
|
+
/** Feed one settled tool batch to the turn's loop evidence (reads, writes), index-aligned like observeVerify. */
|
|
264
|
+
function observeLoop(ev, calls, toolMsgs) {
|
|
265
|
+
calls.forEach((c, i) => {
|
|
266
|
+
let args = {};
|
|
267
|
+
try {
|
|
268
|
+
const a = JSON.parse(c.function.arguments || "{}");
|
|
269
|
+
if (a && typeof a === "object")
|
|
270
|
+
args = a;
|
|
271
|
+
}
|
|
272
|
+
catch { /* unparseable — no targets */ }
|
|
273
|
+
ev.observe(c.function.name, args, toolMsgs[i]?.content ?? "");
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
// A turn the shell starts to deliver a job notice or a sub-agent report serves the LAST request, not the notice.
|
|
277
|
+
function lastRequest(msgs) {
|
|
278
|
+
for (let i = msgs.length - 1; i >= 0; i--) {
|
|
279
|
+
const c = msgs[i].role === "user" && typeof msgs[i].content === "string" ? msgs[i].content : "";
|
|
280
|
+
if (c && !c.startsWith("[engine note") && !c.startsWith("[Compacted summary") && !isSystemNotice(c))
|
|
281
|
+
return servedTask(c);
|
|
282
|
+
}
|
|
283
|
+
return undefined;
|
|
284
|
+
}
|
|
285
|
+
// A line of the model's own narration worth carrying across a loop reset: something it found, fixed or verified.
|
|
286
|
+
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
287
|
/** Thrown by runTurn when the turn is interrupted via AgentOpts.signal (SPEC §9). One type for hosts to catch. */
|
|
254
288
|
export class TurnAbortedError extends Error {
|
|
255
289
|
constructor(reason) {
|
|
@@ -314,7 +348,8 @@ function parseArgs(raw) {
|
|
|
314
348
|
* guard (SPEC §2: identical (name,args) ≥3× this turn is short-circuited) and reporting the
|
|
315
349
|
* batch via onToolBatch with a real (unrounded) duration.
|
|
316
350
|
*/
|
|
317
|
-
async function runToolCalls(toolCalls, tools, callCounts, rca, onToolBatch, onToolStart, onToolResult, signal, guard, onBadArgs)
|
|
351
|
+
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)
|
|
352
|
+
onToolCallStart) {
|
|
318
353
|
// One id for this whole round (SPEC parallel-tool-batch) — every call made here, however it
|
|
319
354
|
// resolves (executed, parse error, loop-guarded), shares it, so a host can box "N tools in
|
|
320
355
|
// parallel" together even for the calls that never reached the executor. Same id-shape idiom as
|
|
@@ -324,11 +359,13 @@ async function runToolCalls(toolCalls, tools, callCounts, rca, onToolBatch, onTo
|
|
|
324
359
|
const batchSize = toolCalls.length;
|
|
325
360
|
const pending = [];
|
|
326
361
|
const preResolved = new Map(); // id -> result, for parse errors + loop-guarded calls
|
|
362
|
+
const refusedById = new Map(); // id -> why it never ran: the guards below, or the executor chain
|
|
327
363
|
const parsedArgs = new Map();
|
|
328
364
|
let loopAbort; // set when a signature blows past LOOP_GUARD_HARD — the turn is aborted (below)
|
|
329
365
|
let loopAbortCompleted = false; // the RCA gate fired: the action already completed, so recovery does not apply
|
|
330
366
|
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
367
|
const guardReplay = new Set(); // calls the identical-args counter refused: one more repeat for the result guard, nothing else
|
|
368
|
+
const repeatIds = new Set(); // calls refused as repeats (identical args, or a re-worded completed action) — a round of only these is dead
|
|
332
369
|
toolCalls.forEach((tc, batchIndex) => {
|
|
333
370
|
const parsed = parseArgs(tc.function.arguments);
|
|
334
371
|
if (!parsed.ok) {
|
|
@@ -342,7 +379,12 @@ async function runToolCalls(toolCalls, tools, callCounts, rca, onToolBatch, onTo
|
|
|
342
379
|
const capped = guard?.beforeCall(tc.function.name, parsed.args);
|
|
343
380
|
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
381
|
preResolved.set(tc.id, `Blocked ${tc.function.name}: ${capped.message}. Work with what you already have and give the user your answer.`);
|
|
382
|
+
refusedById.set(tc.id, "blocked");
|
|
345
383
|
guardSkip.add(tc.id);
|
|
384
|
+
// a replay the result guard knows is futile (the same failure again, a read returning the same again) is a repeat:
|
|
385
|
+
// a round of only these is a dead round, recovered, not a stop. The web and sub-agent caps stay halts.
|
|
386
|
+
if (capped.code === "exact_failure" || capped.code === "no_progress")
|
|
387
|
+
repeatIds.add(tc.id);
|
|
346
388
|
return;
|
|
347
389
|
}
|
|
348
390
|
// Poll/status tools (agent_status, bash_output) are DESIGNED to be called repeatedly with identical
|
|
@@ -366,7 +408,9 @@ async function runToolCalls(toolCalls, tools, callCounts, rca, onToolBatch, onTo
|
|
|
366
408
|
}
|
|
367
409
|
preResolved.set(tc.id, `Loop guard: "${tc.function.name}" already returned your status this turn and it has not changed. Do ` +
|
|
368
410
|
`NOT call it again — answer the user, or ask them what you should do next.`);
|
|
411
|
+
refusedById.set(tc.id, "blocked");
|
|
369
412
|
guardReplay.add(tc.id);
|
|
413
|
+
repeatIds.add(tc.id);
|
|
370
414
|
return;
|
|
371
415
|
}
|
|
372
416
|
if (count >= LOOP_GUARD_LIMIT) { // SPEC §2: short-circuit the Nth identical call (matches executor's guard)
|
|
@@ -379,7 +423,9 @@ async function runToolCalls(toolCalls, tools, callCounts, rca, onToolBatch, onTo
|
|
|
379
423
|
}
|
|
380
424
|
preResolved.set(tc.id, `Loop guard: "${tc.function.name}" has been called ${count} times this turn with identical ` +
|
|
381
425
|
`arguments. Try a different approach instead of repeating this call.`);
|
|
426
|
+
refusedById.set(tc.id, "blocked");
|
|
382
427
|
guardReplay.add(tc.id);
|
|
428
|
+
repeatIds.add(tc.id);
|
|
383
429
|
return;
|
|
384
430
|
}
|
|
385
431
|
// RCA gate (see RCA_STOP above): division of labour with the guard above — EXACT repeats are LOOP_GUARD's
|
|
@@ -396,7 +442,9 @@ async function runToolCalls(toolCalls, tools, callCounts, rca, onToolBatch, onTo
|
|
|
396
442
|
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
443
|
}
|
|
398
444
|
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.`);
|
|
445
|
+
refusedById.set(tc.id, "blocked");
|
|
399
446
|
guardSkip.add(tc.id);
|
|
447
|
+
repeatIds.add(tc.id);
|
|
400
448
|
return;
|
|
401
449
|
}
|
|
402
450
|
pending.push({ id: tc.id, name: tc.function.name, args: parsed.args, batchId, batchSize, batchIndex });
|
|
@@ -413,7 +461,11 @@ async function runToolCalls(toolCalls, tools, callCounts, rca, onToolBatch, onTo
|
|
|
413
461
|
onToolStart?.(pending);
|
|
414
462
|
const started = performance.now();
|
|
415
463
|
const executed = pending.length
|
|
416
|
-
? await tools.executeParallel(pending,
|
|
464
|
+
? await tools.executeParallel(pending, (i, r, why) => {
|
|
465
|
+
if (why)
|
|
466
|
+
refusedById.set(pending[i].id, why);
|
|
467
|
+
onToolResult?.(pending[i].id, r, batchId, why);
|
|
468
|
+
}, signal, onToolCallStart ? (i) => onToolCallStart(pending[i].id, batchId) : undefined)
|
|
417
469
|
: [];
|
|
418
470
|
const durationMs = performance.now() - started;
|
|
419
471
|
const resultById = new Map(preResolved);
|
|
@@ -465,10 +517,42 @@ async function runToolCalls(toolCalls, tools, callCounts, rca, onToolBatch, onTo
|
|
|
465
517
|
batchId,
|
|
466
518
|
batchSize,
|
|
467
519
|
batchIndex,
|
|
520
|
+
...(refusedById.has(tc.id) ? { refused: refusedById.get(tc.id) } : {}),
|
|
468
521
|
}));
|
|
469
522
|
onToolBatch(events, durationMs);
|
|
470
523
|
}
|
|
471
|
-
|
|
524
|
+
pending.forEach((p, i) => { if (EXECUTOR_REPEAT_REFUSAL.test(executed[i] ?? ""))
|
|
525
|
+
repeatIds.add(p.id); }); // the executor's own identical-call guard
|
|
526
|
+
return {
|
|
527
|
+
msgs: toolCalls.map((tc) => ({ role: "tool", content: resultById.get(tc.id) ?? "", tool_call_id: tc.id })),
|
|
528
|
+
repeats: toolCalls.filter((tc) => repeatIds.has(tc.id)).map((tc) => ({ name: tc.function.name, args: parsedArgs.get(tc.id) ?? {} })),
|
|
529
|
+
ran: pending.flatMap((p, i) => (repeatIds.has(p.id) ? [] : [{ name: p.name, args: p.args, result: executed[i] ?? "" }])),
|
|
530
|
+
};
|
|
531
|
+
}
|
|
532
|
+
/** Where a dead round's looping rounds start (runTurn recoverDeadRound). Walking back from the end: every round whose calls
|
|
533
|
+
* are all in the loop, its results, and the loop warnings between those rounds (a loop-family nudge, the self-dialogue
|
|
534
|
+
* nudge) — up to anything else: the turn's own message, an answer, a round with another call, any other engine note (an
|
|
535
|
+
* earlier recovery's note, a reset's digest, a steer). Whole rounds only, so no call is left without its result. */
|
|
536
|
+
function loopingRun(all, userInput, inLoop) {
|
|
537
|
+
let start = all.length;
|
|
538
|
+
let rounds = 0;
|
|
539
|
+
for (let i = all.length - 1; i >= 0; i--) {
|
|
540
|
+
const m = all[i];
|
|
541
|
+
if (m.role === "tool")
|
|
542
|
+
continue;
|
|
543
|
+
const calls = m.role === "assistant" ? m.tool_calls ?? [] : [];
|
|
544
|
+
if (calls.length && calls.every((c) => { const a = parseArgs(c.function?.arguments ?? ""); return inLoop({ name: c.function?.name ?? "", args: a.ok ? a.args : {} }); })) {
|
|
545
|
+
start = i;
|
|
546
|
+
rounds++;
|
|
547
|
+
continue;
|
|
548
|
+
}
|
|
549
|
+
if (m.role === "user" && m.content !== userInput && (loopNudgeKind(m.content) !== undefined || m.content === engineNote(SELF_DIALOGUE_NUDGE))) {
|
|
550
|
+
start = i;
|
|
551
|
+
continue;
|
|
552
|
+
}
|
|
553
|
+
break;
|
|
554
|
+
}
|
|
555
|
+
return { start, rounds };
|
|
472
556
|
}
|
|
473
557
|
// Rehydration (enterprise compaction, continuity half). A compaction summarizes away raw tool outputs — a
|
|
474
558
|
// file the model read 20 turns ago now survives only as a lossy summary, so a later edit can act on STALE
|
|
@@ -505,10 +589,13 @@ export function rehydrationNote(touched) {
|
|
|
505
589
|
}
|
|
506
590
|
/** Streaming half of the repetition guard: wraps the delta callbacks and the abort signal handed to chat() so a
|
|
507
591
|
* 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.
|
|
592
|
+
* streaming until the output cap. A host abort still aborts. `tripped` tells the caller which one it was. The same
|
|
593
|
+
* controller serves ctrl+y (owner-act.ts): a request cuts a live stream at once, or — while the prompt is still being
|
|
594
|
+
* read — arms and cuts on the first token; `partial` is what had streamed, kept for the act round. */
|
|
509
595
|
function watchRepetition(opts, on) {
|
|
510
|
-
|
|
511
|
-
|
|
596
|
+
const owner = opts.ownerAct;
|
|
597
|
+
if (!on && !owner)
|
|
598
|
+
return { signal: opts.signal, onDelta: opts.onDelta, onReasoning: opts.onReasoning, tripped: false, armedTrip: false, partial: { text: "", reasoning: "" }, dispose: () => { } };
|
|
512
599
|
const ctl = new AbortController();
|
|
513
600
|
const link = () => ctl.abort();
|
|
514
601
|
if (opts.signal?.aborted)
|
|
@@ -518,32 +605,59 @@ function watchRepetition(opts, on) {
|
|
|
518
605
|
const text = new RunawayStreamWatch();
|
|
519
606
|
const thought = new RunawayStreamWatch(); // reasoning that REPEATS a fragment
|
|
520
607
|
const thoughtBudget = new ReasoningBudgetWatch(); // reasoning that goes LONG without acting ("in circles")
|
|
608
|
+
let streamed = false;
|
|
609
|
+
let armed = false; // ctrl+y while the server still reads the prompt: cut on the first token, so the read is not wasted
|
|
521
610
|
const w = {
|
|
522
611
|
signal: ctl.signal,
|
|
523
612
|
tripped: false,
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
613
|
+
armedTrip: false,
|
|
614
|
+
partial: { text: "", reasoning: "" },
|
|
615
|
+
onDelta: (c) => {
|
|
616
|
+
opts.onDelta?.(c);
|
|
617
|
+
if (owner)
|
|
618
|
+
w.partial.text += c;
|
|
619
|
+
streamed = true;
|
|
620
|
+
if (w.tripped)
|
|
621
|
+
return;
|
|
622
|
+
if (armed) {
|
|
623
|
+
w.armedTrip = true;
|
|
624
|
+
trip("owner");
|
|
625
|
+
return;
|
|
626
|
+
}
|
|
627
|
+
if (on && text.feed(c))
|
|
628
|
+
trip("repetition");
|
|
629
|
+
},
|
|
529
630
|
onReasoning: (c) => {
|
|
530
631
|
opts.onReasoning?.(c);
|
|
632
|
+
if (owner)
|
|
633
|
+
w.partial.reasoning += c;
|
|
634
|
+
streamed = true;
|
|
531
635
|
if (w.tripped)
|
|
532
636
|
return;
|
|
533
|
-
if (
|
|
534
|
-
w.
|
|
535
|
-
|
|
536
|
-
ctl.abort();
|
|
637
|
+
if (armed) {
|
|
638
|
+
w.armedTrip = true;
|
|
639
|
+
trip("owner");
|
|
537
640
|
return;
|
|
538
641
|
}
|
|
539
|
-
if (
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
642
|
+
if (!on)
|
|
643
|
+
return;
|
|
644
|
+
if (thought.feed(c)) {
|
|
645
|
+
trip("repetition");
|
|
646
|
+
return;
|
|
543
647
|
}
|
|
648
|
+
if (thoughtBudget.feed(c))
|
|
649
|
+
trip("budget");
|
|
544
650
|
},
|
|
545
|
-
dispose: () => opts.signal?.removeEventListener("abort", link),
|
|
651
|
+
dispose: () => { opts.signal?.removeEventListener("abort", link); owner?.listen(undefined); },
|
|
546
652
|
};
|
|
653
|
+
const trip = (why) => { w.tripped = true; w.tripReason = why; ctl.abort(); };
|
|
654
|
+
owner?.listen(() => { if (w.tripped)
|
|
655
|
+
return; if (streamed)
|
|
656
|
+
trip("owner");
|
|
657
|
+
else
|
|
658
|
+
armed = true; });
|
|
659
|
+
if (owner?.pending())
|
|
660
|
+
armed = true; // asked for in the gap between the round's top and this request
|
|
547
661
|
return w;
|
|
548
662
|
}
|
|
549
663
|
/** Runs one user turn to completion: compacts, loops model↔tools ≤maxRounds, self-heals, finalizes. */
|
|
@@ -563,6 +677,22 @@ export function authError(err, base) {
|
|
|
563
677
|
return new Error(`${msg}\n${why}; or set a failover endpoint that needs no token (settings endpoints.failover)`);
|
|
564
678
|
}
|
|
565
679
|
export async function runTurn(userInput, conversation, opts) {
|
|
680
|
+
// One compact() with its host signals around the summarizer round-trip — the slow part a UI shows. A compact() with
|
|
681
|
+
// nothing to evict calls no summarizer and signals nothing, so a host never flashes a compaction that did not happen.
|
|
682
|
+
const compactSignalled = async (msgs, cOpts, before) => {
|
|
683
|
+
let started = false;
|
|
684
|
+
const summarize = async (span) => {
|
|
685
|
+
if (!started) {
|
|
686
|
+
started = true;
|
|
687
|
+
opts.onCompactionStart?.({ before });
|
|
688
|
+
}
|
|
689
|
+
return cOpts.summarize(span);
|
|
690
|
+
};
|
|
691
|
+
const out = await compact(msgs, { ...cOpts, summarize });
|
|
692
|
+
if (started)
|
|
693
|
+
opts.onCompactionEnd?.({ before, after: fullRequestEstimate(out, cOpts) });
|
|
694
|
+
return out;
|
|
695
|
+
};
|
|
566
696
|
const softRounds = opts.maxRounds ?? 10;
|
|
567
697
|
const absCeiling = Math.max(softRounds + 1, opts.maxRoundsHard ?? 400); // absolute safety stop; progress-aware below
|
|
568
698
|
const turnStart = Date.now(); // for the per-turn wall-clock budget (opts.maxTurnWallClockMs) — the only bound on TIME
|
|
@@ -574,6 +704,25 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
574
704
|
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
705
|
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
706
|
const rca = { succeeded: new Map(), refused: new Map() }; // normalized-fingerprint → completed exact spellings; + refusal tally (see RCA_STOP)
|
|
707
|
+
// Loop reset (loop-guard.ts "Loop evidence"): every loop-family nudge is counted; the Nth one the model has seen and
|
|
708
|
+
// answered with no landed write since, while the turn repeats itself (a warning ignored), is not injected — before
|
|
709
|
+
// the next request this turn's rounds become ONE digest note (what it read, with the latest output of each file;
|
|
710
|
+
// what it changed; its findings; the next action). Deterministic, no model call; earlier turns are untouched.
|
|
711
|
+
// Bounded per turn; past it the nudges go in as before (interactive warns, unattended keeps the hard stop and
|
|
712
|
+
// LoopRecovery).
|
|
713
|
+
const loopEv = new LoopEvidenceTracker();
|
|
714
|
+
const loopResetOn = guardCfg.enabled && guardCfg.compactAfterNudges > 0;
|
|
715
|
+
let loopReset; // a reset is due before the next request
|
|
716
|
+
let loopResets = 0;
|
|
717
|
+
const request = opts.request ?? (isSystemNotice(userInput) ? lastRequest(conversation.all) ?? userInput : servedTask(userInput));
|
|
718
|
+
const answerFirst = ["review", "search", "research", "plan"].includes(inferType(request));
|
|
719
|
+
const turnNotes = []; // the model's own narration this turn (first lines, deduped) — its findings survive a reset
|
|
720
|
+
const noteSigs = new Set();
|
|
721
|
+
// Dead rounds (loop-guard.ts "Dead rounds"): a round whose every call was refused as a repeat is recovered — the looping
|
|
722
|
+
// rounds become ONE note of what those calls returned (the ledger) and a review directive — and the turn goes on, within
|
|
723
|
+
// LoopRecovery's budget. The step that follows a recovery is reported once (the mentor pair's second half).
|
|
724
|
+
const ledger = new CallLedger();
|
|
725
|
+
let proceedAfter;
|
|
577
726
|
const contentSigs = new Map(); // per-round prose fingerprints → the narration loop guard
|
|
578
727
|
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
728
|
let progressed = true; // did the PREVIOUS tool batch advance? gates the guard (progress clears it)
|
|
@@ -596,6 +745,7 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
596
745
|
const verifyEnabled = opts.verifyGate?.enabled !== false;
|
|
597
746
|
const verifyMaxNudges = Math.max(0, opts.verifyGate?.maxNudges ?? 1);
|
|
598
747
|
let verifyNudges = 0;
|
|
748
|
+
let unrunNudged = false; // the reported-check reminder fires at most once per turn
|
|
599
749
|
const unrestrictedEnabled = opts.unrestricted !== false; // default on — owner's private system
|
|
600
750
|
// 0perator Computer feed (opt-in, additive): when the host wants a typed action stream, compose the two
|
|
601
751
|
// tool callbacks here so runToolCalls stays untouched. The tracker pushes normalized start/end events into
|
|
@@ -611,7 +761,7 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
611
761
|
const origStart = opts.onToolStart;
|
|
612
762
|
const origResult = opts.onToolResult;
|
|
613
763
|
onToolStartFx = (calls) => { origStart?.(calls); ceTracker.onToolStart(calls); };
|
|
614
|
-
onToolResultFx = (id, result, batchId) => { origResult?.(id, result, batchId); ceTracker.onToolResult(id, result); };
|
|
764
|
+
onToolResultFx = (id, result, batchId, refused) => { origResult?.(id, result, batchId, refused); ceTracker.onToolResult(id, result); };
|
|
615
765
|
}
|
|
616
766
|
// Turn-continuation: nudge a model that ends on an unperformed action announcement to actually do it (bounded).
|
|
617
767
|
const continuationEnabled = opts.turnContinuation?.enabled !== false && (opts.toolSchemas?.length ?? 0) > 0;
|
|
@@ -625,9 +775,10 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
625
775
|
let lastReasoning = ""; // the reasoning channel of an empty round — a model that answers there still answered
|
|
626
776
|
const hasAskTool = (opts.toolSchemas ?? []).some((s) => s?.function?.name === "ask_user");
|
|
627
777
|
const decisionGate = opts.decisionPoints?.enabled === true && hasAskTool;
|
|
628
|
-
const buildTurn = decisionGate && isBuildRequest(userInput);
|
|
778
|
+
const buildTurn = decisionGate && isBuildRequest(opts.ownerText ?? userInput);
|
|
629
779
|
let askedThisTurn = false; // ask_user ran this turn — the owner already chose a direction
|
|
630
780
|
let decisionNudged = false; // the decision-point hold fires at most once per turn
|
|
781
|
+
const decisionNudge = opts.decisionPoints?.planReview === true ? PLAN_REVIEW_NUDGE : DECISION_POINT_NUDGE; // Autonomous: a plan review replaces the options
|
|
631
782
|
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
783
|
let emptyNudged = false; // the reframe nudge goes in on the FIRST genuine empty, whatever the retry counter says
|
|
633
784
|
let malformedCallNudges = 0; // bounded re-prompts for an unparseable text tool call
|
|
@@ -652,7 +803,128 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
652
803
|
const stopTurn = (note, roundsRun, stopReason) => {
|
|
653
804
|
const text = closeStopNote(note, opts.preservedState?.()); // never a bare stop: the open items + how to steer
|
|
654
805
|
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 };
|
|
806
|
+
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() };
|
|
807
|
+
};
|
|
808
|
+
/** A loop-family nudge: injected, or — when it is the Nth ignored one — replaced by a loop reset before the next
|
|
809
|
+
* request. While a reset is pending, further nudges are absorbed: its note supersedes them. */
|
|
810
|
+
const loopNudge = (kind, text) => {
|
|
811
|
+
const { unheeded, repeating } = loopEv.nudge(kind);
|
|
812
|
+
if (loopReset)
|
|
813
|
+
return;
|
|
814
|
+
if (loopResetOn && repeating && unheeded >= guardCfg.compactAfterNudges && loopResets < guardCfg.maxLoopCompactions) {
|
|
815
|
+
loopReset = kind;
|
|
816
|
+
return;
|
|
817
|
+
}
|
|
818
|
+
engineUser(text);
|
|
819
|
+
};
|
|
820
|
+
const noteNarration = (content) => {
|
|
821
|
+
const line = content.split("\n").map((l) => l.trim()).find(Boolean) ?? "";
|
|
822
|
+
const sig = contentSignature(line);
|
|
823
|
+
if (!sig || noteSigs.has(sig) || /^(?:you'?re right|good point)\b/i.test(line))
|
|
824
|
+
return;
|
|
825
|
+
noteSigs.add(sig);
|
|
826
|
+
turnNotes.push(line.length > 200 ? line.slice(0, 200) + "…" : line);
|
|
827
|
+
};
|
|
828
|
+
/** The reset itself — deterministic, no model call: this turn's rounds (everything after the turn's own message) become
|
|
829
|
+
* ONE engine note built from what the engine saw them do (loopRecoveryNote). Earlier turns stay as they are; the
|
|
830
|
+
* proactive compaction right after it handles their size under the normal rules. The repeat counters that compared
|
|
831
|
+
* against the replaced results start over, so the one re-read the note allows comes back whole. */
|
|
832
|
+
const resetLoop = (kind, cOpts) => {
|
|
833
|
+
loopResets++;
|
|
834
|
+
const ev = loopEv.evidence();
|
|
835
|
+
const digest = loopEv.digest();
|
|
836
|
+
const before = fullRequestEstimate(conversation.all, cOpts);
|
|
837
|
+
const all = conversation.all;
|
|
838
|
+
let start = all.length - 1;
|
|
839
|
+
while (start >= 0 && !(all[start].role === "user" && all[start].content === userInput))
|
|
840
|
+
start--;
|
|
841
|
+
const replaced = start >= 0 ? all.length - start - 1 : 0;
|
|
842
|
+
if (replaced > 0) {
|
|
843
|
+
conversation.replaceAll(all.slice(0, start + 1));
|
|
844
|
+
callCounts.clear();
|
|
845
|
+
rca.succeeded.clear();
|
|
846
|
+
rca.refused.clear();
|
|
847
|
+
guard?.forgetResults();
|
|
848
|
+
touchedFiles.length = 0; // the digest carries them; a later rehydration note must not send the model back to them
|
|
849
|
+
}
|
|
850
|
+
loopEv.recovered(replaced > 0);
|
|
851
|
+
// A fresh runway: the streaks that would re-nudge or stop this turn count again from the reset.
|
|
852
|
+
selfLoopStreak = 0;
|
|
853
|
+
thinkSpiralStreak = 0;
|
|
854
|
+
convergeStreak = 0;
|
|
855
|
+
noEditStreak = 0;
|
|
856
|
+
contentSigs.clear();
|
|
857
|
+
engineUser(loopRecoveryNote({ replaced, evidence: ev, digest, findings: turnNotes.filter((l) => FINDING_RE.test(l)).slice(-8), tasks: cOpts.preservedState, request, answer: answerFirst }));
|
|
858
|
+
restoreOwnerSaid(); // a steer (or the ctrl+y ask) typed during the replaced rounds is the owner's word: it stays
|
|
859
|
+
opts.onLoopCompaction?.({ attempt: loopResets, kind, nudges: ev.nudges, before, after: fullRequestEstimate(conversation.all, cOpts), files: digest.files.length, replaced });
|
|
860
|
+
};
|
|
861
|
+
/** The step a dead-round recovery was waiting for: reported once, with the calls the loop repeated. */
|
|
862
|
+
const proceeded = (forward, answer) => {
|
|
863
|
+
const p = proceedAfter;
|
|
864
|
+
if (!p)
|
|
865
|
+
return;
|
|
866
|
+
proceedAfter = undefined;
|
|
867
|
+
opts.onLoopProceed?.({ attempt: p.attempt, request, repeated: p.repeated, forward, ...(answer ? { answer } : {}) });
|
|
868
|
+
};
|
|
869
|
+
/** A dead round — every call in it refused as a repeat. One recovery from LoopRecovery's budget: the looping rounds (this
|
|
870
|
+
* one and the rounds before it whose every call was one of these, with the warnings between them) become ONE note of what
|
|
871
|
+
* those calls returned and a review directive, and the turn goes on. The budget spent, the turn ends with the loop
|
|
872
|
+
* guard's stop note. The repeat counters keep counting — a call the note already answered is refused again. */
|
|
873
|
+
const recoverDeadRound = (round) => {
|
|
874
|
+
// the dead round's calls, and every other action repeating since the last landed write: an alternating loop is
|
|
875
|
+
// replaced whole, with each member's result in the note
|
|
876
|
+
const fps = new Set([...round.repeats.map((c) => actionFingerprint(c.name, c.args)), ...ledger.repeating(LOOP_GUARD_LIMIT - 1)]);
|
|
877
|
+
const calls = ledger.calls(fps);
|
|
878
|
+
const attempt = recovery.spend();
|
|
879
|
+
if (attempt === undefined) {
|
|
880
|
+
const d = guard?.halt ?? deadRoundStop(calls, Math.max(0, ...round.repeats.map((c) => callCounts.get(callSignature(c.name, c.args)) ?? 0)));
|
|
881
|
+
return stopTurn(loopStopNote({ ...d, message: d.message + (recovery.attempts ? `; ${recovery.attempts} recovery attempts used` : "") }), rounds + 1);
|
|
882
|
+
}
|
|
883
|
+
guard?.resume(); // this batch's halt (a hard limit, a re-worded completed action) is what the recovery answers
|
|
884
|
+
guard?.forgetResults(); // the results it compares against leave the context: a later duplicate is no stub pointing at them
|
|
885
|
+
const run = loopingRun(conversation.all, userInput, (c) => fps.has(actionFingerprint(c.name, c.args)));
|
|
886
|
+
const replaced = conversation.all.length - run.start;
|
|
887
|
+
conversation.replaceAll(conversation.all.slice(0, run.start));
|
|
888
|
+
loopEv.recoveredDeadRound();
|
|
889
|
+
loopReset = undefined; // the note answers the warnings a reset was pending on
|
|
890
|
+
selfLoopStreak = 0;
|
|
891
|
+
thinkSpiralStreak = 0;
|
|
892
|
+
convergeStreak = 0;
|
|
893
|
+
noEditStreak = 0;
|
|
894
|
+
contentSigs.clear();
|
|
895
|
+
const repeated = calls.map((c) => ({ call: c.labels[0], name: c.name, args: c.args, ran: c.ran }));
|
|
896
|
+
engineUser(deadRoundNote({ attempt, max: recovery.max, rounds: run.rounds, calls, request, tasks: opts.preservedState?.(), answer: answerFirst }));
|
|
897
|
+
restoreOwnerSaid(); // a steer typed during the looping rounds survives their rewrite, after the note
|
|
898
|
+
proceedAfter = { attempt, fps, repeated };
|
|
899
|
+
opts.onLoopRecovery?.({ attempt, max: recovery.max, rounds: run.rounds, replaced, repeated });
|
|
900
|
+
return true;
|
|
901
|
+
};
|
|
902
|
+
/** After every settled batch: the ledger learns what ran (a landed write clears it), the step a recovery was waiting for
|
|
903
|
+
* is reported, and a dead round is recovered (true: go to the next round) or ends the turn (its result). */
|
|
904
|
+
const settleRound = (round) => {
|
|
905
|
+
const dead = guardCfg.enabled && round.msgs.length > 0 && round.repeats.length === round.msgs.length;
|
|
906
|
+
if (!dead && proceedAfter) {
|
|
907
|
+
const fps = proceedAfter.fps;
|
|
908
|
+
const forward = round.ran.filter((c) => !fps.has(actionFingerprint(c.name, c.args)) && !refusedResult(c.result) && !resultFailed(c.name, c.result));
|
|
909
|
+
if (forward.length)
|
|
910
|
+
proceeded(forward.map((c) => ({ call: callLabel(c.name, c.args), name: c.name, args: c.args })));
|
|
911
|
+
}
|
|
912
|
+
if (round.ran.some((c) => mutationLanded(c.name, c.result)))
|
|
913
|
+
ledger.clear();
|
|
914
|
+
else
|
|
915
|
+
for (const c of round.ran)
|
|
916
|
+
ledger.ran(actionFingerprint(c.name, c.args), c.name, c.args, c.result);
|
|
917
|
+
for (const c of round.repeats)
|
|
918
|
+
ledger.refused(actionFingerprint(c.name, c.args), c.name, c.args);
|
|
919
|
+
return dead ? recoverDeadRound(round) : undefined;
|
|
920
|
+
};
|
|
921
|
+
/** 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
|
|
922
|
+
* was asked for) and the turn ends on the owner's stop, which asks how to go on. */
|
|
923
|
+
const refuseAfterOwnerAct = (content, calls) => {
|
|
924
|
+
conversation.assistant(cleanAssistantProse(content), calls);
|
|
925
|
+
for (const c of calls)
|
|
926
|
+
conversation.tool(c.id, OWNER_ACT_REFUSED);
|
|
927
|
+
return stopTurn(OWNER_ACT_STOP, rounds + 1);
|
|
656
928
|
};
|
|
657
929
|
/** Feed one settled tool batch to the converge guard; true ⇒ the turn has stalled and must stop. */
|
|
658
930
|
const stalledNotConverging = (calls, toolMsgs, content) => {
|
|
@@ -672,6 +944,7 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
672
944
|
`from me and no file change that landed, so I'm handing back rather than burn more time. Nothing was lost — ` +
|
|
673
945
|
`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
946
|
};
|
|
947
|
+
const thinkingNow = () => (typeof opts.thinking === "function" ? opts.thinking() : opts.thinking === true);
|
|
675
948
|
conversation.user(userInput);
|
|
676
949
|
/** Every mid-turn message the engine injects rides in the user role; the marker is what lets the model tell it from
|
|
677
950
|
* the owner (continuation.ts, owner-facing turns). */
|
|
@@ -687,7 +960,51 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
687
960
|
let truncRetries = 0; // chunk-write nudges spent recovering a truncated-tool-call 500 (truncatedToolNudge)
|
|
688
961
|
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
962
|
let loadingRetries = 0; // patient waits spent while an endpoint reports it's still (re)loading its model
|
|
690
|
-
|
|
963
|
+
opts.onTurnState?.(() => ({ rounds, toolCalls: toolCallTotal, tokens: tokensTotal, loop: loopEv.evidence() }));
|
|
964
|
+
// 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
|
|
965
|
+
// rounds must not lose one: resetLoop replaces every round after the turn's own message, so restoreOwnerSaid puts back,
|
|
966
|
+
// after the rewrite's note and in the order said, each one no longer there (recoverDeadRound's walk-back already stops
|
|
967
|
+
// at an owner message; the call there is the same guarantee).
|
|
968
|
+
const ownerSaid = [];
|
|
969
|
+
const ownerUser = (text) => { conversation.user(text); ownerSaid.push(text); repliesSinceOwner = 0; };
|
|
970
|
+
const restoreOwnerSaid = () => {
|
|
971
|
+
const all = conversation.all;
|
|
972
|
+
let from = all.length - 1;
|
|
973
|
+
while (from >= 0 && !(all[from].role === "user" && all[from].content === userInput))
|
|
974
|
+
from--;
|
|
975
|
+
const left = new Map();
|
|
976
|
+
for (const m of all.slice(from + 1))
|
|
977
|
+
if (m.role === "user")
|
|
978
|
+
left.set(m.content, (left.get(m.content) ?? 0) + 1);
|
|
979
|
+
for (const t of ownerSaid) {
|
|
980
|
+
const n = left.get(t) ?? 0;
|
|
981
|
+
if (n) {
|
|
982
|
+
left.set(t, n - 1);
|
|
983
|
+
continue;
|
|
984
|
+
}
|
|
985
|
+
if (t === userInput)
|
|
986
|
+
continue; // the turn's own words are there
|
|
987
|
+
conversation.user(t);
|
|
988
|
+
repliesSinceOwner = 0;
|
|
989
|
+
}
|
|
990
|
+
};
|
|
991
|
+
// ctrl+y (owner-act.ts): 1 = the act round may make its one next call; 2 = any further call ends the turn on the
|
|
992
|
+
// owner's stop. The rest of the turn runs think-off; the system prompt and tools array are untouched (cache holds).
|
|
993
|
+
let ownerActStage = 0;
|
|
994
|
+
const actNow = (phase, actRound, partial) => {
|
|
995
|
+
if (ownerActStage > 0)
|
|
996
|
+
return; // one act per turn (OwnerAct refuses later presses; this is the engine's own guard)
|
|
997
|
+
opts.ownerAct?.acted();
|
|
998
|
+
const kept = partial ? keptPartial(partial.reasoning, partial.text) : "";
|
|
999
|
+
if (kept)
|
|
1000
|
+
conversation.assistant(kept); // what it had is kept in context — it answers from that
|
|
1001
|
+
const steered = opts.ownerSteer?.(actRound); // a typed steer IS the owner's message; else the plain ask
|
|
1002
|
+
ownerUser(steered ?? OWNER_ACT_MESSAGE);
|
|
1003
|
+
thinkLatched = true;
|
|
1004
|
+
ownerActStage = 1;
|
|
1005
|
+
opts.onOwnerAct?.({ round: actRound, phase, steered: !!steered });
|
|
1006
|
+
};
|
|
1007
|
+
roundLoop: for (; rounds < absCeiling; rounds++) {
|
|
691
1008
|
throwIfAborted(opts.signal); // stop before spending another round (covers compaction below too)
|
|
692
1009
|
const steerMsg = rounds > 0 ? opts.steer?.() : undefined;
|
|
693
1010
|
if (steerMsg)
|
|
@@ -739,9 +1056,7 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
739
1056
|
// stop; a legitimate long read-only task is valid) to convert insight into action or surface a blocker.
|
|
740
1057
|
if (!noEditNudged && noEditStreak >= NO_EDIT_NUDGE) {
|
|
741
1058
|
noEditNudged = true;
|
|
742
|
-
|
|
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.`);
|
|
1059
|
+
loopNudge("no_edit_streak", noEditNudge(noEditStreak));
|
|
745
1060
|
}
|
|
746
1061
|
let endpoint = opts.router.select(buildMessages(opts.systemPrompt, conversation.all), opts.toolSchemas);
|
|
747
1062
|
opts.onRoute?.(endpoint);
|
|
@@ -772,6 +1087,12 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
772
1087
|
// route change can send an over-budget request; and since every surface (CLI, web, mobile/RC,
|
|
773
1088
|
// ACP, headless) drives turns through this one runTurn, compaction is guaranteed fleet-wide.
|
|
774
1089
|
const cOpts = compactionOptsFor(endpoint);
|
|
1090
|
+
const resetNow = loopReset !== undefined;
|
|
1091
|
+
if (loopReset) {
|
|
1092
|
+
const kind = loopReset;
|
|
1093
|
+
loopReset = undefined;
|
|
1094
|
+
resetLoop(kind, cOpts);
|
|
1095
|
+
}
|
|
775
1096
|
if (shouldProactivelyCompact(conversation.all, cOpts)) {
|
|
776
1097
|
// Compact (evict + summarize old turns), then GUARANTEE fit: when the bulk is inside the kept recent
|
|
777
1098
|
// turns (one turn that dumped huge tool output), fitToWindow elides the largest tool outputs in place
|
|
@@ -783,7 +1104,7 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
783
1104
|
const before = fullRequestEstimate(conversation.all, cOpts);
|
|
784
1105
|
const overWindow = needsCompaction(conversation.all, cOpts);
|
|
785
1106
|
let skipped = overWindow ? undefined : ceilingSummaryFailed;
|
|
786
|
-
const evicted = skipped ? conversation.all : await
|
|
1107
|
+
const evicted = skipped ? conversation.all : await compactSignalled(conversation.all, { ...cOpts, onSkip: (r) => { skipped = r; } }, before);
|
|
787
1108
|
if (!overWindow)
|
|
788
1109
|
ceilingSummaryFailed = skipped;
|
|
789
1110
|
conversation.replaceAll(fitToWindow(evicted, cOpts));
|
|
@@ -792,8 +1113,8 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
792
1113
|
opts.onCompaction?.({ before, after, ceiling: effectiveCeilingTokens(cOpts), skipped });
|
|
793
1114
|
// Rehydrate: if compaction actually evicted turns, re-surface the plan + recently-touched files so the
|
|
794
1115
|
// 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));
|
|
1116
|
+
if (conversation.all.length < beforeLen && !resetNow)
|
|
1117
|
+
engineUser(rehydrationNote(touchedFiles)); // after a reset its digest is this turn's current account — "re-read everything" would undo it
|
|
797
1118
|
}
|
|
798
1119
|
// Intra-turn output-headroom guard (task #14's third leg — _ai-docs 2026-10-19): the proactive gate
|
|
799
1120
|
// above keeps the PROMPT under threshold, but near the window (or on a small endpoint) the leftover
|
|
@@ -821,6 +1142,15 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
821
1142
|
else {
|
|
822
1143
|
compactionFailStreak = 0;
|
|
823
1144
|
}
|
|
1145
|
+
// What the owner did while the last round ran goes in now, past every round-top stop, so a steer is never "steered
|
|
1146
|
+
// in" to a round that does not run (review F6): ctrl+y during a tool batch, then a typed steer. Round 1 is the
|
|
1147
|
+
// turn's own message; from its request on, ctrl+y has something to use (opened).
|
|
1148
|
+
if (opts.ownerAct?.consume())
|
|
1149
|
+
actNow("between", rounds + 1);
|
|
1150
|
+
const ownerMsg = rounds > 0 ? opts.ownerSteer?.(rounds + 1) : undefined;
|
|
1151
|
+
if (ownerMsg)
|
|
1152
|
+
ownerUser(ownerMsg);
|
|
1153
|
+
opts.ownerAct?.opened();
|
|
824
1154
|
const messages = buildMessages(opts.systemPrompt, conversation.all);
|
|
825
1155
|
// Clamp generation to the room left after the real prompt (incl. tool_calls args + schemas) so a
|
|
826
1156
|
// deep-session request never overflows the window into a truncated reply. See clampMaxTokens.
|
|
@@ -842,13 +1172,14 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
842
1172
|
// sampling to escape it. One-shot — consumed right after this call so the normal path stays greedy.
|
|
843
1173
|
temperature: retryTempOverride > 0 ? retryTempOverride : opts.temperature,
|
|
844
1174
|
tools: opts.toolSchemas,
|
|
845
|
-
thinking: (truncatedThisTurn || thinkLatched) ? false :
|
|
1175
|
+
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
1176
|
signal: watch.signal,
|
|
847
1177
|
background: opts.background, // endpoint gate: sub-agents yield the shared slot to the interactive main turn
|
|
848
1178
|
onDelta: watch.onDelta,
|
|
849
1179
|
onReasoning: watch.onReasoning,
|
|
850
1180
|
onServed: opts.onServed,
|
|
851
1181
|
onPromptProgress: opts.onPromptProgress,
|
|
1182
|
+
owner: opts.owner, onQueued: opts.onQueued, onSent: opts.onSent, onToolDraft: opts.onToolDraft,
|
|
852
1183
|
});
|
|
853
1184
|
watch.dispose();
|
|
854
1185
|
retryTempOverride = 0; // one-shot consumed: this request has read the perturbed temperature
|
|
@@ -878,6 +1209,13 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
878
1209
|
}
|
|
879
1210
|
catch (err) {
|
|
880
1211
|
watch.dispose();
|
|
1212
|
+
// ctrl+y cut this stream: keep what it had, add the owner's ask, and go straight to the act round (think-off).
|
|
1213
|
+
if (watch.tripped && watch.tripReason === "owner" && !opts.signal?.aborted) {
|
|
1214
|
+
opts.ownerAct?.consume();
|
|
1215
|
+
actNow(watch.armedTrip ? "read" : "stream", rounds + 2, watch.partial);
|
|
1216
|
+
await sleep(OWNER_ACT_SETTLE_MS, opts.signal, () => new TurnAbortedError()); // let the server free the cut slot (owner-act.ts)
|
|
1217
|
+
continue roundLoop;
|
|
1218
|
+
}
|
|
881
1219
|
// The stream became a runaway repetition loop and the watch tore it down: end the turn here, before any
|
|
882
1220
|
// retry or continue-nudge could re-seed it. The partial is dropped; history keeps only the marker.
|
|
883
1221
|
if (watch.tripped && !opts.signal?.aborted)
|
|
@@ -909,7 +1247,7 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
909
1247
|
"(python3 -c / bash -c) kept breaking the tool-call JSON. I'll write scripts to a file and run " +
|
|
910
1248
|
"the file from here. Send your next message and I'll continue.]";
|
|
911
1249
|
conversation.assistant(msg);
|
|
912
|
-
return { content: msg, rounds: rounds + 1, toolCalls: toolCallTotal, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal };
|
|
1250
|
+
return { content: msg, rounds: rounds + 1, toolCalls: toolCallTotal, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal, loop: loopEv.evidence() };
|
|
913
1251
|
}
|
|
914
1252
|
truncRetries += 1;
|
|
915
1253
|
opts.onSelfHeal?.("server_error", truncRetries); // footer ↻ — a recovery is in flight
|
|
@@ -987,7 +1325,7 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
987
1325
|
// eviction alone can't shed. Give up only if we genuinely couldn't shrink the request at all.
|
|
988
1326
|
const before = conversation.all;
|
|
989
1327
|
const cOpts = compactionOptsFor(endpoint);
|
|
990
|
-
const shrunk = fitToWindow(await
|
|
1328
|
+
const shrunk = fitToWindow(await compactSignalled(before, cOpts, fullRequestEstimate(before, cOpts)), cOpts);
|
|
991
1329
|
conversation.replaceAll(shrunk);
|
|
992
1330
|
const chars = (ms) => ms.reduce((n, m) => n + m.content.length, 0);
|
|
993
1331
|
if (chars(shrunk) >= chars(before))
|
|
@@ -1009,6 +1347,7 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
1009
1347
|
continue;
|
|
1010
1348
|
}
|
|
1011
1349
|
}
|
|
1350
|
+
loopEv.responded(); // the warnings injected before this request have been seen
|
|
1012
1351
|
// Unrestricted mode (engine/unrestricted.ts, owner's private system): this round's `response` just came
|
|
1013
1352
|
// back clean (no self-heal error) — if it has no tool calls AND its text/stopReason reads as a
|
|
1014
1353
|
// POLICY/MORAL refusal (not a capability limit), re-issue the SAME request with an affirmative-prefill
|
|
@@ -1039,13 +1378,14 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
1039
1378
|
maxTokens: clampMaxTokens(retryMessages, compactionOptsFor(endpoint), opts.maxTokens ?? 8192),
|
|
1040
1379
|
temperature: opts.temperature,
|
|
1041
1380
|
tools: opts.toolSchemas,
|
|
1042
|
-
thinking: (truncatedThisTurn || thinkLatched) ? false :
|
|
1381
|
+
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
1382
|
signal: opts.signal,
|
|
1044
1383
|
background: opts.background,
|
|
1045
1384
|
onDelta: opts.onDelta,
|
|
1046
1385
|
onReasoning: opts.onReasoning,
|
|
1047
1386
|
onServed: opts.onServed,
|
|
1048
1387
|
onPromptProgress: opts.onPromptProgress,
|
|
1388
|
+
owner: opts.owner, onQueued: opts.onQueued, onSent: opts.onSent, onToolDraft: opts.onToolDraft,
|
|
1049
1389
|
});
|
|
1050
1390
|
}
|
|
1051
1391
|
}
|
|
@@ -1098,7 +1438,7 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
1098
1438
|
"section, then file_edit to append each next part, a few hundred lines per call), or paste the " +
|
|
1099
1439
|
"content and I'll place it.]";
|
|
1100
1440
|
conversation.assistant(msg);
|
|
1101
|
-
return { content: msg, rounds: rounds + 1, toolCalls: toolCallTotal, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal };
|
|
1441
|
+
return { content: msg, rounds: rounds + 1, toolCalls: toolCallTotal, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal, loop: loopEv.evidence() };
|
|
1102
1442
|
}
|
|
1103
1443
|
truncDispatched += 1; // fall through to dispatch; onBadArgs fires the evidence (recovered:false)
|
|
1104
1444
|
}
|
|
@@ -1133,10 +1473,7 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
1133
1473
|
// 09-27). NUDGE it to try something different and CONTINUE; keep counting so a model that ignores
|
|
1134
1474
|
// the nudge escalates. A bare user-role nudge is safe here (no leak).
|
|
1135
1475
|
opts.onSelfHeal?.("server_error", seen - CONTENT_LOOP_LIMIT + 1); // footer ↻ — breaking a stall
|
|
1136
|
-
|
|
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.`);
|
|
1476
|
+
loopNudge("repeated_step", repeatedStepNudge(seen));
|
|
1140
1477
|
continue;
|
|
1141
1478
|
}
|
|
1142
1479
|
if (forcedRedirects < CONTENT_LOOP_REDIRECT_MAX) {
|
|
@@ -1150,17 +1487,7 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
1150
1487
|
forcedRedirects += 1;
|
|
1151
1488
|
contentSigs.set(rsig, 0); // fresh runway for this signature after the forced redirect
|
|
1152
1489
|
opts.onSelfHeal?.("server_error", forcedRedirects); // footer ↻ — a forced self-correction
|
|
1153
|
-
|
|
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.`);
|
|
1490
|
+
loopNudge("repeated_step", repeatedStepRedirect(seen));
|
|
1164
1491
|
continue;
|
|
1165
1492
|
}
|
|
1166
1493
|
// Exhausted the forced redirects on a still-unbroken loop — genuinely intractable. Hand back cleanly
|
|
@@ -1179,7 +1506,7 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
1179
1506
|
// fixing (no file edit) and are reasoning HEAVILY — a round that answers or edits never counts. After
|
|
1180
1507
|
// THINK_SPIRAL_ROUNDS, latch native thinking OFF for the rest of the turn and push the model to act or
|
|
1181
1508
|
// answer. Reversible (per-turn), never a hard stop.
|
|
1182
|
-
if (
|
|
1509
|
+
if (thinkingNow() && !thinkLatched) {
|
|
1183
1510
|
const heavyReasoning = (response.reasoningContent?.length ?? 0) >= THINK_SPIRAL_MIN_REASON_CHARS;
|
|
1184
1511
|
const mutating = response.toolCalls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? ""));
|
|
1185
1512
|
if (response.toolCalls.length > 0 && !mutating && heavyReasoning) {
|
|
@@ -1187,10 +1514,7 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
1187
1514
|
if (thinkSpiralStreak >= THINK_SPIRAL_ROUNDS) {
|
|
1188
1515
|
thinkLatched = true;
|
|
1189
1516
|
opts.onSelfHeal?.("server_error", thinkSpiralStreak); // footer ↻ — breaking a reasoning spiral
|
|
1190
|
-
|
|
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.`);
|
|
1517
|
+
loopNudge("reasoning_loop", reasoningLoopNudge(thinkSpiralStreak));
|
|
1194
1518
|
continue; // re-prompt with thinking disabled; don't dispatch this spiral round's calls
|
|
1195
1519
|
}
|
|
1196
1520
|
}
|
|
@@ -1204,8 +1528,9 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
1204
1528
|
// round that admits-and-fixes, both pass through untouched. A file edit clears the streak (broke out).
|
|
1205
1529
|
{
|
|
1206
1530
|
const mutatingThisRound = response.toolCalls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? ""));
|
|
1207
|
-
|
|
1208
|
-
|
|
1531
|
+
const admitted = SELF_LOOP_RE.test(response.content);
|
|
1532
|
+
if (response.toolCalls.length > 0 && !mutatingThisRound && (admitted || LOOP_ADMISSION_RE.test(response.content))) {
|
|
1533
|
+
selfLoopStreak = admitted ? selfLoopStreak + 1 : 0; // only SELF_LOOP_RE's admissions build toward the stop
|
|
1209
1534
|
if (selfLoopStreak >= SELF_LOOP_STOP) {
|
|
1210
1535
|
const gist = response.content.trim().split("\n").find((l) => l.trim())?.slice(0, 200) ?? "";
|
|
1211
1536
|
const stuck = `[stopped — I said I was going in circles ${selfLoopStreak}× without making a change that broke ` +
|
|
@@ -1213,24 +1538,24 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
1213
1538
|
`to proceed — a different angle, or I can apply the fix I've been circling if you confirm it.]`;
|
|
1214
1539
|
return stopTurn(stuck, rounds + 1);
|
|
1215
1540
|
}
|
|
1216
|
-
opts.onSelfHeal?.("server_error", selfLoopStreak); // footer ↻ — breaking a self-declared loop
|
|
1217
|
-
|
|
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.`);
|
|
1541
|
+
opts.onSelfHeal?.("server_error", Math.max(1, selfLoopStreak)); // footer ↻ — breaking a self-declared loop
|
|
1542
|
+
loopNudge("self_loop", SELF_LOOP_NUDGE);
|
|
1221
1543
|
continue; // let the model act on the nudge; don't dispatch this round's repeated calls
|
|
1222
1544
|
}
|
|
1223
1545
|
selfLoopStreak = 0; // a round that fixes, doesn't act, or doesn't admit looping clears the streak
|
|
1224
1546
|
}
|
|
1225
1547
|
// 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.
|
|
1548
|
+
// gets a plan + options (ask_user), or in Autonomous mode a plan review, instead of a silently picked approach.
|
|
1549
|
+
// This round's calls are not dispatched.
|
|
1227
1550
|
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
1551
|
decisionNudged = true;
|
|
1229
1552
|
if (response.content.trim())
|
|
1230
1553
|
conversation.assistant(cleanAssistantProse(response.content));
|
|
1231
|
-
engineUser(
|
|
1554
|
+
engineUser(decisionNudge);
|
|
1232
1555
|
continue;
|
|
1233
1556
|
}
|
|
1557
|
+
if (response.toolCalls.length > 0 && ownerActStage === 2)
|
|
1558
|
+
return refuseAfterOwnerAct(response.content, response.toolCalls);
|
|
1234
1559
|
if (response.toolCalls.length > 0) {
|
|
1235
1560
|
throwIfAborted(opts.signal); // don't dispatch a tool batch for a turn the user already cancelled
|
|
1236
1561
|
// Strip any leaked tool-call/thinking delimiter tags the model emitted into content ALONGSIDE the
|
|
@@ -1244,11 +1569,24 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
1244
1569
|
finishReason: response.finishReason, maxTokensSent: lastMaxTokens, promptTokens: response.promptTokens,
|
|
1245
1570
|
genTokens: response.tokens, endpoint: endpoint.base, model: endpoint.model,
|
|
1246
1571
|
});
|
|
1247
|
-
const
|
|
1572
|
+
const round = await abortable(runToolCalls(response.toolCalls, opts.tools, callCounts, rca, opts.onToolBatch, onToolStartFx, onToolResultFx, opts.signal, guard, onBadArgs, opts.onToolCallStart), opts.signal);
|
|
1573
|
+
const toolMsgs = round.msgs;
|
|
1248
1574
|
for (const tm of capToolRound(toolMsgs))
|
|
1249
1575
|
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
1576
|
observeVerify(verify, response.toolCalls, toolMsgs); // verify-before-done: record mutation / verify signal
|
|
1577
|
+
observeLoop(loopEv, response.toolCalls, toolMsgs);
|
|
1578
|
+
noteNarration(cleanAssistantProse(response.content));
|
|
1251
1579
|
toolCallTotal += response.toolCalls.length;
|
|
1580
|
+
if (ownerActStage === 1)
|
|
1581
|
+
ownerActStage = 2; // that was the one next call, refused repeat or not
|
|
1582
|
+
const settled = settleRound(round); // a dead round is recovered here (or, past the budget, ends the turn)
|
|
1583
|
+
if (settled === true)
|
|
1584
|
+
continue;
|
|
1585
|
+
if (settled)
|
|
1586
|
+
return settled;
|
|
1587
|
+
const reread = loopEv.staleRereadDue(); // the same unchanged files again: the re-read warning (or, ignored, the reset)
|
|
1588
|
+
if (reread)
|
|
1589
|
+
loopNudge("stale_reread", staleRereadNudge(reread));
|
|
1252
1590
|
if (guard?.halt) {
|
|
1253
1591
|
const note = recovery.next(guard.halt);
|
|
1254
1592
|
if (!note)
|
|
@@ -1309,7 +1647,7 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
1309
1647
|
if (nwp.action === "halt")
|
|
1310
1648
|
return stopTurn(nwp.message, rounds + 1);
|
|
1311
1649
|
if (nwp.action === "warn") {
|
|
1312
|
-
|
|
1650
|
+
loopNudge("no_write_progress", nwp.message); // tool messages were already copied into history; mutate neither a stale copy nor the system prompt
|
|
1313
1651
|
}
|
|
1314
1652
|
}
|
|
1315
1653
|
if (stalledNotConverging(response.toolCalls, toolMsgs, response.content))
|
|
@@ -1329,17 +1667,32 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
1329
1667
|
decisionNudged = true;
|
|
1330
1668
|
if (recovered.cleanedContent.trim())
|
|
1331
1669
|
conversation.assistant(recovered.cleanedContent);
|
|
1332
|
-
engineUser(
|
|
1670
|
+
engineUser(decisionNudge);
|
|
1333
1671
|
continue;
|
|
1334
1672
|
}
|
|
1673
|
+
if (recovered.calls.length > 0 && ownerActStage === 2)
|
|
1674
|
+
return refuseAfterOwnerAct(recovered.cleanedContent, recovered.calls);
|
|
1335
1675
|
if (recovered.calls.length > 0) {
|
|
1336
1676
|
throwIfAborted(opts.signal);
|
|
1337
1677
|
conversation.assistant(recovered.cleanedContent, recovered.calls);
|
|
1338
|
-
const
|
|
1678
|
+
const round = await abortable(runToolCalls(recovered.calls, opts.tools, callCounts, rca, opts.onToolBatch, onToolStartFx, onToolResultFx, opts.signal, guard, undefined, opts.onToolCallStart), opts.signal);
|
|
1679
|
+
const toolMsgs = round.msgs;
|
|
1339
1680
|
for (const tm of capToolRound(toolMsgs))
|
|
1340
1681
|
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
1682
|
observeVerify(verify, recovered.calls, toolMsgs); // verify-before-done: record mutation / verify signal
|
|
1683
|
+
observeLoop(loopEv, recovered.calls, toolMsgs);
|
|
1684
|
+
noteNarration(recovered.cleanedContent);
|
|
1342
1685
|
toolCallTotal += recovered.calls.length;
|
|
1686
|
+
if (ownerActStage === 1)
|
|
1687
|
+
ownerActStage = 2; // that was the one next call, refused repeat or not
|
|
1688
|
+
const settled = settleRound(round);
|
|
1689
|
+
if (settled === true)
|
|
1690
|
+
continue;
|
|
1691
|
+
if (settled)
|
|
1692
|
+
return settled;
|
|
1693
|
+
const reread = loopEv.staleRereadDue();
|
|
1694
|
+
if (reread)
|
|
1695
|
+
loopNudge("stale_reread", staleRereadNudge(reread));
|
|
1343
1696
|
if (guard?.halt) {
|
|
1344
1697
|
const note = recovery.next(guard.halt);
|
|
1345
1698
|
if (!note)
|
|
@@ -1388,7 +1741,7 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
1388
1741
|
if (nwp.action === "halt")
|
|
1389
1742
|
return stopTurn(nwp.message, rounds + 1);
|
|
1390
1743
|
if (nwp.action === "warn") {
|
|
1391
|
-
|
|
1744
|
+
loopNudge("no_write_progress", nwp.message);
|
|
1392
1745
|
continue;
|
|
1393
1746
|
}
|
|
1394
1747
|
}
|
|
@@ -1415,7 +1768,8 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
1415
1768
|
// TRUNCATION, not a dud. Free output room by compacting, then retry the SAME request. If nothing
|
|
1416
1769
|
// can be shed, fall through to finalize with the reasoning we did capture.
|
|
1417
1770
|
const before = conversation.all.length;
|
|
1418
|
-
|
|
1771
|
+
const eOpts = compactionOptsFor(endpoint);
|
|
1772
|
+
conversation.replaceAll(await compactSignalled(conversation.all, eOpts, fullRequestEstimate(conversation.all, eOpts)));
|
|
1419
1773
|
if (conversation.all.length < before)
|
|
1420
1774
|
continue;
|
|
1421
1775
|
}
|
|
@@ -1488,6 +1842,16 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
1488
1842
|
engineUser(VERIFY_REMINDER);
|
|
1489
1843
|
continue;
|
|
1490
1844
|
}
|
|
1845
|
+
// Reported-check gate: an answer that reports a clean type-check or passing tests, in a turn that did work but never ran
|
|
1846
|
+
// that check, gets ONE reminder to run it (11/02: "✅ No TypeScript errors" after vite builds, tsc never run).
|
|
1847
|
+
// only a turn that changed files owes its reported checks: a read-only turn reporting CI or a log is quoting it
|
|
1848
|
+
const unrunChecks = verifyEnabled && final && !isEngineFinal(final) && toolCallTotal > 0 && verify.changedFiles() ? verify.unrun(final) : [];
|
|
1849
|
+
if (unrunChecks.length && !unrunNudged) {
|
|
1850
|
+
unrunNudged = true;
|
|
1851
|
+
conversation.assistant(final);
|
|
1852
|
+
engineUser(unrunCheckReminder(unrunChecks));
|
|
1853
|
+
continue;
|
|
1854
|
+
}
|
|
1491
1855
|
// Owner-facing: a final that leaves open task-list items with neither a question nor a status is a bare stop —
|
|
1492
1856
|
// one nudge to continue or to close with a status line per item and ONE steering question.
|
|
1493
1857
|
if (final && response.stopReason !== "length" && !closingNudged && !opts.background && !isEngineFinal(final) && needsClosingSteer(final, !!opts.preservedState?.())) {
|
|
@@ -1497,14 +1861,18 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
1497
1861
|
continue;
|
|
1498
1862
|
}
|
|
1499
1863
|
const unverified = verifyEnabled && verify.gate(); // changed files, still no passing check after the nudge
|
|
1500
|
-
const answer = (unverified ? NOT_VERIFIED_BANNER : "") +
|
|
1864
|
+
const answer = (unverified ? NOT_VERIFIED_BANNER : unrunChecks.length ? unrunCheckBanner(unrunChecks) : "") +
|
|
1501
1865
|
(final || stripScratchpad(response.reasoningContent ?? "") || stripScratchpad(lastReasoning) ||
|
|
1502
1866
|
(response.stopReason === "length"
|
|
1503
1867
|
? "(hit the output limit before an answer landed — ask me to continue and I'll pick up where I left off.)"
|
|
1504
1868
|
: emptyReplyStatus(opts.preservedState?.(), emptyRetries + 1)));
|
|
1505
1869
|
conversation.assistant(answer);
|
|
1870
|
+
// a recovered loop moved on to an answer: reported here, where the answer is final — an announcement the continuation
|
|
1871
|
+
// check sent back, or a closing the nudge rewrote, never became the step that moved the turn on
|
|
1872
|
+
if (final && !isEngineFinal(final))
|
|
1873
|
+
proceeded([], final);
|
|
1506
1874
|
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 };
|
|
1875
|
+
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
1876
|
}
|
|
1509
1877
|
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
1878
|
return stopTurn(timeoutMsg, rounds);
|