@0perator/operator 0.1.346 → 0.1.348
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/auth/beta.js +8 -0
- package/dist/auth/client.js +10 -6
- package/dist/auth/commands.js +19 -5
- package/dist/cli.js +9 -0
- package/dist/engine/agent.js +36 -17
- package/dist/engine/loop-guard.js +35 -4
- package/dist/tools/executor.js +2 -1
- package/package.json +1 -1
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// AuthGate's private-beta refusals and the one sentence a person sees for them: at sign-in, in `operator auth status`
|
|
2
|
+
// and on a turn's 403. Node-free on purpose: engine/agent.ts imports it, and the engine ships in the neutral bundle.
|
|
3
|
+
const REFUSAL = /\b(?:not_allowlisted|pending_approval|account_rejected|account_inactive)\b/;
|
|
4
|
+
/** True when an AuthGate error code, or an error message carrying one, says this person isn't let in. */
|
|
5
|
+
export const isBetaRefusal = (text = "") => REFUSAL.test(text);
|
|
6
|
+
export function privateBetaMessage(who) {
|
|
7
|
+
return `Operator is in private beta and ${who} isn't on the access list yet — ask the Operator team for access.`;
|
|
8
|
+
}
|
package/dist/auth/client.js
CHANGED
|
@@ -23,6 +23,12 @@ async function post(path, body, timeoutMs = 15_000) {
|
|
|
23
23
|
clearTimeout(t);
|
|
24
24
|
}
|
|
25
25
|
}
|
|
26
|
+
// A refusal body is flat (`{error}`) or under FastAPI's `detail` (`{detail:{error, message}}` or `{detail:"..."}`).
|
|
27
|
+
// `message` is the server's own sentence for the person, when it sends one.
|
|
28
|
+
function refusal(status, json) {
|
|
29
|
+
const error = json?.error ?? json?.detail?.error ?? (typeof json?.detail === "string" ? json.detail : `http_${status}`);
|
|
30
|
+
return typeof json?.detail?.message === "string" ? { error, message: json.detail.message } : { error };
|
|
31
|
+
}
|
|
26
32
|
/** Kick off a device-authorization grant: the CLI shows user_code, the human approves in a browser. */
|
|
27
33
|
export async function requestDeviceCode() {
|
|
28
34
|
const { status, json } = await post("/operator/device/code", { client_id: CLIENT_ID });
|
|
@@ -81,9 +87,9 @@ export async function verifyTokenDetailed(token, timeoutMs = 10_000) {
|
|
|
81
87
|
});
|
|
82
88
|
if (res.status >= 500)
|
|
83
89
|
return { state: "unreachable" }; // a sick backend is not a verdict on the token
|
|
84
|
-
if (res.status !== 200)
|
|
85
|
-
return { state: "rejected", status: res.status };
|
|
86
90
|
const json = (await res.json().catch(() => ({})));
|
|
91
|
+
if (res.status !== 200)
|
|
92
|
+
return { state: "rejected", status: res.status, ...refusal(res.status, json) };
|
|
87
93
|
return json.account ? { state: "ok", account: json.account, raw: json } : { state: "rejected", status: 200 };
|
|
88
94
|
}
|
|
89
95
|
catch {
|
|
@@ -106,8 +112,7 @@ export async function signupStart(email) {
|
|
|
106
112
|
const { status, json } = await post("/operator/signup/start", { email });
|
|
107
113
|
if (status === 200)
|
|
108
114
|
return { ok: true };
|
|
109
|
-
|
|
110
|
-
return { ok: false, error, status };
|
|
115
|
+
return { ok: false, status, ...refusal(status, json) };
|
|
111
116
|
}
|
|
112
117
|
/** Exchange (email, 6-digit code) for an operator token. Burns the code on success. */
|
|
113
118
|
export async function signupVerify(email, code) {
|
|
@@ -115,6 +120,5 @@ export async function signupVerify(email, code) {
|
|
|
115
120
|
if (status === 200 && json?.token) {
|
|
116
121
|
return { ok: true, token: json.token, account: (json.account ?? { external_id: email }) };
|
|
117
122
|
}
|
|
118
|
-
|
|
119
|
-
return { ok: false, error, status };
|
|
123
|
+
return { ok: false, status, ...refusal(status, json) };
|
|
120
124
|
}
|
package/dist/auth/commands.js
CHANGED
|
@@ -14,7 +14,8 @@
|
|
|
14
14
|
import { spawn } from "node:child_process";
|
|
15
15
|
import { platform } from "node:os";
|
|
16
16
|
import { createInterface } from "node:readline/promises";
|
|
17
|
-
import { requestDeviceCode, awaitApproval, verifyToken, authBase, signupStart, signupVerify, } from "./client.js";
|
|
17
|
+
import { requestDeviceCode, awaitApproval, verifyToken, verifyTokenDetailed, authBase, signupStart, signupVerify, } from "./client.js";
|
|
18
|
+
import { isBetaRefusal, privateBetaMessage } from "./beta.js";
|
|
18
19
|
import { saveCredentials, loadCredentials, clearCredentials } from "./store.js";
|
|
19
20
|
import { listByoAccounts, hasByoToken, deleteByoToken, setByoTokenInteractive } from "./byo.js";
|
|
20
21
|
import { auditControl } from "../telemetry/lifecycle.js";
|
|
@@ -73,6 +74,8 @@ async function loginEmail(emailArg) {
|
|
|
73
74
|
console.error(`✗ "${email}" doesn't look like a valid email address`);
|
|
74
75
|
else if (started.error === "too_many_requests")
|
|
75
76
|
console.error("✗ too many codes requested for that address — wait a few minutes, then try again");
|
|
77
|
+
else if (isBetaRefusal(started.error))
|
|
78
|
+
console.error(`✗ ${started.message ?? privateBetaMessage(email)}`);
|
|
76
79
|
else
|
|
77
80
|
console.error(`✗ couldn't start sign-in via ${authBase()} (${started.error})`);
|
|
78
81
|
await audit("auth_failed", `method=email stage=start reason=${started.error}`);
|
|
@@ -107,6 +110,10 @@ async function loginEmail(emailArg) {
|
|
|
107
110
|
console.error("✗ too many wrong tries — run `operator auth login` again for a fresh code");
|
|
108
111
|
return 1;
|
|
109
112
|
}
|
|
113
|
+
if (isBetaRefusal(v.error)) {
|
|
114
|
+
console.error(`✗ ${v.message ?? privateBetaMessage(email)}`);
|
|
115
|
+
return 1;
|
|
116
|
+
}
|
|
110
117
|
console.error(`✗ sign-in failed (${v.error})`);
|
|
111
118
|
return 1;
|
|
112
119
|
}
|
|
@@ -151,7 +158,9 @@ async function loginDevice() {
|
|
|
151
158
|
const r = await awaitApproval(dc, { signal: ctrl.signal, onTick: () => process.stdout.write(".") });
|
|
152
159
|
process.stdout.write("\n");
|
|
153
160
|
if (r.state !== "approved") {
|
|
154
|
-
|
|
161
|
+
// AuthGate denies the grant for someone off the access list; a Ctrl-C also ends the wait as "denied".
|
|
162
|
+
const refused = r.state === "denied" && !ctrl.signal.aborted;
|
|
163
|
+
console.error(refused ? `✗ sign-in not approved — ${privateBetaMessage("your account")}` : `✗ sign-in ${r.state === "expired" ? "timed out" : r.state}`);
|
|
155
164
|
await audit("auth_failed", `method=browser reason=${r.state}`);
|
|
156
165
|
return 1;
|
|
157
166
|
}
|
|
@@ -185,12 +194,17 @@ async function status() {
|
|
|
185
194
|
console.log("not signed in — run `operator auth login`");
|
|
186
195
|
return 0;
|
|
187
196
|
}
|
|
188
|
-
const
|
|
189
|
-
if (
|
|
197
|
+
const r = await verifyTokenDetailed(creds.token);
|
|
198
|
+
if (r.state === "rejected" && isBetaRefusal(r.error)) {
|
|
199
|
+
const who = creds.user?.replace(/^phone:/, "") ?? "your account"; // a phone identity's external_id is "phone:+E164"
|
|
200
|
+
console.log(`signed in, but access isn't active: ${r.message ?? privateBetaMessage(who)}`);
|
|
201
|
+
return 0;
|
|
202
|
+
}
|
|
203
|
+
if (r.state !== "ok") {
|
|
190
204
|
console.log(`stored credentials for ${creds.user ?? "?"} are no longer valid — run \`operator auth login\``);
|
|
191
205
|
return 0;
|
|
192
206
|
}
|
|
193
|
-
console.log(`signed in as ${account.email ?? account.external_id} · ${creds.host ?? authBase()}`);
|
|
207
|
+
console.log(`signed in as ${r.account.email ?? r.account.external_id} · ${creds.host ?? authBase()}`);
|
|
194
208
|
return 0;
|
|
195
209
|
}
|
|
196
210
|
function flagValue(rest, flag) {
|
package/dist/cli.js
CHANGED
|
@@ -1943,6 +1943,7 @@ function Root() {
|
|
|
1943
1943
|
// /login --browser the explicit device-grant fallback (unchanged behaviour)
|
|
1944
1944
|
const a = (arg ?? "").trim();
|
|
1945
1945
|
const { signupStart, signupVerify, verifyToken, authBase } = await import("./auth/client.js");
|
|
1946
|
+
const { isBetaRefusal, privateBetaMessage } = await import("./auth/beta.js");
|
|
1946
1947
|
const { classifyLoginArg } = await import("./auth/login-intent.js");
|
|
1947
1948
|
const { saveCredentials } = await import("./auth/store.js");
|
|
1948
1949
|
const { setOperatorToken } = await import("./engine/aurora.js");
|
|
@@ -1963,6 +1964,8 @@ function Root() {
|
|
|
1963
1964
|
setAuthUser(r.account.email ?? r.account.external_id);
|
|
1964
1965
|
sys(`✓ Authenticated as ${r.account.email ?? r.account.external_id}`);
|
|
1965
1966
|
}
|
|
1967
|
+
else if (r.state === "denied")
|
|
1968
|
+
sys(`sign-in not approved — ${privateBetaMessage("your account")}`);
|
|
1966
1969
|
else
|
|
1967
1970
|
sys(`sign-in ${r.state} — try /login <email> to sign in by code instead`);
|
|
1968
1971
|
}
|
|
@@ -2007,6 +2010,10 @@ function Root() {
|
|
|
2007
2010
|
pendingLoginEmailRef.current = null;
|
|
2008
2011
|
sys("too many wrong tries — /login <email> for a fresh code");
|
|
2009
2012
|
}
|
|
2013
|
+
else if (isBetaRefusal(v.error)) {
|
|
2014
|
+
pendingLoginEmailRef.current = null;
|
|
2015
|
+
sys(v.message ?? privateBetaMessage(email));
|
|
2016
|
+
}
|
|
2010
2017
|
else
|
|
2011
2018
|
sys(`sign-in failed (${v.error}) — /login <email> to retry`);
|
|
2012
2019
|
break;
|
|
@@ -2021,6 +2028,8 @@ function Root() {
|
|
|
2021
2028
|
sys(`"${a}" doesn't look like a valid email`);
|
|
2022
2029
|
else if (started.error === "too_many_requests")
|
|
2023
2030
|
sys("too many codes requested — wait a few minutes, then /login <email> again");
|
|
2031
|
+
else if (isBetaRefusal(started.error))
|
|
2032
|
+
sys(started.message ?? privateBetaMessage(a));
|
|
2024
2033
|
else
|
|
2025
2034
|
sys(`couldn't start sign-in (${started.error})`);
|
|
2026
2035
|
break;
|
package/dist/engine/agent.js
CHANGED
|
@@ -12,8 +12,9 @@ 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
|
+
import { isBetaRefusal, privateBetaMessage } from "../auth/beta.js";
|
|
17
18
|
const MAX_SELF_HEAL_PER_TURN = 3;
|
|
18
19
|
// A "loading" 503 (endpoint restarting/warming) is a KNOWN-recoverable WAIT, not a failure — a model reload
|
|
19
20
|
// is ~30-90s, far longer than the ≤8s exponential self-heal backoff, so it gets its own patient budget that
|
|
@@ -325,6 +326,7 @@ async function runToolCalls(toolCalls, tools, callCounts, rca, onToolBatch, onTo
|
|
|
325
326
|
const preResolved = new Map(); // id -> result, for parse errors + loop-guarded calls
|
|
326
327
|
const parsedArgs = new Map();
|
|
327
328
|
let loopAbort; // set when a signature blows past LOOP_GUARD_HARD — the turn is aborted (below)
|
|
329
|
+
let loopAbortCompleted = false; // the RCA gate fired: the action already completed, so recovery does not apply
|
|
328
330
|
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
331
|
const guardReplay = new Set(); // calls the identical-args counter refused: one more repeat for the result guard, nothing else
|
|
330
332
|
toolCalls.forEach((tc, batchIndex) => {
|
|
@@ -347,7 +349,7 @@ async function runToolCalls(toolCalls, tools, callCounts, rca, onToolBatch, onTo
|
|
|
347
349
|
// args while waiting on async work — that's not a spin, so they are never loop-guarded. Live 09-27:
|
|
348
350
|
// agent_status polled while sub-agents ran tripped the guard at 5 (and kept firing) even though the
|
|
349
351
|
// model was doing real work between polls.
|
|
350
|
-
if (LOOP_GUARD_EXEMPT.has(tc.function.name)) {
|
|
352
|
+
if (LOOP_GUARD_EXEMPT.has(tc.function.name) || (guard && IDEMPOTENT_TOOLS.has(tc.function.name))) {
|
|
351
353
|
pending.push({ id: tc.id, name: tc.function.name, args: parsed.args, batchId, batchSize, batchIndex });
|
|
352
354
|
return;
|
|
353
355
|
}
|
|
@@ -390,6 +392,7 @@ async function runToolCalls(toolCalls, tools, callCounts, rca, onToolBatch, onTo
|
|
|
390
392
|
const refused = (rca.refused.get(fp) ?? 0) + 1;
|
|
391
393
|
rca.refused.set(fp, refused);
|
|
392
394
|
if (refused >= RCA_STOP) {
|
|
395
|
+
loopAbortCompleted = true;
|
|
393
396
|
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
397
|
}
|
|
395
398
|
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 +403,12 @@ async function runToolCalls(toolCalls, tools, callCounts, rca, onToolBatch, onTo
|
|
|
400
403
|
});
|
|
401
404
|
// A signature blew past the hard loop ceiling: stop the turn cleanly rather than let the model spin to the
|
|
402
405
|
// round cap. TurnAbortedError is the engine's existing clean-stop path (identical to an esc interrupt).
|
|
403
|
-
if (loopAbort)
|
|
404
|
-
|
|
406
|
+
if (loopAbort) {
|
|
407
|
+
if (guard)
|
|
408
|
+
guard.trip(loopAbort, loopAbortCompleted ? "completed_action" : "repeated_action");
|
|
409
|
+
else
|
|
410
|
+
throw new TurnAbortedError(`Loop guard: ${loopAbort}`);
|
|
411
|
+
}
|
|
405
412
|
if (pending.length)
|
|
406
413
|
onToolStart?.(pending);
|
|
407
414
|
const started = performance.now();
|
|
@@ -541,11 +548,14 @@ function watchRepetition(opts, on) {
|
|
|
541
548
|
}
|
|
542
549
|
/** Runs one user turn to completion: compacts, loops model↔tools ≤maxRounds, self-heals, finalizes. */
|
|
543
550
|
/** A gateway 401/403 with the reason a person can act on: no token was loaded at all (signed out, or the keychain
|
|
544
|
-
* is locked — every SSH session on macOS), versus a token the gateway rejected
|
|
551
|
+
* is locked — every SSH session on macOS), versus a token the gateway rejected, versus an account the private beta
|
|
552
|
+
* hasn't let in (pending or removed), which no new sign-in can fix. */
|
|
545
553
|
export function authError(err, base) {
|
|
546
554
|
const msg = err instanceof Error ? err.message : String(err);
|
|
547
555
|
if (!requiresOperatorToken(base))
|
|
548
556
|
return err instanceof Error ? err : new Error(msg);
|
|
557
|
+
if (isBetaRefusal(msg))
|
|
558
|
+
return new Error(`${msg}\n${privateBetaMessage("your account")} Signing in again won't change this.`);
|
|
549
559
|
const why = getOperatorToken()
|
|
550
560
|
? "the gateway rejected this Operator's sign-in token — run `operator auth login` to renew it"
|
|
551
561
|
: "no sign-in token was loaded — run `operator auth login`; over SSH the macOS keychain is locked, so unlock it " +
|
|
@@ -558,10 +568,11 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
558
568
|
const turnStart = Date.now(); // for the per-turn wall-clock budget (opts.maxTurnWallClockMs) — the only bound on TIME
|
|
559
569
|
const callCounts = new Map();
|
|
560
570
|
const guardCfg = resolveLoopGuardConfig(opts.loopGuard, { unattended: opts.unattended === true });
|
|
571
|
+
const recovery = new LoopRecovery(guardCfg.recoveryAttempts);
|
|
561
572
|
const guard = guardCfg.enabled ? new LoopGuard(guardCfg) : undefined; // result-aware tool loop guard (engine/loop-guard.ts)
|
|
562
573
|
const pollSpin = guardCfg.enabled ? new PollSpinGuard() : undefined; // auto-post-poller (agent_status) spin guard — a separate detector, since pollers are EXEMPT from `guard`
|
|
563
574
|
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
|
|
575
|
+
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
576
|
const rca = { succeeded: new Map(), refused: new Map() }; // normalized-fingerprint → completed exact spellings; + refusal tally (see RCA_STOP)
|
|
566
577
|
const contentSigs = new Map(); // per-round prose fingerprints → the narration loop guard
|
|
567
578
|
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 +1249,14 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
1238
1249
|
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
1250
|
observeVerify(verify, response.toolCalls, toolMsgs); // verify-before-done: record mutation / verify signal
|
|
1240
1251
|
toolCallTotal += response.toolCalls.length;
|
|
1241
|
-
if (guard?.halt)
|
|
1242
|
-
|
|
1252
|
+
if (guard?.halt) {
|
|
1253
|
+
const note = recovery.next(guard.halt);
|
|
1254
|
+
if (!note)
|
|
1255
|
+
return stopTurn(loopStopNote({ ...guard.halt, message: guard.halt.message + (recovery.attempts ? `; ${recovery.attempts} recovery attempts used` : "") }), rounds + 1);
|
|
1256
|
+
guard.resume();
|
|
1257
|
+
engineUser(note);
|
|
1258
|
+
continue;
|
|
1259
|
+
}
|
|
1243
1260
|
progressed = batchProgressed(toolMsgs);
|
|
1244
1261
|
noProgressStreak = progressed ? 0 : noProgressStreak + 1; // reset the stall counter on any real progress
|
|
1245
1262
|
noEditStreak = response.toolCalls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? "")) ? 0 : noEditStreak + 1;
|
|
@@ -1288,15 +1305,11 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
1288
1305
|
}
|
|
1289
1306
|
}
|
|
1290
1307
|
if (noWriteProgress) {
|
|
1291
|
-
const nwp = noWriteProgress.observe(response.toolCalls.map((c) => c.function.name));
|
|
1308
|
+
const nwp = noWriteProgress.observe(response.toolCalls.map((c) => c.function.name), toolMsgs.map((m) => m.content ?? ""));
|
|
1292
1309
|
if (nwp.action === "halt")
|
|
1293
1310
|
return stopTurn(nwp.message, rounds + 1);
|
|
1294
1311
|
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 + "]";
|
|
1312
|
+
engineUser(nwp.message); // tool messages were already copied into history; mutate neither a stale copy nor the system prompt
|
|
1300
1313
|
}
|
|
1301
1314
|
}
|
|
1302
1315
|
if (stalledNotConverging(response.toolCalls, toolMsgs, response.content))
|
|
@@ -1327,8 +1340,14 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
1327
1340
|
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
1341
|
observeVerify(verify, recovered.calls, toolMsgs); // verify-before-done: record mutation / verify signal
|
|
1329
1342
|
toolCallTotal += recovered.calls.length;
|
|
1330
|
-
if (guard?.halt)
|
|
1331
|
-
|
|
1343
|
+
if (guard?.halt) {
|
|
1344
|
+
const note = recovery.next(guard.halt);
|
|
1345
|
+
if (!note)
|
|
1346
|
+
return stopTurn(loopStopNote({ ...guard.halt, message: guard.halt.message + (recovery.attempts ? `; ${recovery.attempts} recovery attempts used` : "") }), rounds + 1);
|
|
1347
|
+
guard.resume();
|
|
1348
|
+
engineUser(note);
|
|
1349
|
+
continue;
|
|
1350
|
+
}
|
|
1332
1351
|
progressed = batchProgressed(toolMsgs);
|
|
1333
1352
|
noProgressStreak = progressed ? 0 : noProgressStreak + 1; // reset the stall counter on any real progress
|
|
1334
1353
|
noEditStreak = recovered.calls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? "")) ? 0 : noEditStreak + 1;
|
|
@@ -1365,7 +1384,7 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
1365
1384
|
}
|
|
1366
1385
|
}
|
|
1367
1386
|
if (noWriteProgress) {
|
|
1368
|
-
const nwp = noWriteProgress.observe(recovered.calls.map((c) => c.function.name));
|
|
1387
|
+
const nwp = noWriteProgress.observe(recovered.calls.map((c) => c.function.name), toolMsgs.map((m) => m.content ?? ""));
|
|
1369
1388
|
if (nwp.action === "halt")
|
|
1370
1389
|
return stopTurn(nwp.message, rounds + 1);
|
|
1371
1390
|
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);
|