@0perator/operator 0.1.346 → 0.1.347
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/engine/agent.js +31 -16
- package/dist/engine/loop-guard.js +35 -4
- package/dist/tools/executor.js +2 -1
- package/package.json +1 -1
package/dist/engine/agent.js
CHANGED
|
@@ -12,7 +12,7 @@ import { classifyFailure, servedContextLimit, outputCeilingLimit, learnOutputCei
|
|
|
12
12
|
import { TaskVerification, VERIFY_REMINDER, NOT_VERIFIED_BANNER } from "./verify-gate.js";
|
|
13
13
|
import { detectRefusal, buildAffirmativeRetry, UNRESTRICTED_MAX_RETRIES } from "./unrestricted.js";
|
|
14
14
|
import { ComputerEventStream, ComputerEventTracker } from "./computer-event.js";
|
|
15
|
-
import { LoopGuard, PollSpinGuard, NoWriteProgressGuard, YieldAfterDispatchGuard, loopStopNote, resolveLoopGuardConfig } from "./loop-guard.js";
|
|
15
|
+
import { LoopRecovery, IDEMPOTENT_TOOLS, LoopGuard, PollSpinGuard, NoWriteProgressGuard, YieldAfterDispatchGuard, loopStopNote, resolveLoopGuardConfig } from "./loop-guard.js";
|
|
16
16
|
import { RunawayStreamWatch, ReasoningBudgetWatch, isDegenerateReply, REPETITION_INTERRUPTED, REASONING_BUDGET_INTERRUPTED } from "./repetition-guard.js";
|
|
17
17
|
const MAX_SELF_HEAL_PER_TURN = 3;
|
|
18
18
|
// A "loading" 503 (endpoint restarting/warming) is a KNOWN-recoverable WAIT, not a failure — a model reload
|
|
@@ -325,6 +325,7 @@ async function runToolCalls(toolCalls, tools, callCounts, rca, onToolBatch, onTo
|
|
|
325
325
|
const preResolved = new Map(); // id -> result, for parse errors + loop-guarded calls
|
|
326
326
|
const parsedArgs = new Map();
|
|
327
327
|
let loopAbort; // set when a signature blows past LOOP_GUARD_HARD — the turn is aborted (below)
|
|
328
|
+
let loopAbortCompleted = false; // the RCA gate fired: the action already completed, so recovery does not apply
|
|
328
329
|
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)
|
|
329
330
|
const guardReplay = new Set(); // calls the identical-args counter refused: one more repeat for the result guard, nothing else
|
|
330
331
|
toolCalls.forEach((tc, batchIndex) => {
|
|
@@ -347,7 +348,7 @@ async function runToolCalls(toolCalls, tools, callCounts, rca, onToolBatch, onTo
|
|
|
347
348
|
// args while waiting on async work — that's not a spin, so they are never loop-guarded. Live 09-27:
|
|
348
349
|
// agent_status polled while sub-agents ran tripped the guard at 5 (and kept firing) even though the
|
|
349
350
|
// model was doing real work between polls.
|
|
350
|
-
if (LOOP_GUARD_EXEMPT.has(tc.function.name)) {
|
|
351
|
+
if (LOOP_GUARD_EXEMPT.has(tc.function.name) || (guard && IDEMPOTENT_TOOLS.has(tc.function.name))) {
|
|
351
352
|
pending.push({ id: tc.id, name: tc.function.name, args: parsed.args, batchId, batchSize, batchIndex });
|
|
352
353
|
return;
|
|
353
354
|
}
|
|
@@ -390,6 +391,7 @@ async function runToolCalls(toolCalls, tools, callCounts, rca, onToolBatch, onTo
|
|
|
390
391
|
const refused = (rca.refused.get(fp) ?? 0) + 1;
|
|
391
392
|
rca.refused.set(fp, refused);
|
|
392
393
|
if (refused >= RCA_STOP) {
|
|
394
|
+
loopAbortCompleted = true;
|
|
393
395
|
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.`;
|
|
394
396
|
}
|
|
395
397
|
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.`);
|
|
@@ -400,8 +402,12 @@ async function runToolCalls(toolCalls, tools, callCounts, rca, onToolBatch, onTo
|
|
|
400
402
|
});
|
|
401
403
|
// A signature blew past the hard loop ceiling: stop the turn cleanly rather than let the model spin to the
|
|
402
404
|
// round cap. TurnAbortedError is the engine's existing clean-stop path (identical to an esc interrupt).
|
|
403
|
-
if (loopAbort)
|
|
404
|
-
|
|
405
|
+
if (loopAbort) {
|
|
406
|
+
if (guard)
|
|
407
|
+
guard.trip(loopAbort, loopAbortCompleted ? "completed_action" : "repeated_action");
|
|
408
|
+
else
|
|
409
|
+
throw new TurnAbortedError(`Loop guard: ${loopAbort}`);
|
|
410
|
+
}
|
|
405
411
|
if (pending.length)
|
|
406
412
|
onToolStart?.(pending);
|
|
407
413
|
const started = performance.now();
|
|
@@ -558,10 +564,11 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
558
564
|
const turnStart = Date.now(); // for the per-turn wall-clock budget (opts.maxTurnWallClockMs) — the only bound on TIME
|
|
559
565
|
const callCounts = new Map();
|
|
560
566
|
const guardCfg = resolveLoopGuardConfig(opts.loopGuard, { unattended: opts.unattended === true });
|
|
567
|
+
const recovery = new LoopRecovery(guardCfg.recoveryAttempts);
|
|
561
568
|
const guard = guardCfg.enabled ? new LoopGuard(guardCfg) : undefined; // result-aware tool loop guard (engine/loop-guard.ts)
|
|
562
569
|
const pollSpin = guardCfg.enabled ? new PollSpinGuard() : undefined; // auto-post-poller (agent_status) spin guard — a separate detector, since pollers are EXEMPT from `guard`
|
|
563
570
|
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
|
|
564
|
-
const noWriteProgress = guardCfg.enabled ? new NoWriteProgressGuard(guardCfg.warnInvestigateLoop, guardCfg.stopInvestigateLoop, guardCfg.hardStop) : undefined; // investigate-loop detector — catches rounds with zero mutating calls
|
|
571
|
+
const noWriteProgress = guardCfg.enabled ? new NoWriteProgressGuard(guardCfg.warnInvestigateLoop, guardCfg.stopInvestigateLoop, guardCfg.hardStop && guardCfg.stopOnNoWrite) : undefined; // investigate-loop detector — catches rounds with zero mutating calls
|
|
565
572
|
const rca = { succeeded: new Map(), refused: new Map() }; // normalized-fingerprint → completed exact spellings; + refusal tally (see RCA_STOP)
|
|
566
573
|
const contentSigs = new Map(); // per-round prose fingerprints → the narration loop guard
|
|
567
574
|
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)
|
|
@@ -1238,8 +1245,14 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
1238
1245
|
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
|
|
1239
1246
|
observeVerify(verify, response.toolCalls, toolMsgs); // verify-before-done: record mutation / verify signal
|
|
1240
1247
|
toolCallTotal += response.toolCalls.length;
|
|
1241
|
-
if (guard?.halt)
|
|
1242
|
-
|
|
1248
|
+
if (guard?.halt) {
|
|
1249
|
+
const note = recovery.next(guard.halt);
|
|
1250
|
+
if (!note)
|
|
1251
|
+
return stopTurn(loopStopNote({ ...guard.halt, message: guard.halt.message + (recovery.attempts ? `; ${recovery.attempts} recovery attempts used` : "") }), rounds + 1);
|
|
1252
|
+
guard.resume();
|
|
1253
|
+
engineUser(note);
|
|
1254
|
+
continue;
|
|
1255
|
+
}
|
|
1243
1256
|
progressed = batchProgressed(toolMsgs);
|
|
1244
1257
|
noProgressStreak = progressed ? 0 : noProgressStreak + 1; // reset the stall counter on any real progress
|
|
1245
1258
|
noEditStreak = response.toolCalls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? "")) ? 0 : noEditStreak + 1;
|
|
@@ -1288,15 +1301,11 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
1288
1301
|
}
|
|
1289
1302
|
}
|
|
1290
1303
|
if (noWriteProgress) {
|
|
1291
|
-
const nwp = noWriteProgress.observe(response.toolCalls.map((c) => c.function.name));
|
|
1304
|
+
const nwp = noWriteProgress.observe(response.toolCalls.map((c) => c.function.name), toolMsgs.map((m) => m.content ?? ""));
|
|
1292
1305
|
if (nwp.action === "halt")
|
|
1293
1306
|
return stopTurn(nwp.message, rounds + 1);
|
|
1294
1307
|
if (nwp.action === "warn") {
|
|
1295
|
-
//
|
|
1296
|
-
// Append to the last tool message's content.
|
|
1297
|
-
const last = toolMsgs[toolMsgs.length - 1];
|
|
1298
|
-
if (last)
|
|
1299
|
-
last.content += "\n\n[note: " + nwp.message + "]";
|
|
1308
|
+
engineUser(nwp.message); // tool messages were already copied into history; mutate neither a stale copy nor the system prompt
|
|
1300
1309
|
}
|
|
1301
1310
|
}
|
|
1302
1311
|
if (stalledNotConverging(response.toolCalls, toolMsgs, response.content))
|
|
@@ -1327,8 +1336,14 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
1327
1336
|
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
|
|
1328
1337
|
observeVerify(verify, recovered.calls, toolMsgs); // verify-before-done: record mutation / verify signal
|
|
1329
1338
|
toolCallTotal += recovered.calls.length;
|
|
1330
|
-
if (guard?.halt)
|
|
1331
|
-
|
|
1339
|
+
if (guard?.halt) {
|
|
1340
|
+
const note = recovery.next(guard.halt);
|
|
1341
|
+
if (!note)
|
|
1342
|
+
return stopTurn(loopStopNote({ ...guard.halt, message: guard.halt.message + (recovery.attempts ? `; ${recovery.attempts} recovery attempts used` : "") }), rounds + 1);
|
|
1343
|
+
guard.resume();
|
|
1344
|
+
engineUser(note);
|
|
1345
|
+
continue;
|
|
1346
|
+
}
|
|
1332
1347
|
progressed = batchProgressed(toolMsgs);
|
|
1333
1348
|
noProgressStreak = progressed ? 0 : noProgressStreak + 1; // reset the stall counter on any real progress
|
|
1334
1349
|
noEditStreak = recovered.calls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? "")) ? 0 : noEditStreak + 1;
|
|
@@ -1365,7 +1380,7 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
1365
1380
|
}
|
|
1366
1381
|
}
|
|
1367
1382
|
if (noWriteProgress) {
|
|
1368
|
-
const nwp = noWriteProgress.observe(recovered.calls.map((c) => c.function.name));
|
|
1383
|
+
const nwp = noWriteProgress.observe(recovered.calls.map((c) => c.function.name), toolMsgs.map((m) => m.content ?? ""));
|
|
1369
1384
|
if (nwp.action === "halt")
|
|
1370
1385
|
return stopTurn(nwp.message, rounds + 1);
|
|
1371
1386
|
if (nwp.action === "warn") {
|
|
@@ -8,7 +8,8 @@
|
|
|
8
8
|
// Detectors: consecutive identical (tool, args, result) calls; repeating cycles A,B,A,B… of up to four calls
|
|
9
9
|
// with identical args and results; exact-args failure replays; failure runs on one tool; read-only calls that
|
|
10
10
|
// keep returning the same result; per-turn caps on web searches and sub-agent spawns. Warnings never block.
|
|
11
|
-
// A hard stop is on by default for unattended runs and opt-in for an interactive owner
|
|
11
|
+
// A hard stop is on by default for unattended runs and opt-in for an interactive owner; before it ends a turn the
|
|
12
|
+
// engine offers bounded recovery (LoopRecovery).
|
|
12
13
|
export const LOOP_GUARD_DEFAULTS = {
|
|
13
14
|
warnIdentical: 3, warnExactFailure: 2, warnSameToolFailure: 3, warnNoProgress: 2, warnInvestigateLoop: 8,
|
|
14
15
|
stopIdentical: 5, stopExactFailure: 5, stopSameToolFailure: 8, stopNoProgress: 5, stopInvestigateLoop: 15,
|
|
@@ -24,6 +25,8 @@ export function resolveLoopGuardConfig(raw, ctx) {
|
|
|
24
25
|
enabled: s.enabled !== false,
|
|
25
26
|
hardStop: typeof s.hardStop === "boolean" ? s.hardStop : ctx.unattended,
|
|
26
27
|
repetition: s.repetition !== false,
|
|
28
|
+
recoveryAttempts: Math.min(5, intAtLeast(s.recovery?.maxAttempts, 2, 0)),
|
|
29
|
+
stopOnNoWrite: s.stopOnNoWrite === true,
|
|
27
30
|
warnIdentical: intAtLeast(s.warnAfter?.identicalCall, d.warnIdentical, 2),
|
|
28
31
|
warnExactFailure: intAtLeast(s.warnAfter?.exactFailure, d.warnExactFailure, 1),
|
|
29
32
|
warnSameToolFailure: intAtLeast(s.warnAfter?.sameToolFailure, d.warnSameToolFailure, 1),
|
|
@@ -148,6 +151,10 @@ export class LoopGuard {
|
|
|
148
151
|
}
|
|
149
152
|
/** The decision that ended the turn, if any. The engine stops cleanly at the next batch boundary. */
|
|
150
153
|
get halt() { return this.haltDecision; }
|
|
154
|
+
/** Legacy repeat detectors enter the same batch-boundary recovery path, never the user-cancel path. */
|
|
155
|
+
trip(message, code = "repeated_action") { this.stop(code, "tool batch", 0, message); }
|
|
156
|
+
/** Clear the pending stop only. Evidence, refusal counters and resource caps remain intact. */
|
|
157
|
+
resume() { this.haltDecision = null; }
|
|
151
158
|
stop(code, tool, count, message) {
|
|
152
159
|
const d = { action: "halt", code, message, tool, count };
|
|
153
160
|
this.haltDecision ??= d;
|
|
@@ -477,7 +484,8 @@ export class YieldAfterDispatchGuard {
|
|
|
477
484
|
// This detector keys on the ABSENCE of progress, not on repetition. It is a round-level guard
|
|
478
485
|
// (fed one settled round at a time), not a per-call guard.
|
|
479
486
|
export const INVESTIGATE_LOOP_NUDGE = "You have made no write-progress in the last {n} rounds — only reads, searches, and status checks. " +
|
|
480
|
-
"
|
|
487
|
+
"Summarize the evidence and the remaining question. If the task is research or review, produce the requested answer; " +
|
|
488
|
+
"if a change is required, take the smallest justified step and verify it. Do not create files merely to satisfy this notice.";
|
|
481
489
|
export const INVESTIGATE_LOOP_STOP = "[stopped — no write-progress in {n} consecutive rounds. You have been gathering context without producing output. " +
|
|
482
490
|
"Pick a direction and act on it, or end the turn.]";
|
|
483
491
|
/** Watches settled tool rounds for zero write-progress. Fed one round at a time via observe(); a
|
|
@@ -496,9 +504,9 @@ export class NoWriteProgressGuard {
|
|
|
496
504
|
}
|
|
497
505
|
reset() { this.streak = 0; this.warned = false; }
|
|
498
506
|
/** One settled round: the tools it ran (names) and their results, index-aligned. */
|
|
499
|
-
observe(names) {
|
|
507
|
+
observe(names, results) {
|
|
500
508
|
// Any write-progress call ⇒ progress, reset.
|
|
501
|
-
if (names.some((n) => WRITE_PROGRESS_TOOLS.has(n))) {
|
|
509
|
+
if (names.some((n, i) => WRITE_PROGRESS_TOOLS.has(n) && (!results || (results[i] !== undefined && !resultFailed(n, results[i]) && !/^(?:loop guard|repeated action|blocked)\b/i.test(results[i].trimStart()))))) {
|
|
502
510
|
this.reset();
|
|
503
511
|
return { action: "allow", streak: 0 };
|
|
504
512
|
}
|
|
@@ -519,3 +527,26 @@ export function loopStopNote(d) {
|
|
|
519
527
|
return `[stopped — the loop guard ended this turn: ${d.message}. Repeating it unchanged was not making progress. ` +
|
|
520
528
|
`Nothing was lost; tell me how you'd like to proceed, or ask me to continue and I'll take a different approach.]`;
|
|
521
529
|
}
|
|
530
|
+
/** Turn-local recovery budget. No network, endpoint selection, permission changes, or counter resets. */
|
|
531
|
+
export class LoopRecovery {
|
|
532
|
+
maxAttempts;
|
|
533
|
+
used = 0;
|
|
534
|
+
constructor(maxAttempts) {
|
|
535
|
+
this.maxAttempts = maxAttempts;
|
|
536
|
+
}
|
|
537
|
+
get attempts() { return this.used; }
|
|
538
|
+
next(d) {
|
|
539
|
+
// Caps are budgets, and a re-worded repeat of a COMPLETED action has nothing left to recover: both stay terminal.
|
|
540
|
+
if (d.code === "web_search_cap" || d.code === "subagent_cap" || d.code === "completed_action" || this.used >= this.maxAttempts)
|
|
541
|
+
return undefined;
|
|
542
|
+
this.used++;
|
|
543
|
+
return `Loop recovery ${this.used}/${this.maxAttempts}: ${d.message}. ` +
|
|
544
|
+
`Keep completed work and the original objective. Do not repeat the blocked action unchanged. ` +
|
|
545
|
+
(this.used === 1
|
|
546
|
+
? `State the failed assumption and use the available evidence to choose a different query, tool, or smaller step. `
|
|
547
|
+
: `The previous recovery did not resolve the stall. Work on an independent remaining step or report a useful partial result with the exact blocker and what is needed next. `) +
|
|
548
|
+
`Use only authorized tools and configured endpoints; offline evidence may suffice. Never bypass a permission denial, ` +
|
|
549
|
+
`repeat a side effect whose outcome is uncertain, invent missing information, or claim unverified success. ` +
|
|
550
|
+
`Continue within the existing time, token, round and resource limits.`;
|
|
551
|
+
}
|
|
552
|
+
}
|
package/dist/tools/executor.js
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
// new user turn (not required by SPEC §3's
|
|
9
9
|
// round loop itself, but needed so the guard
|
|
10
10
|
// doesn't bleed across turns)
|
|
11
|
+
import { IDEMPOTENT_TOOLS } from "../engine/loop-guard.js";
|
|
11
12
|
import { isAbsolute, join, resolve } from "node:path";
|
|
12
13
|
import { registry } from "./registry.js";
|
|
13
14
|
import { expandPath } from "./paths.js";
|
|
@@ -80,7 +81,7 @@ export class Executor {
|
|
|
80
81
|
}
|
|
81
82
|
async execute(name, rawArgs) {
|
|
82
83
|
const args = this.root ? rootArgs(name, rawArgs, this.root) : rawArgs;
|
|
83
|
-
if (!LOOP_GUARD_EXEMPT.has(name)) { // poll/status tools are never loop-guarded (repeated calls are legit)
|
|
84
|
+
if (!LOOP_GUARD_EXEMPT.has(name) && !IDEMPOTENT_TOOLS.has(name)) { // poll/status tools are never loop-guarded (repeated calls are legit)
|
|
84
85
|
const key = `${name} ${JSON.stringify(args)}`;
|
|
85
86
|
const count = (this.seen.get(key) ?? 0) + 1;
|
|
86
87
|
this.seen.set(key, count);
|