Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(limits): a bot carries on with another AI at its usage limit by itself, and an engine waiting a limit out ends its turn (#3789)

Milind Sonib3eefc4f2a55
diff --git a/docs/routine-schedules.md b/docs/routine-schedules.md
index 34369a2e4c..2cacfc799a 100644
--- a/docs/routine-schedules.md
+++ b/docs/routine-schedules.md
@@ -110,11 +110,15 @@ use an appropriate event/webhook workflow instead of a fake weekly schedule.
starts again; the same run, never a copy.
- Its bot or conversation was busy when it started: it waits there,
checking every 30 s, for up to an hour.
- - Signed out, out of credit, payment required, a usage limit or an engine
- that needs setting up: no retry. The owner gets one notification per bot
- and cause saying what to do, and no more until one of that bot's runs
- completes. A usage limit that says when it resets (Claude Code does) puts
- the run back for just after the reset, if that is within 12 hours.
+ - A usage limit with another AI that can carry on: the run starts again on
+ that AI after a short wait (see "When an engine runs out" in
+ self-hosting.md), and the owner hears once that the bot is using it.
+ - Signed out, out of credit, payment required, a usage limit nothing can carry
+ on from, or an engine that needs setting up: no retry. The owner gets one
+ notification per bot and cause saying what to do, and no more until one of
+ that bot's runs completes. A usage limit that says when it resets (Claude
+ Code does) puts the run back for just after the reset, if that is within
+ 12 hours.
- The log says what happened ("Retried after the engine stalled ·
Completed"), and each routine shows "N of M runs OK this week".
- Existing one-time, daily/weekday and interval schedules are not migrated or
diff --git a/docs/self-hosting.md b/docs/self-hosting.md
index 34fcfaa59a..39635bb6b3 100644
--- a/docs/self-hosting.md
+++ b/docs/self-hosting.md
@@ -873,20 +873,35 @@ current month to date.
### When an engine runs out
-When a person's turn ends on its engine's quota or usage limit (a
-subscription's weekly limit, an API key out of credit), the conversation gets
-one card offering up to three other engines that can take over, and "Not
-now". An engine is offered only if it can run a turn now (installed, signed
-in, allowed by your organisation), has the tools and the working folder the
-current one has, and can run the conversation's approval level as it stands.
-Nothing changes until the person picks one: that conversation alone moves to
-the engine's default model, the bot's own model and its other conversations
-stay where they are, and their message is sent again. Turns nobody typed
-(routines, webhooks, a teammate's work) get no card.
-
-The offer is on by default. To switch it off, start the server with
-`OMB_QUOTA_SWITCH=0`; any other value, or none, leaves it on. It has no
-setting in `config.json` yet.
+When a turn ends on a usage limit (a subscription's 5-hour or weekly limit,
+one model's own weekly window, a model's extra usage credits), the bot carries
+on by itself with another AI the person has set up until that limit resets,
+and the person hears it once for that stretch of the limit, as a notification:
+"Codex reached its limit until 14:00, so Kai is using Claude meanwhile." With
+no AI to carry on, it says the bot waits instead. Nobody is asked.
+
+- **Which AI.** For one model's own limit, the same AI's default model first;
+ then the backups chosen for the bot or in Automatic recovery; then the AI a
+ new bot would get. Only an AI that can run a turn now (installed, signed in,
+ allowed by your organisation, not limited itself) with the tools and the
+ working folder the current one has. Never another sign-in to the same
+ subscription, which would rotate accounts around the provider's limit; a
+ pay-per-use API key on the same AI is fine.
+- **What moves.** The person's message that met the limit is sent again on that
+ AI, in that conversation alone; the bot's own model and its other
+ conversations stay where they are. While the limit lasts, every new turn
+ (a person's, a routine's, a webhook's) goes straight to that AI without
+ asking the limited one first, and a routine run the limit stopped starts
+ again on it.
+- **How long.** The limited AI is held until the reset it named, or for an hour
+ when it named none. One model's own limit holds that model alone, and for at
+ most six hours before it is tried again. A conversation that moved goes back
+ once its AI's limit has reset, with one line saying so.
+
+This is on by default. Start the server with `OMB_QUOTA_SWITCH=0` to switch it
+off: then only the backups Automatic recovery names take over, and the
+notification says the bot waits. Any other value, or none, leaves it on. It
+has no setting in `config.json` yet.
### Which engine a new bot uses
diff --git a/server/contracts.ts b/server/contracts.ts
index 526eef4a7e..ce56a0eeb5 100644
--- a/server/contracts.ts
+++ b/server/contracts.ts
@@ -52,14 +52,20 @@ export class TurnAuthenticationRefusedError extends TurnNotStartedError {
}
/** The engine's usage limit refused the turn before any model or tool activity (or is known to be refusing until
- * `resetsAt`), and no process of it is running the turn. */
+ * `resetsAt`), and no process of it is running the turn. `scope`: the limit is the account's on that engine, or one
+ * model's own window ("model") or extra usage credits ("credits"), which leave the engine's other models working.
+ * `known`: refused here by a limit already noted, so it is no new refusal. */
export class TurnUsageLimitRefusedError extends TurnNotStartedError {
override readonly name = "TurnUsageLimitRefusedError";
readonly resetsAt: number | undefined;
+ readonly scope: "engine" | "model" | "credits";
+ readonly known: boolean;
- constructor(turnId: TurnId, message: string, resetsAt?: number) {
+ constructor(turnId: TurnId, message: string, resetsAt?: number, scope: "engine" | "model" | "credits" = "engine", known = false) {
super(turnId, message);
this.resetsAt = resetsAt;
+ this.scope = scope;
+ this.known = known;
}
}
diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.ts
index c9a2ac3a74..f91ad408f4 100644
--- a/server/drivers/acp/core.ts
+++ b/server/drivers/acp/core.ts
@@ -20,7 +20,7 @@ import { runAcpOneShot } from "./background-text.ts";
import { sanitizeAcpToolMessage } from "./tool-log.ts";
import { stripLeakedSystemHarnessMessages } from "../../../shared/system-message-guard.ts";
import {
- classifyQuiet, describeQuiet, formatQuietLimit, lastSeenPhrase, LogTail, promptIdleTimeoutMs, quietKey, quietNoticeMs, quietTickMs, sampleProcessTree,
+ classifyQuiet, describeQuiet, formatQuietLimit, lastSeenPhrase, LIMIT_WORDS, LogTail, promptIdleTimeoutMs, quietKey, quietNoticeMs, quietTickMs, quietVerdict, sampleProcessTree,
type LogSignal, type ProcessSample, type QuietState,
} from "./quiet-status.ts";
import { readSessionReport } from "./session-reports.ts";
@@ -571,13 +571,11 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
previous = sample;
previousAt = now;
if (first && next.kind === "unknown") return;
- // An SDK sleeping between retries holds no socket and burns no CPU (Qwen against a 429ing endpoint).
- if (next.kind === "no-signs") {
- noSignsSince ??= now;
- if (now - noSignsSince < ACP_STUCK_AFTER_MS) next = { kind: "between-requests" };
- } else {
- noSignsSince = null;
- }
+ // An SDK sleeping between retries holds no socket and burns no CPU (Qwen against a 429ing endpoint); waiting out a
+ // usage limit, or no sign of life for minutes, ends the turn now rather than after the full silence guard.
+ const verdict = quietVerdict({ next, logged, noSignsSince, now, quietMs, name: support.displayName, stuckAfterMs: ACP_STUCK_AFTER_MS });
+ next = verdict.next; noSignsSince = verdict.noSignsSince;
+ if (verdict.stop) return void session.acp.failAll(verdict.stop);
state = next;
const key = quietKey(next);
if (key === shownKey || notices >= 12) return;
@@ -1601,9 +1599,10 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
...base(threadId, turnId), type: "runtime.error",
message: (accountError ? support.describeAccountError?.(code, cliTurn.model) : undefined) ?? engineFailureMessage(support.displayName, message) ?? message,
...(needsAuth ? { setup: true } : {}), ...((e as any)?.acpPromptStall === true ? { stalled: true } : {}),
+ ...((e as any)?.acpUsageLimit === true || (code === "quota_or_region_restriction" && LIMIT_WORDS.test(message)) ? { limit: "engine" as const } : {}), // waited out, or the engine gave up: another AI can carry on
});
// Never replay an accepted prompt (it may have run tools); evict before listeners start the next turn.
- if (!needsAuth && !accountError && ((e as any)?.acpPromptStall === true || (e as any)?.acpSessionFailure === true
+ if (!needsAuth && !accountError && ((e as any)?.acpPromptStall === true || (e as any)?.acpUsageLimit === true || (e as any)?.acpSessionFailure === true
|| code === "upstream_outage") && session.child.exitCode === null && !session.closing) {
closeSession(threadId, (e as any)?.acpPromptStall === true ? "prompt-stall" : "rpc-failure");
} else if (approvalUnconfirmed && session.child.exitCode === null && !session.closing) {
@@ -1611,7 +1610,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
} else if (staleProcess && !state.promptSent && session.child.exitCode === null && !session.closing) {
closeSession(threadId, "stale-models");
}
- settle(threadId, session, state.stopped, state.stopped ? "cancelled" : needsAuth ? "auth_required" : "rpc_error");
+ settle(threadId, session, state.stopped, state.stopped ? "cancelled" : needsAuth ? "auth_required" : (e as any)?.acpUsageLimit === true ? "quota" : "rpc_error");
}
}
})();
diff --git a/server/drivers/acp/opencode-go.test.ts b/server/drivers/acp/opencode-go.test.ts
index 19f16d2d5a..c11dfe2cdd 100644
--- a/server/drivers/acp/opencode-go.test.ts
+++ b/server/drivers/acp/opencode-go.test.ts
@@ -810,6 +810,54 @@ describe("OpenCode turns without a sign-in gate", () => {
vi.restoreAllMocks();
}
});
+
+ // OpenCode 1.18.27 against a provider at its limit (a 429 naming GoUsageLimitError, retry-after 5 h): one "stream
+ // error" row in its log, then nothing over ACP while it sleeps the whole retry-after, uncapped, five times over.
+ it("ends a turn that waits out a usage limit as that limit, so another AI can carry on", async () => {
+ vi.spyOn(quietStatus, "sampleProcessTree").mockResolvedValue({ cpuMs: 0, connections: 0 });
+ vi.stubEnv("OMB_ACP_QUIET_NOTICE_MS", "300");
+ vi.stubEnv("OMB_ACP_QUIET_TICK_MS", "50");
+ vi.stubEnv("OMB_ACP_LIMIT_QUIET_MS", "400");
+ const row = `timestamp=2026-10-28T22:11:15.919Z level=ERROR run=fixture_run message="stream error" providerID=opencode-go modelID=kimi-k3 session.id={session} small=false agent=build mode=primary error.error="AI_APICallError: Usage limit reached"`;
+ const f = await open("opencode-go-limit", () => ({
+ FAKE_ACP_MODE: "quiet-then-answer", FAKE_ACP_QUIET_MS: "30000", FAKE_ACP_MODELS: "opencode/big-pickle",
+ FAKE_ACP_OPENCODE_LOG: JSON.stringify([row]),
+ }));
+ try {
+ const { done, events } = await f.run("t-go-limit", "opencode/big-pickle");
+ expect(done).toMatchObject({ ok: false, stopReason: "quota" });
+ expect(events.find((event) => event.type === "runtime.error")).toMatchObject({ limit: "engine", message: expect.stringMatching(/usage limit/i) });
+ } finally {
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+ }
+ });
+
+ it("marks OpenCode's own usage-limit refusal as the account's limit, so another AI can carry on", async () => {
+ const f = await open("opencode-gave-up", (scratch) => ({ FAKE_ACP_MODELS: "opencode/big-pickle", FAKE_ACP_RPC_FAILURE_FILE: join(scratch, "failure.json") }));
+ writeFileSync(join(f.scratch, "failure.json"), JSON.stringify({
+ code: -32603, message: "Internal error: Monthly usage limit reached for this key", data: { service: "session", errorName: "APIError" },
+ }));
+ const { done, events } = await f.run("t-gave-up", "opencode/big-pickle");
+ expect(done).toMatchObject({ ok: false });
+ expect(events.find((event) => event.type === "runtime.error")).toMatchObject({ limit: "engine" });
+ });
+
+ it("stops an engine with no open request, no CPU use and nothing logged after a few minutes, not the full silence guard", async () => {
+ vi.spyOn(quietStatus, "sampleProcessTree").mockResolvedValue({ cpuMs: 0, connections: 0 });
+ vi.stubEnv("OMB_ACP_QUIET_NOTICE_MS", "200");
+ vi.stubEnv("OMB_ACP_QUIET_TICK_MS", "50");
+ vi.stubEnv("OMB_ACP_NO_SIGNS_STOP_MS", "500");
+ const f = await open("opencode-lifeless", () => ({ FAKE_ACP_MODE: "quiet-then-answer", FAKE_ACP_QUIET_MS: "30000", FAKE_ACP_MODELS: "opencode/big-pickle" }));
+ try {
+ const { done, events } = await f.run("t-lifeless", "opencode/big-pickle");
+ expect(done).toMatchObject({ ok: false });
+ expect(events.find((event) => event.type === "runtime.error")).toMatchObject({ stalled: true, message: expect.stringContaining("no open request to its model and no CPU use") });
+ } finally {
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+ }
+ });
});
// Measured on opencode 1.18.27: a pooled `opencode acp` kept its old model list after `opencode auth login`.
diff --git a/server/drivers/acp/quiet-status.test.ts b/server/drivers/acp/quiet-status.test.ts
index 037af908bd..1df36c15ae 100644
--- a/server/drivers/acp/quiet-status.test.ts
+++ b/server/drivers/acp/quiet-status.test.ts
@@ -7,7 +7,8 @@ import { describe, expect, it } from "vitest";
import { removeTempDir } from "../../testing/cleanup.ts";
import {
- classifyQuiet, describeQuiet, LogTail, parseOpenCodeLogLine, parseQwenLogLine, quietKey, sampleProcessTree, startedSince, treePids,
+ classifyQuiet, describeQuiet, LogTail, parseOpenCodeLogLine, parseQwenLogLine, quietKey, sampleLinuxProc, sampleProcessTree, startedSince, treePids,
+ quietVerdict, waitingOutLimit, type ProcReader,
} from "./quiet-status.ts";
import { qwenDebugLogPath } from "./qwen.ts";
@@ -206,3 +207,93 @@ describe("qwenDebugLogPath", () => {
expect(qwenDebugLogPath({ QWEN_DEBUG_LOG_FILE: "1" }, "../escape")).toBeNull();
});
});
+
+describe("a Linux process tree from /proc alone", () => {
+ // stat as /proc/<pid>/stat writes it: utime, stime and starttime are fields 14, 15 and 22, after a comm with spaces.
+ const stat = (pid: number, ppid: number, utime: number, stime: number, start: number) =>
+ `${pid} (node (mcp) x) S ${ppid} ${pid} ${pid} 0 -1 4194304 0 0 0 0 ${utime} ${stime} 0 0 20 0 1 0 ${start} 1000 100`;
+ const row = (inode: number, remote: string, state = "01") => ` 0: 0100007F:9C40 ${remote} ${state} 00000000:00000000 00:00000000 00000000 1000 0 ${inode} 1 0000000000000000 20 4 30 10 -1`;
+ const header = " sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode";
+ // An engine (100) and its MCP server (101) in one network namespace, the engine's boxed child (102) in its own, and a
+ // process of something else (200).
+ const files: Record<string, string> = {
+ "/proc/stat": "cpu 1 2 3 4\nbtime 1700000000\n",
+ "/proc/100/stat": stat(100, 1, 300, 200, 1000),
+ "/proc/101/stat": stat(101, 100, 50, 50, 1200),
+ "/proc/102/stat": stat(102, 101, 100, 0, 5000),
+ "/proc/200/stat": stat(200, 1, 9999, 0, 10),
+ "/proc/100/net/tcp": [header, row(11, "0100007F:225F"), row(12, "5DB8D822:01BB"), row(13, "00000000:0000", "0A"), row(15, "5DB8D822:01BB")].join("\n"),
+ "/proc/100/net/tcp6": header,
+ "/proc/102/net/tcp": [header, row(14, "0100007F:0C38")].join("\n"),
+ "/proc/102/net/tcp6": header,
+ };
+ const links: Record<string, string> = {
+ "/proc/100/ns/net": "net:[1]", "/proc/101/ns/net": "net:[1]", "/proc/102/ns/net": "net:[2]",
+ "/proc/100/fd/0": "/dev/null", "/proc/100/fd/3": "socket:[11]", "/proc/100/fd/4": "socket:[12]", "/proc/101/fd/5": "socket:[13]",
+ "/proc/102/fd/6": "socket:[14]", "/proc/200/fd/7": "socket:[15]",
+ };
+ const lists: Record<string, string[]> = {
+ "/proc": ["100", "101", "102", "200", "self", "stat"], "/proc/100/fd": ["0", "3", "4"], "/proc/101/fd": ["5"], "/proc/102/fd": ["6"], "/proc/200/fd": ["7"],
+ };
+ const missing = (path: string) => Object.assign(new Error(`ENOENT: ${path}`), { code: "ENOENT" });
+ const proc = (overrides: Partial<Record<keyof ProcReader, (path: string) => never>> = {}): ProcReader => ({
+ read: (path) => { if (path in files) return files[path]!; throw missing(path); },
+ list: (path) => { if (path in lists) return lists[path]!; throw missing(path); },
+ link: (path) => { if (path in links) return links[path]!; throw missing(path); },
+ ...overrides,
+ });
+
+ it("adds the tree's CPU, and counts its open connections in each of its network namespaces", () => {
+ // 11 is the harness on loopback; 12 a model request; 13 listens; 14 is the box's egress gate on loopback 3128;
+ // 15 belongs to another process.
+ expect(sampleLinuxProc(100, undefined, proc())).toEqual({ cpuMs: 7_000, connections: 3 });
+ });
+
+ it("counts only what started since a time, without the root, as a tool call's own processes", () => {
+ const boot = 1_700_000_000_000;
+ expect(sampleLinuxProc(100, boot + 40_000, proc())).toEqual({ cpuMs: 1_000, connections: 1 });
+ expect(sampleLinuxProc(100, boot + 90_000, proc())).toEqual({ cpuMs: null, connections: null });
+ });
+
+ it("reads nothing it cannot see as unknown, never as idle", () => {
+ expect(sampleLinuxProc(999, undefined, proc()), "no such process").toEqual({ cpuMs: null, connections: null });
+ expect(sampleLinuxProc(100, undefined, proc({ list: (path) => { throw missing(path); } }))).toEqual({ cpuMs: null, connections: null });
+ const noTables = proc({ read: (path) => { if (path.includes("/net/")) throw missing(path); if (path in files) return files[path] as never; throw missing(path); } });
+ expect(sampleLinuxProc(100, undefined, noTables)).toEqual({ cpuMs: 7_000, connections: null });
+ });
+});
+
+describe("an engine waiting out a limit", () => {
+ it("is a model request that failed on a usage or rate limit, or a long wait after a 429", () => {
+ expect(waitingOutLimit({ kind: "provider-error", message: "Usage limit reached" })).toBe(true);
+ expect(waitingOutLimit({ kind: "provider-error", message: "Rate limit exceeded. Please try again later." })).toBe(true);
+ expect(waitingOutLimit({ kind: "provider-error", message: "Incorrect API key provided" })).toBe(false);
+ expect(waitingOutLimit({ kind: "provider-error", message: 'Model \\"x\\" is overloaded' })).toBe(false);
+ expect(waitingOutLimit({ kind: "retry", status: 429, delayMs: 20_000, attempt: 1 })).toBe(false);
+ expect(waitingOutLimit({ kind: "retry", status: 429, delayMs: 600_000, attempt: 1 })).toBe(true);
+ expect(waitingOutLimit({ kind: "retry", status: 503, delayMs: 600_000, attempt: 1 })).toBe(false);
+ expect(waitingOutLimit(null)).toBe(false);
+ });
+});
+
+describe("ending a quiet turn early", () => {
+ const base = { logged: null, noSignsSince: null, now: 1_000_000, quietMs: 420_000, name: "OpenCode Go", stuckAfterMs: 180_000 };
+ it("reads no sign of life as between requests at first, and stops the turn as stuck once it lasts five minutes", () => {
+ expect(quietVerdict({ ...base, next: { kind: "no-signs" } })).toEqual({ next: { kind: "between-requests" }, noSignsSince: 1_000_000, stop: null });
+ expect(quietVerdict({ ...base, next: { kind: "no-signs" }, noSignsSince: 1_000_000 - 200_000 })).toMatchObject({ next: { kind: "no-signs" }, stop: null });
+ const stuck = quietVerdict({ ...base, next: { kind: "no-signs" }, noSignsSince: 1_000_000 - 300_000 }).stop;
+ expect(stuck?.message).toBe("OpenCode Go sent nothing for 7 min with no tool running, no open request to its model and no CPU use, so the turn was stopped as stuck. Send the message again to retry.");
+ expect(stuck).toMatchObject({ acpPromptStall: true });
+ expect(quietVerdict({ ...base, next: { kind: "waiting-model", nearFullContext: false }, noSignsSince: 1 }), "a sign of life starts it over").toEqual({ next: { kind: "waiting-model", nearFullContext: false }, noSignsSince: null, stop: null });
+ });
+
+ it("ends the turn as a usage limit two minutes after the request that failed on one, and never for another error", () => {
+ const limit = { kind: "provider-error" as const, message: "Usage limit reached" };
+ expect(quietVerdict({ ...base, next: { kind: "provider-error", message: limit.message }, logged: { signal: limit, at: 1_000_000 - 60_000 } }).stop).toBeNull();
+ const ended = quietVerdict({ ...base, next: { kind: "provider-error", message: limit.message }, logged: { signal: limit, at: 1_000_000 - 120_000 } }).stop;
+ expect(ended?.message).toBe("OpenCode Go reached a usage limit (“Usage limit reached”) and is waiting it out without replying, so this turn was stopped.");
+ expect(ended).toMatchObject({ acpUsageLimit: true });
+ const other = { kind: "provider-error" as const, message: "Incorrect API key provided" };
+ expect(quietVerdict({ ...base, next: { kind: "provider-error", message: other.message }, logged: { signal: other, at: 0 } }).stop).toBeNull();
+ });
+});
diff --git a/server/drivers/acp/quiet-status.ts b/server/drivers/acp/quiet-status.ts
index fa628e65dd..6d84f6e90b 100644
--- a/server/drivers/acp/quiet-status.ts
+++ b/server/drivers/acp/quiet-status.ts
@@ -3,7 +3,7 @@
// probed from the agent's debug log and its process tree's connections and CPU.
import { execFile } from "node:child_process";
-import { closeSync, existsSync, fstatSync, openSync, readSync } from "node:fs";
+import { closeSync, existsSync, fstatSync, openSync, readdirSync, readFileSync, readlinkSync, readSync } from "node:fs";
import { join } from "node:path";
import { redactSecretsInText } from "../../redact.ts";
@@ -238,13 +238,122 @@ async function sampleWindows(root: number, since?: number): Promise<ProcessSampl
};
}
+/** What Linux's /proc says, read through these (a test passes a fake tree). */
+export interface ProcReader {
+ read(path: string): string;
+ list(path: string): string[];
+ link(path: string): string;
+}
+
+const realProc: ProcReader = { read: (path) => readFileSync(path, "utf8"), list: (path) => readdirSync(path), link: (path) => readlinkSync(path) };
+
+/** Clock ticks per second in /proc/<pid>/stat: USER_HZ, 100 on every Linux this runs on. */
+const PROC_TICKS = 100;
+
+/** Linux from /proc alone, so an image without procps or lsof (a Cloud home's) still says what a quiet engine does, as
+ * ps and lsof do elsewhere: CPU is the tree's utime and stime; connections are its established TCP sockets, read in each
+ * network namespace the tree lives in (a boxed engine has its own). */
+export function sampleLinuxProc(root: number, since?: number, proc: ProcReader = realProc): ProcessSample {
+ const unknown = { cpuMs: null, connections: null };
+ let names: string[];
+ try { names = proc.list("/proc"); } catch { return unknown; }
+ let bootMs = 0;
+ try { bootMs = Number(/^btime (\d+)$/m.exec(proc.read("/proc/stat"))?.[1] ?? 0) * 1000; } catch {}
+ const rows: Array<{ pid: number; ppid: number; cpuMs: number; startedAt: number | null }> = [];
+ for (const name of names) {
+ if (!/^\d+$/.test(name)) continue;
+ let stat: string;
+ try { stat = proc.read(`/proc/${name}/stat`); } catch { continue; }
+ // pid (comm) state ppid …: comm may hold spaces and parentheses; utime, stime and starttime are fields 14, 15 and 22.
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
+ const ticks = (Number(fields[11]) || 0) + (Number(fields[12]) || 0), started = Number(fields[19]);
+ rows.push({ pid: Number(name), ppid: Number(fields[1]), cpuMs: ticks * (1000 / PROC_TICKS), startedAt: bootMs && Number.isFinite(started) ? bootMs + started * (1000 / PROC_TICKS) : null });
+ }
+ if (!rows.some((row) => row.pid === root)) return unknown;
+ const pids = since === undefined ? treePids(rows, root) : startedSince(rows, root, since);
+ if (!pids.length) return unknown;
+ const cpuMs = rows.filter((row) => pids.includes(row.pid)).reduce((sum, row) => sum + row.cpuMs, 0);
+ const sockets = new Set<string>();
+ const namespaces = new Map<string, number>();
+ for (const pid of pids) {
+ try { const ns = proc.link(`/proc/${pid}/ns/net`); if (!namespaces.has(ns)) namespaces.set(ns, pid); } catch {}
+ let fds: string[];
+ try { fds = proc.list(`/proc/${pid}/fd`); } catch { continue; }
+ for (const fd of fds) {
+ try { const inode = /^socket:\[(\d+)\]$/.exec(proc.link(`/proc/${pid}/fd/${fd}`))?.[1]; if (inode) sockets.add(inode); } catch {}
+ }
+ }
+ let connections = 0, readable = false;
+ for (const pid of namespaces.size ? namespaces.values() : [root]) {
+ for (const table of ["tcp", "tcp6"]) {
+ let text: string;
+ try { text = proc.read(`/proc/${pid}/net/${table}`); readable = true; } catch { continue; }
+ for (const line of text.split("\n").slice(1)) {
+ // sl local_address rem_address st … inode: st 01 is ESTABLISHED; addresses are hex, the port after the colon.
+ const cols = line.trim().split(/\s+/);
+ if (cols.length >= 10 && cols[3] === "01" && sockets.has(cols[9]!)) connections += 1;
+ }
+ }
+ }
+ return { cpuMs, connections: readable ? connections : null };
+}
+
/** A missing tool or a refused query reads as null (unknown), never as idle. With `since`, only the processes the tree
* started from then on count, without the root: what one tool call is running, not the engine or its tool servers. */
export function sampleProcessTree(pid: number, since?: number): Promise<ProcessSample> {
+ if (process.platform === "linux") {
+ try { return Promise.resolve(sampleLinuxProc(pid, since)); } catch { return Promise.resolve({ cpuMs: null, connections: null }); }
+ }
return (process.platform === "win32" ? sampleWindows(pid, since) : samplePosix(pid, since))
.catch(() => ({ cpuMs: null, connections: null }));
}
+/** A model request that failed on a usage or rate limit: an engine that then goes quiet is waiting that limit out
+ * (OpenCode 1.18 sleeps for the provider's whole retry-after, uncapped, five times over). */
+export const LIMIT_WORDS = /\b429\b|rate.?limit|too many requests|usage limit|quota|GoUsageLimitError|FreeUsageLimitError|insufficient_quota|credits? (?:exhausted|used up)|out of credits/i;
+
+/** How long an engine may stay quiet after a model request failed on a limit before the turn is ended as a usage limit,
+ * so the bot carries on with another AI: longer than any retry an engine makes without a provider's retry-after
+ * (OMB_ACP_LIMIT_QUIET_MS overrides). */
+export const DEFAULT_LIMIT_QUIET_MS = 2 * 60_000;
+export const limitQuietMs = (): number => knob("OMB_ACP_LIMIT_QUIET_MS", DEFAULT_LIMIT_QUIET_MS);
+
+/** No open request, no CPU and nothing logged, this long: the engine is stuck, and the turn is stopped
+ * (OMB_ACP_NO_SIGNS_STOP_MS overrides). */
+export const DEFAULT_NO_SIGNS_STOP_MS = 5 * 60_000;
+export const noSignsStopMs = (): number => knob("OMB_ACP_NO_SIGNS_STOP_MS", DEFAULT_NO_SIGNS_STOP_MS);
+
+/** Whether this quiet state is an engine waiting out a usage or rate limit. */
+export function waitingOutLimit(signal: LogSignal | null): boolean {
+ if (!signal) return false;
+ if (signal.kind === "provider-error") return LIMIT_WORDS.test(signal.message);
+ return signal.kind === "retry" && signal.status === 429 && (signal.delayMs ?? 0) > limitQuietMs();
+}
+
+/** A quiet turn after it is classified: no sign of life reads as "between requests" until `stuckAfterMs`, and the turn
+ * ends, with the error its prompt fails with, when the engine is waiting out a usage limit `limitQuietMs()` after the
+ * request that failed on it, or has shown no sign of life for `noSignsStopMs()`. */
+export function quietVerdict(input: {
+ next: QuietState; logged: { signal: LogSignal; at: number } | null; noSignsSince: number | null; now: number; quietMs: number; name: string; stuckAfterMs: number;
+}): { next: QuietState; noSignsSince: number | null; stop: Error | null } {
+ let next = input.next, noSignsSince = input.noSignsSince;
+ if (next.kind === "no-signs") {
+ noSignsSince ??= input.now;
+ if (input.now - noSignsSince < input.stuckAfterMs) next = { kind: "between-requests" };
+ } else {
+ noSignsSince = null;
+ }
+ const limited = input.logged && waitingOutLimit(input.logged.signal) && input.now - input.logged.at >= limitQuietMs() ? input.logged.signal : null;
+ if (limited) {
+ const said = limited.kind === "provider-error" ? ` (“${limited.message}”)` : "";
+ return { next, noSignsSince, stop: Object.assign(new Error(`${input.name} reached a usage limit${said} and is waiting it out without replying, so this turn was stopped.`), { acpUsageLimit: true }) };
+ }
+ if (noSignsSince !== null && input.now - noSignsSince >= noSignsStopMs()) {
+ return { next, noSignsSince, stop: Object.assign(new Error(`${input.name} sent nothing for ${formatQuietLimit(input.quietMs)} with no tool running, no open request to its model and no CPU use, so the turn was stopped as stuck. Send the message again to retry.`), { acpPromptStall: true }) };
+ }
+ return { next, noSignsSince, stop: null };
+}
+
const BUSY_CPU_MS_PER_MIN = 3_000;
export function classifyQuiet(input: {
diff --git a/server/drivers/claude-auth-recovery.test.ts b/server/drivers/claude-auth-recovery.test.ts
index a6951121e3..dfe6dadd60 100644
--- a/server/drivers/claude-auth-recovery.test.ts
+++ b/server/drivers/claude-auth-recovery.test.ts
@@ -172,12 +172,24 @@ describe("a usage-limit refusal", () => {
it("rejects the turn with its reset once the process has stopped, publishing nothing", async () => {
const f = fixture();
await expect(f.send(() => refuse(f))).rejects.toMatchObject({
- name: "TurnUsageLimitRefusedError", turnId: "turn", message: limitError.message, resetsAt: 1_760_888_400_000,
+ name: "TurnUsageLimitRefusedError", turnId: "turn", message: limitError.message, resetsAt: 1_760_888_400_000, scope: "engine", known: false,
});
expect(f.stopped).toHaveBeenCalledOnce();
expect(f.events.map(event => event.type)).toEqual(["turn.started"]);
});
+ it("says which limit it was, so one model's own limit holds that model alone", async () => {
+ const f = fixture();
+ const modelLimit = { ...limitError, limit: "model", limitResetsAt: 1_761_000_000_000 } as RuntimeEvent;
+ await expect(f.send(() => {
+ f.recovery.frame("thread", { type: "rate_limit_event" });
+ f.recovery.frame("thread", limitFrame);
+ f.recovery.emit(modelLimit);
+ f.recovery.frame("thread", result);
+ f.recovery.emit(quota);
+ })).rejects.toMatchObject({ name: "TurnUsageLimitRefusedError", resetsAt: 1_761_000_000_000, scope: "model" });
+ });
+
it("publishes the limit as usual when recovery is off or the model already worked", async () => {
const off = fixture();
await expect(off.send(() => refuse(off), false)).resolves.toEqual({ turnId: "turn" });
diff --git a/server/drivers/claude-auth-recovery.ts b/server/drivers/claude-auth-recovery.ts
index 85de1d2cb7..83e6b9bdd2 100644
--- a/server/drivers/claude-auth-recovery.ts
+++ b/server/drivers/claude-auth-recovery.ts
@@ -6,7 +6,7 @@ type Frame = {
is_error?: unknown; isReplay?: unknown; total_cost_usd?: unknown;
message?: { model?: unknown; content?: unknown };
};
-type Refusal = { text: string; kind: "auth" | "limit"; said?: string; resetsAt?: number };
+type Refusal = { text: string; kind: "auth" | "limit"; said?: string; resetsAt?: number; scope?: "engine" | "model" | "credits" };
type Pending = { refusal?: Refusal; refused?: boolean; buffered: RuntimeEvent[]; settle: (error?: Error) => void };
/** Only CLI-marked API errors count; assistant prose about signing out does not. */
@@ -65,7 +65,7 @@ export function claudeAuthRecovery(
const refusal = held.refusal;
if (refusal?.kind === "auth" && event.type === "runtime.error" && event.setup && event.message === refusal.text) return void held.buffered.push(event);
if (refusal?.kind === "limit" && event.type === "runtime.error" && !event.setup) {
- Object.assign(refusal, { said: event.message, resetsAt: event.limitResetsAt });
+ Object.assign(refusal, { said: event.message, resetsAt: event.limitResetsAt, scope: event.limit });
return void held.buffered.push(event);
}
if (refusal && held.refused && event.type === "turn.completed" && !event.ok && event.stopReason === refusedStop[refusal.kind] && typeof event.turnId === "string") {
@@ -76,7 +76,7 @@ export function claudeAuthRecovery(
if (!stopped) return accept(event.threadId, held);
pending.delete(event.threadId);
held.settle(refusal.kind === "auth" ? new TurnAuthenticationRefusedError(turnId, refusal.text)
- : new TurnUsageLimitRefusedError(turnId, refusal.said ?? refusal.text, refusal.resetsAt));
+ : new TurnUsageLimitRefusedError(turnId, refusal.said ?? refusal.text, refusal.resetsAt, refusal.scope));
}, () => accept(event.threadId, held));
}
accept(event.threadId, held);
diff --git a/server/drivers/claude-auth.test.ts b/server/drivers/claude-auth.test.ts
index d0d5b035fb..30c43299ee 100644
--- a/server/drivers/claude-auth.test.ts
+++ b/server/drivers/claude-auth.test.ts
@@ -4,7 +4,7 @@ import { describe, expect, it } from "vitest";
import { claudeSignedIn } from "./claude-auth-status.ts";
import { claudeAuthFailure } from "./claude-auth-recovery.ts";
import { claudeResultError, claudeVersionTooOld } from "./claude.ts";
-import { claudeApiErrorMessage, claudeEngineReset, claudeLimitMessage, claudeLimitRefusal, claudeUsageLimit } from "./claude-limits.ts";
+import { claudeApiErrorMessage, claudeEngineReset, claudeLimitFacts, claudeLimitMessage, claudeLimitRefusal, claudeUsageLimit } from "./claude-limits.ts";
import { classifyError } from "./retry.ts";
describe("claudeSignedIn", () => {
@@ -109,6 +109,14 @@ describe("Claude usage limits", () => {
expect(claudeEngineReset(null)).toBeUndefined();
});
+ it("names what a limit refuses for the runtime error: the model's credits, its own window with that reset, or the account", () => {
+ expect(claudeLimitFacts(claudeLimitRefusal(OUT_OF_CREDITS)), "no countdown to the billing period's end").toEqual({ limit: "credits" });
+ expect(claudeLimitFacts(claudeLimitRefusal({ ...WEEKLY, rateLimitType: "seven_day_opus" }))).toEqual({ limit: "model", limitResetsAt: 1791795600_000 });
+ expect(claudeLimitFacts(claudeLimitRefusal(WEEKLY))).toEqual({ limit: "engine", limitResetsAt: 1791795600_000 });
+ expect(claudeLimitFacts(claudeLimitRefusal({ status: "rejected" }))).toEqual({ limit: "engine" });
+ expect(claudeLimitFacts(null)).toEqual({ limit: "engine" });
+ });
+
it("says a model's credits ran out, with no countdown to the billing reset", () => {
const message = claudeLimitMessage(claudeLimitRefusal(OUT_OF_CREDITS), undefined, BEFORE_RESET, "America/Los_Angeles");
expect(message).toContain("runs on extra usage for your account, and those credits are used up");
diff --git a/server/drivers/claude-limits.ts b/server/drivers/claude-limits.ts
index 46f6f3acb3..8c6c4e09b7 100644
--- a/server/drivers/claude-limits.ts
+++ b/server/drivers/claude-limits.ts
@@ -57,6 +57,14 @@ export function claudeEngineReset(limit: ClaudeLimit | null | undefined): { limi
return { limitResetsAt: limit.resetsAt * 1000 };
}
+/** The runtime error's facts for a usage limit: what it refuses, and when that resets when Claude said. A model's own
+ * window resets that model alone; extra usage credits name only the billing period's end, which is no countdown. */
+export function claudeLimitFacts(limit: ClaudeLimit | null | undefined): { limit: "engine" | "model" | "credits"; limitResetsAt?: number } {
+ if (limit?.credits) return { limit: "credits" };
+ if (modelWindow(limit?.window)) return { limit: "model", ...(limit?.resetsAt ? { limitResetsAt: limit.resetsAt * 1000 } : {}) };
+ return { limit: "engine", ...claudeEngineReset(limit) };
+}
+
export function claudeLimitMessage(limit: ClaudeLimit | null, said?: string, now = Date.now(), timeZone = hostTimeZone()): string {
if (limit?.credits) {
return "Claude refused this turn because this model runs on extra usage for your account, and those credits are used up. " +
diff --git a/server/drivers/claude.test.ts b/server/drivers/claude.test.ts
index a4378c07a9..9149763400 100644
--- a/server/drivers/claude.test.ts
+++ b/server/drivers/claude.test.ts
@@ -692,7 +692,7 @@ describe("ClaudeDriver turns (fake CLI)", () => {
await instance.adapter.sendTurn({ threadId: "t-weekly", text: "Hey talk to @Tango" });
await recorder.until((event) => event.type === "turn.completed");
const errors = recorder.events.filter((event) => event.type === "runtime.error");
- expect(errors).toEqual([expect.objectContaining({ message: claudeLimitMessage({ window: "seven_day", resetsAt }), limitResetsAt: resetsAt * 1000 })]);
+ expect(errors).toEqual([expect.objectContaining({ message: claudeLimitMessage({ window: "seven_day", resetsAt }), limitResetsAt: resetsAt * 1000, limit: "engine" })]);
expect((errors[0] as any).message).toMatch(/^This Claude account has reached its weekly limit, which resets .+\. Until then, /);
expect(errors[0]).not.toHaveProperty("setup");
expect(errors[0]).not.toHaveProperty("claudeUpdate");
@@ -708,12 +708,23 @@ describe("ClaudeDriver turns (fake CLI)", () => {
await instance.adapter.sendTurn({ threadId: "t-credits", text: "continue" });
await recorder.until((event) => event.type === "turn.completed");
const errors = recorder.events.filter((event) => event.type === "runtime.error");
- expect(errors).toEqual([expect.objectContaining({ message: claudeLimitMessage({ window: null, resetsAt, credits: true }) })]);
+ expect(errors).toEqual([expect.objectContaining({ message: claudeLimitMessage({ window: null, resetsAt, credits: true }), limit: "credits" })]);
expect((errors[0] as any).message).toContain("those credits are used up");
expect(errors[0]).not.toHaveProperty("limitResetsAt");
expect(recorder.events.at(-1)).toMatchObject({ type: "turn.completed", ok: false, stopReason: "quota" });
});
+ it("settles a turn its model's own weekly window refused as that model's limit, with that window's reset", async () => {
+ const resetsAt = Math.floor(Date.now() / 1000) + 2 * 86_400;
+ const opus = { status: "rejected", resetsAt, rateLimitType: "seven_day_opus", overageStatus: "rejected", isUsingOverage: false };
+ await create("usage-limit", { FAKE_CLAUDE_RATE_LIMIT: JSON.stringify(opus) });
+ await instance.adapter.sendTurn({ threadId: "t-opus-window", text: "continue" });
+ await recorder.until((event) => event.type === "turn.completed");
+ const errors = recorder.events.filter((event) => event.type === "runtime.error");
+ expect(errors).toEqual([expect.objectContaining({ limit: "model", limitResetsAt: resetsAt * 1000 })]);
+ expect(recorder.events.at(-1)).toMatchObject({ type: "turn.completed", ok: false, stopReason: "quota" });
+ });
+
it("names the weekly limit behind an older CLI's update request, and offers no update", async () => {
const resetsAt = Math.floor(Date.now() / 1000) + 86_400;
await create("api-error", {
diff --git a/server/drivers/claude.ts b/server/drivers/claude.ts
index 9c55b76551..f2884cc165 100644
--- a/server/drivers/claude.ts
+++ b/server/drivers/claude.ts
@@ -38,7 +38,7 @@ import { assertToolScopeSupported } from "../../shared/tool-scope-support.ts";
import { newEventId, newId } from "../contracts.ts";
import { askInputSummary, commandSummary, toolDetailPreview } from "../tool-summary.ts";
import { classifyError, computeBackoff, interruptibleDelay, RETRY_MAX_ATTEMPTS, USAGE_LIMIT } from "./retry.ts";
-import { claudeApiErrorMessage, claudeEngineReset, claudeLimitRefusal, claudeUsageLimit, claudeLimitMessage, type ClaudeLimit } from "./claude-limits.ts";
+import { claudeApiErrorMessage, claudeLimitFacts, claudeLimitRefusal, claudeUsageLimit, claudeLimitMessage, type ClaudeLimit } from "./claude-limits.ts";
import { TEAM_TOOLS_FAILED, failedCustomMcp, teamToolsFailed } from "./team-tools.ts";
import { engineIdleMs, sessionIdlePolicy } from "./session-idle.ts";
import { promptHalves, withVolatileNote } from "./prompt-split.ts";
@@ -1444,7 +1444,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
t.limitReached = t.explained = true;
t.limit = claudeLimitRefusal(frame.api_error_params?.rate_limit_info) ?? t.limit;
const said = typeof words === "string" && USAGE_LIMIT.test(words) ? words : undefined;
- emit({ ...base(threadId, currentTurnId()), type: "runtime.error", message: claudeLimitMessage(t.limit ?? null, said), ...claudeEngineReset(t.limit) });
+ emit({ ...base(threadId, currentTurnId()), type: "runtime.error", message: claudeLimitMessage(t.limit ?? null, said), ...claudeLimitFacts(t.limit) });
};
const noteCostState = (total: unknown, modelUsage: unknown, usage: Parameters<typeof restoredCostBase>[2]) => {
const state = claudeCostSnapshot(total, modelUsage);
diff --git a/server/drivers/codex-errors.ts b/server/drivers/codex-errors.ts
index 4b95123d27..aa8ae25c27 100644
--- a/server/drivers/codex-errors.ts
+++ b/server/drivers/codex-errors.ts
@@ -52,10 +52,12 @@ export function codexLimitResetsAt(said: string, now = Date.now()): number | und
return Number.isFinite(at) ? at : undefined;
}
-/** The runtime.error fields a Codex usage-limit refusal adds: when it resets, if Codex said. */
-export function codexLimitFacts(raw: string, route: CodexRoute): { limitResetsAt?: number } {
+/** The runtime.error fields a Codex usage-limit refusal adds: that it is one, for the whole account or for one model
+ * ("You've hit your usage limit for gpt-6.1-sol. Switch to another model now…"), and when it resets, if Codex said. */
+export function codexLimitFacts(raw: string, route: CodexRoute, codexErrorInfo?: unknown): { limit?: "engine" | "model"; limitResetsAt?: number } {
+ if (codexErrorInfo !== "usageLimitExceeded" && !USAGE_LIMIT.test(raw) && !raw.includes("subscription_sharing_usage_limit_exceeded")) return {};
const at = route === "own" ? codexLimitResetsAt(raw) : undefined;
- return at === undefined ? {} : { limitResetsAt: at };
+ return { limit: /\busage limit for \S+?\.(?:\s|$)/i.test(raw) ? "model" : "engine", ...(at === undefined ? {} : { limitResetsAt: at }) };
}
export function codexUserError(value: string, route: CodexRoute, codexErrorInfo?: unknown): string {
diff --git a/server/drivers/codex.test.ts b/server/drivers/codex.test.ts
index 6d057124f0..e1ca51b475 100644
--- a/server/drivers/codex.test.ts
+++ b/server/drivers/codex.test.ts
@@ -15,7 +15,7 @@ import { recordEvents, type EventRecorder } from "../testing/events.ts";
import { CodexDriver, codexNativeIncomingLogMessage, codexUpdateCommand } from "./codex.ts";
import { codexCliOverrides } from "./codex-process.ts";
import * as codexProcess from "./codex-process.ts";
-import { CODEX_SIGN_IN_EXPIRED, codexNotSignedIn, codexSignInRefused, codexUserError } from "./codex-errors.ts";
+import { CODEX_SIGN_IN_EXPIRED, codexLimitFacts, codexNotSignedIn, codexSignInRefused, codexUserError } from "./codex-errors.ts";
import { CODEX_USAGE_LIMIT_REACHED } from "../../shared/codex-usage-limit.ts";
import { removeTempDir } from "../testing/cleanup.ts";
import { TEAM_TOOLS_FAILED } from "./team-tools.ts";
@@ -3313,6 +3313,13 @@ process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:m.id,result})+'\\n');});`)
expect(codexUserError("You've hit your usage limit.", "own")).not.toContain("resets at");
expect(codexUserError("Quota reached.", "own", "usageLimitExceeded")).toContain(CODEX_USAGE_LIMIT_REACHED);
expect(codexUserError(plus, "other")).toBe(plus);
+ expect(codexLimitFacts(plus, "own"), "the account's limit, with its reset on Codex's own sign-in").toEqual({ limit: "engine", limitResetsAt: expect.any(Number) });
+ expect(codexLimitFacts(plus, "plan")).toEqual({ limit: "engine" });
+ expect(codexLimitFacts("You've hit your usage limit for gpt-6.1-sol. Switch to another model now, or try again at Oct 17th, 2026 5:23 PM.", "own"))
+ .toEqual({ limit: "model", limitResetsAt: new Date(2026, 9, 17, 17, 23, 0).getTime() });
+ expect(codexLimitFacts("Quota reached.", "own", "usageLimitExceeded")).toEqual({ limit: "engine" });
+ expect(codexLimitFacts(`${"x".repeat(40)}subscription_sharing_usage_limit_exceeded`, "plan")).toEqual({ limit: "engine" });
+ expect(codexLimitFacts("stream disconnected before completion", "own")).toEqual({});
const noBearer = "unexpected status 401 Unauthorized: Missing bearer or basic authentication in header, url: https://api.openai.com/v1/responses";
expect(codexUserError(noBearer, "own")).toBe(codexNotSignedIn());
expect(codexUserError(noBearer, "other")).toBe(noBearer);
diff --git a/server/drivers/codex.ts b/server/drivers/codex.ts
index 008537dcd4..b9a0ef61cd 100644
--- a/server/drivers/codex.ts
+++ b/server/drivers/codex.ts
@@ -1126,7 +1126,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
if (message === state.lastError && (state.lastErrorSetup || !setup)) return;
state.lastError = message;
state.lastErrorSetup ||= setup;
- emit({ ...base(threadId, turnId), type: "runtime.error", message, ...(setup ? { setup: true } : {}), ...codexLimitFacts(raw, route) });
+ emit({ ...base(threadId, turnId), type: "runtime.error", message, ...(setup ? { setup: true } : {}), ...codexLimitFacts(raw, route, error.codexErrorInfo) });
};
const handleNotification = (msg: any) => {
const p = msg.params ?? {};
diff --git a/server/host/chief-notices.ts b/server/host/chief-notices.ts
index cae859e675..f3855b1cbf 100644
--- a/server/host/chief-notices.ts
+++ b/server/host/chief-notices.ts
@@ -152,7 +152,8 @@ export function createChiefNotices(deps: ChiefNoticeDeps) {
/** A failed teammate run gets one retry from OpenMausBot before its Chief hears; the Chief then hears how that retry ended.
* Never retried: a stall the turn watchdog stopped (kind "stalled"), a stop, a refusal or a cap (retriesTeammateThread,
* from the failure's words and `facts`), a run that answered a retry, and a thread whose asks are not the Chief's person's. */
- function reportIncident(input: { kind: IncidentKind; bot: BotRecord; threadId: string; detail: string; facts?: RoutineFailureFacts }): void {
+ /** `notified`: the person already heard of it another way (a usage limit's own notice), so only the Chief is told. */
+ function reportIncident(input: { kind: IncidentKind; bot: BotRecord; threadId: string; detail: string; facts?: RoutineFailureFacts; notified?: boolean }): void {
const { bot, threadId } = input;
if (deps.quietThread?.(bot.id, threadId)) return;
const task = store.taskByThread(bot.id, threadId);
@@ -173,7 +174,7 @@ export function createChiefNotices(deps: ChiefNoticeDeps) {
const report = (retry?: IncidentRetry): void => void deliver({
chief, title: INCIDENTS_THREAD_TITLE, bot, threadId,
chip: incidentChip(incident), text: incidentText(incident, count, retry),
- alreadyNotified: input.kind === "could-not-start" || input.kind === "routine-failed",
+ alreadyNotified: input.notified === true || input.kind === "could-not-start" || input.kind === "routine-failed",
});
if (!chief || group || !reachesChief(chief, bot, threadId)) return report();
const answered = store.activePath(threadId).findLast((line) => line.role === "user")?.text ?? "";
diff --git a/server/host/limit-takeover.test.ts b/server/host/limit-takeover.test.ts
new file mode 100644
index 0000000000..a2673f45a2
--- /dev/null
+++ b/server/host/limit-takeover.test.ts
@@ -0,0 +1,176 @@
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import type { RuntimeEvent } from "../../shared/runtime-events.ts";
+import type { ModelSelection } from "../../shared/wire.ts";
+import type { InstanceConfigMap } from "../contracts.ts";
+import { UNNAMED_LIMIT_MS } from "../limit-resets.ts";
+import { MODEL_HOLD_MS, createLimitTakeover, type LimitTakeoverDeps, type TakeoverEngine } from "./limit-takeover.ts";
+
+const NOW = Date.parse("2026-10-27T10:00:00Z");
+const HOUR = 3_600_000;
+const dirs: string[] = [];
+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });
+
+const TOOLS = { agentsMcp: true, customMcp: true, composioMcp: true } as unknown as TakeoverEngine["capabilities"];
+
+function engine(instanceId: string, driverKind: string, models: string[], extra: Partial<TakeoverEngine> = {}): TakeoverEngine {
+ return {
+ instanceId, driverKind,
+ snapshot: { state: "available", authenticated: true },
+ models: { default: models[0]!, options: models.map((id) => ({ id, label: id })) },
+ capabilities: TOOLS,
+ ...extra,
+ };
+}
+
+const CLAUDE = engine("claude", "claudeAgent", ["claude-opus-5-5", "claude-sonnet-5"]);
+const CODEX = engine("codex", "codex", ["gpt-6", "gpt-6-mini"]);
+const GO = engine("opencode", "opencode", ["go-default"]);
+const NAMES: Record<string, string> = { claude: "Claude", codex: "Codex", opencode: "OpenCode Go" };
+const on = (instanceId: string, model: string): ModelSelection => ({ instanceId, model });
+const KAI = { id: "kai", name: "Kai" };
+
+function takeover(overrides: Partial<LimitTakeoverDeps> = {}) {
+ const dir = mkdtempSync(join(tmpdir(), "omb-limit-takeover-"));
+ dirs.push(dir);
+ const now = { at: NOW };
+ const told: Array<{ bot: string; text: string }> = [];
+ const record = vi.fn();
+ const instance = createLimitTakeover({
+ file: join(dir, "limit-notices.json"),
+ engines: () => [CLAUDE, CODEX, GO],
+ configs: () => ({}),
+ context: {},
+ blockedUntil: () => null,
+ chosen: () => [],
+ engineName: (id) => NAMES[id] ?? id,
+ tell: (bot, text) => { told.push({ bot: bot.name, text }); },
+ record,
+ now: () => now.at,
+ ...overrides,
+ });
+ return { instance, told, record, now };
+}
+
+describe("which AI carries on while one is limited", () => {
+ it("never picks an AI that bills each use by itself, only as a backup the person chose", () => {
+ const apiClaude = engine("claude-api", "claudeAgent", ["claude-opus-5-5"], { access: "api" });
+ const keyedClaude = engine("claude-key", "claudeAgent", ["claude-opus-5-5"]);
+ const keyed = { "claude-key": { environment: { ANTHROPIC_API_KEY: "sk-ant-fixture" } } } as unknown as InstanceConfigMap;
+ expect(takeover({ engines: () => [CODEX, apiClaude] }).instance.backups("kai", on("codex", "gpt-6"))).toEqual([]);
+ expect(takeover({ engines: () => [CODEX, keyedClaude], configs: () => keyed }).instance.backups("kai", on("codex", "gpt-6"))).toEqual([]);
+ expect(takeover({ engines: () => [CODEX, apiClaude, GO] }).instance.backups("kai", on("codex", "gpt-6"))).toEqual([on("opencode", "go-default")]);
+ expect(takeover({ engines: () => [CODEX, apiClaude], chosen: () => [on("claude-api", "claude-opus-5-5")] }).instance.backups("kai", on("codex", "gpt-6")))
+ .toEqual([on("claude-api", "claude-opus-5-5")]);
+ });
+
+ it("takes the backups the person chose first, then the AI a new bot would get, and never the limited AI", () => {
+ const { instance } = takeover({ chosen: () => [on("opencode", "go-default"), on("codex", "gpt-6-mini")] });
+ expect(instance.backups("kai", on("codex", "gpt-6"))).toEqual([on("opencode", "go-default"), on("claude", "claude-opus-5-5")]);
+ expect(takeover().instance.backups("kai", on("codex", "gpt-6"))).toEqual([on("claude", "claude-opus-5-5")]);
+ });
+
+ it("for one model's own limit tries that AI's default model first, and never the limited model", () => {
+ const { instance } = takeover();
+ expect(instance.backups("kai", on("claude", "claude-sonnet-5"), "model")).toEqual([on("claude", "claude-opus-5-5"), on("codex", "gpt-6")]);
+ expect(instance.backups("kai", on("claude", "claude-opus-5-5"), "credits")).toEqual([on("codex", "gpt-6")]);
+ });
+
+ it("leaves out an AI that is signed out, held by its own limit, short of this AI's tools, or another sign-in to the same plan", () => {
+ const signedOut = engine("claude", "claudeAgent", ["claude-opus-5-5"], { snapshot: { state: "available", authenticated: false } });
+ expect(takeover({ engines: () => [signedOut, CODEX] }).instance.backups("kai", on("codex", "gpt-6"))).toEqual([]);
+ expect(takeover({ blockedUntil: (id) => (id === "claude" ? NOW + HOUR : null) }).instance.backups("kai", on("codex", "gpt-6")))
+ .toEqual([on("opencode", "go-default")]);
+ const fewerTools = engine("claude", "claudeAgent", ["claude-opus-5-5"], { capabilities: { agentsMcp: true } as unknown as TakeoverEngine["capabilities"] });
+ expect(takeover({ engines: () => [fewerTools, CODEX] }).instance.backups("kai", on("codex", "gpt-6"))).toEqual([]);
+ const secondCodex = engine("codex-2", "codex", ["gpt-6"]);
+ expect(takeover({ engines: () => [CODEX, secondCodex], chosen: () => [on("codex-2", "gpt-6")] }).instance.backups("kai", on("codex", "gpt-6")),
+ "never another sign-in to the same plan").toEqual([]);
+ const keyed = { "codex-2": { environment: { OPENAI_API_KEY: "sk-test" } } } as unknown as InstanceConfigMap;
+ expect(takeover({ engines: () => [CODEX, secondCodex], configs: () => keyed, chosen: () => [on("codex-2", "gpt-6")] }).instance.backups("kai", on("codex", "gpt-6")),
+ "a pay-per-use key on the same AI is fine as a backup the person chose").toEqual([on("codex-2", "gpt-6")]);
+ });
+
+ it("has none for an AI it doesn't know", () => {
+ expect(takeover().instance.backups("kai", on("gone", "m"))).toEqual([]);
+ });
+});
+
+describe("a model's own limit", () => {
+ const error = (limit: "model" | "credits" | "engine", limitResetsAt?: number) => ({
+ eventId: "e", provider: "claudeAgent", createdAt: new Date(NOW).toISOString(), threadId: "t1",
+ type: "runtime.error", message: "limit", limit, ...(limitResetsAt ? { limitResetsAt } : {}),
+ }) as RuntimeEvent;
+
+ it("holds that model alone until the reset it named, at most six hours, an hour when it named none, and not once it works", () => {
+ const { instance, now } = takeover();
+ instance.noteRuntimeEvent(on("claude", "claude-opus-5-5"), error("model", NOW + 2 * HOUR));
+ expect(instance.modelHeld(on("claude", "claude-opus-5-5"))).toEqual({ until: NOW + 2 * HOUR, resetsAt: NOW + 2 * HOUR, scope: "model" });
+ expect(instance.modelHeld(on("claude", "claude-sonnet-5")), "the AI's other models still work").toBeNull();
+ instance.noteRuntimeEvent(on("claude", "claude-opus-5-5"), error("model", NOW + 50 * HOUR));
+ expect(instance.modelHeld(on("claude", "claude-opus-5-5")), "tried again after six hours, the named reset kept")
+ .toEqual({ until: NOW + MODEL_HOLD_MS, resetsAt: NOW + 50 * HOUR, scope: "model" });
+ instance.holdModel(on("claude", "claude-sonnet-5"), "credits");
+ expect(instance.modelHeld(on("claude", "claude-sonnet-5"))).toEqual({ until: NOW + UNNAMED_LIMIT_MS, scope: "credits" });
+ instance.noteRuntimeEvent(on("codex", "gpt-6"), error("engine"));
+ expect(instance.modelHeld(on("codex", "gpt-6")), "an engine's own limit is the reset clock's to hold").toBeNull();
+ expect(instance.backups("kai", on("codex", "gpt-6")), "a held model carries on nothing").toEqual([on("opencode", "go-default")]);
+
+ instance.worked("kai", on("claude", "claude-opus-5-5"));
+ expect(instance.modelHeld(on("claude", "claude-opus-5-5"))).toBeNull();
+ now.at = NOW + UNNAMED_LIMIT_MS + 1;
+ expect(instance.modelHeld(on("claude", "claude-sonnet-5"))).toBeNull();
+ });
+});
+
+describe("what the person hears", () => {
+ it("says once per bot for each stretch of a limit what carries on, and again once a turn on that AI worked", () => {
+ const { instance, told } = takeover();
+ const resetsAt = NOW + 4 * HOUR;
+ instance.tell(KAI, on("codex", "gpt-6"), { resetsAt, scope: "engine", backup: on("claude", "claude-opus-5-5") });
+ instance.tell(KAI, on("codex", "gpt-6"), { resetsAt, scope: "engine", backup: on("claude", "claude-opus-5-5") });
+ instance.tell({ id: "rosa", name: "Rosa" }, on("codex", "gpt-6"), { resetsAt });
+ expect(told.map((entry) => entry.bot)).toEqual(["Kai", "Rosa"]);
+ expect(told[0]!.text).toMatch(/^Codex reached its limit until .+, so Kai is using Claude meanwhile\.$/);
+ expect(told[1]!.text).toMatch(/^Codex reached its limit until .+, so Rosa waits until then: no other AI you have set up can take over\.$/);
+ instance.worked("kai", on("codex", "gpt-6"));
+ instance.tell(KAI, on("codex", "gpt-6"), { resetsAt, backup: on("claude", "claude-opus-5-5") });
+ expect(told).toHaveLength(3);
+ });
+
+ it("names the model for a model's own limit, and the same AI's other model when that carries on", () => {
+ const { instance, told } = takeover();
+ instance.tell(KAI, on("claude", "claude-sonnet-5"), { scope: "credits", backup: on("claude", "claude-opus-5-5") });
+ instance.tell(KAI, on("claude", "claude-opus-5-5"), { scope: "model", backup: on("codex", "gpt-6") });
+ expect(told.map((entry) => entry.text)).toEqual([
+ "Claude claude-sonnet-5's extra usage credits are used up, so Kai is using Claude claude-opus-5-5 meanwhile.",
+ "Claude claude-opus-5-5 reached its limit, so Kai is using Codex meanwhile.",
+ ]);
+ });
+
+ it("files one incident per bot for each stretch of a limit, apart from the person's notice", () => {
+ const { instance, told } = takeover();
+ const resetsAt = NOW + 4 * HOUR;
+ instance.tell(KAI, on("codex", "gpt-6"), { resetsAt });
+ expect(instance.firstIncident("kai", on("codex", "gpt-6"), "engine", resetsAt), "the notice is not the incident").toBe(true);
+ expect(instance.firstIncident("kai", on("codex", "gpt-6"), "engine", resetsAt)).toBe(false);
+ expect(instance.firstIncident("rosa", on("codex", "gpt-6"), "engine", resetsAt)).toBe(true);
+ expect(instance.firstIncident("kai", on("claude", "claude-opus-5-5"), "model"), "another limit is another stretch").toBe(true);
+ instance.worked("kai", on("codex", "gpt-6"));
+ expect(instance.firstIncident("kai", on("codex", "gpt-6"), "engine", resetsAt), "a new stretch once it worked").toBe(true);
+ expect(told).toHaveLength(1);
+ });
+
+ it("records a conversation that moved, so it goes back once the limit resets", () => {
+ const { instance, record } = takeover();
+ instance.moved("kai", "t1", on("codex", "gpt-6"), on("claude", "claude-opus-5-5"), NOW + HOUR);
+ instance.moved("kai", "t2", on("codex", "gpt-6"), on("claude", "claude-opus-5-5"));
+ expect(record.mock.calls.map(([failover]) => failover)).toEqual([
+ { botId: "kai", threadId: "t1", from: on("codex", "gpt-6"), to: on("claude", "claude-opus-5-5"), resetsAt: NOW + HOUR, at: NOW },
+ { botId: "kai", threadId: "t2", from: on("codex", "gpt-6"), to: on("claude", "claude-opus-5-5"), resetsAt: null, at: NOW },
+ ]);
+ });
+});
diff --git a/server/host/limit-takeover.ts b/server/host/limit-takeover.ts
new file mode 100644
index 0000000000..aa806604de
--- /dev/null
+++ b/server/host/limit-takeover.ts
@@ -0,0 +1,136 @@
+// When the AI a bot runs on reaches its usage limit, the bot carries on with another AI the person has set up until that
+// limit resets, without anyone being asked, and the person hears it once for that stretch of the limit.
+import { recoveryCapabilityError } from "../automatic-recovery.ts";
+import type { InstanceConfigMap, ProviderAdapter, RuntimeEvent } from "../contracts.ts";
+import { readyToRun, selectDefaultModelSelection, type DefaultSelectionContext, type SelectableInstance } from "../default-model-selection.ts";
+import { billsEachUse, limitBackupAllowed, type LimitFailover } from "../limit-failover.ts";
+import { LimitNotices, limitNoticeText } from "../limit-notices.ts";
+import { UNNAMED_LIMIT_MS } from "../limit-resets.ts";
+import type { ModelSelection } from "../../shared/wire.ts";
+
+/** What a usage limit refused (the runtime error's `limit`): the account on that engine, one model's own window, or
+ * one model's extra usage credits. */
+export type LimitScope = "engine" | "model" | "credits";
+
+/** A model's own limit holds that model at most this long before it is tried again, in case its window ended early. */
+export const MODEL_HOLD_MS = 6 * 60 * 60_000;
+
+/** A model held by its own limit: until when, when the limit said it resets, and which limit it is. */
+export interface ModelHold { until: number; resetsAt?: number; scope: "model" | "credits" }
+
+export type TakeoverEngine = SelectableInstance & { displayName?: string; capabilities: ProviderAdapter["capabilities"] };
+type Bot = { id: string; name: string };
+
+export interface LimitTakeoverDeps {
+ file: string;
+ /** Every engine here as last read: no probe, so a turn never waits on one. */
+ engines(): TakeoverEngine[];
+ configs(): InstanceConfigMap;
+ context: DefaultSelectionContext;
+ /** Until when this engine refuses work, or null. */
+ blockedUntil(instanceId: string): number | null;
+ /** The backups the person chose for this bot, or for every bot. */
+ chosen(botId: string): ModelSelection[];
+ engineName(instanceId: string): string;
+ tell(bot: Bot, text: string): void;
+ /** A conversation moved off a limited AI: it goes back once that limit resets. */
+ record(failover: LimitFailover): void;
+ now?(): number;
+}
+
+export function createLimitTakeover(deps: LimitTakeoverDeps) {
+ const now = deps.now ?? Date.now;
+ const notices = new LimitNotices(deps.file, now);
+ const heldModels = new Map<string, ModelHold>();
+ const modelKey = (selection: ModelSelection) => `${selection.instanceId}\u0000${selection.model}`;
+ const incidentKey = (botId: string) => `incident\u0000${botId}`;
+
+ const modelHeld = (selection: ModelSelection): ModelHold | null => {
+ const held = heldModels.get(modelKey(selection));
+ if (!held) return null;
+ if (held.until > now()) return held;
+ heldModels.delete(modelKey(selection));
+ return null;
+ };
+
+ const holdModel = (selection: ModelSelection, scope: "model" | "credits", resetsAt?: number): void => {
+ const at = now(), named = resetsAt !== undefined && resetsAt > at ? resetsAt : undefined;
+ heldModels.set(modelKey(selection), { until: Math.min(named ?? at + UNNAMED_LIMIT_MS, at + MODEL_HOLD_MS), ...(named ? { resetsAt: named } : {}), scope });
+ };
+
+ const usable = (engines: TakeoverEngine[], current: TakeoverEngine, selection: ModelSelection): boolean => {
+ const engine = engines.find((candidate) => candidate.instanceId === selection.instanceId);
+ if (!engine || !readyToRun(engine, deps.context) || deps.blockedUntil(engine.instanceId) !== null || modelHeld(selection) !== null) return false;
+ if (engine.instanceId !== current.instanceId && !limitBackupAllowed(current, engine, deps.configs()[engine.instanceId])) return false;
+ if (recoveryCapabilityError(current, engine)) return false;
+ return engine.models.default === selection.model || engine.models.options.some((model) => model.id === selection.model);
+ };
+
+ /** The AIs that may carry on while `from` is limited, best first: for one model's limit the same AI's own default
+ * model, then the backups the person chose, then the AI OpenMausBot would pick for a new bot among the rest that draw on
+ * a plan. One that bills each use spends the person's money, so it carries on only as a backup they chose. */
+ function backups(botId: string, from: ModelSelection, scope: LimitScope = "engine"): ModelSelection[] {
+ const engines = deps.engines();
+ const current = engines.find((engine) => engine.instanceId === from.instanceId);
+ if (!current) return [];
+ const out: ModelSelection[] = [];
+ const add = (selection: ModelSelection) => {
+ if (selection.instanceId === from.instanceId && (scope === "engine" || selection.model === from.model)) return;
+ if (out.some((known) => known.instanceId === selection.instanceId && known.model === selection.model)) return;
+ if (usable(engines, current, selection)) out.push({ instanceId: selection.instanceId, model: selection.model });
+ };
+ if (scope !== "engine") add({ instanceId: current.instanceId, model: current.models.default });
+ for (const selection of deps.chosen(botId)) add(selection);
+ const others = engines.filter((engine) => engine.instanceId !== from.instanceId && engine.access !== "api" && !billsEachUse(deps.configs()[engine.instanceId])
+ && usable(engines, current, { instanceId: engine.instanceId, model: engine.models.default }));
+ const pick = selectDefaultModelSelection(others, undefined, deps.context);
+ if (pick.instanceId && pick.model) add(pick);
+ return out;
+ }
+
+ const label = (selection: ModelSelection, from: ModelSelection) => (selection.instanceId === from.instanceId
+ ? `${deps.engineName(selection.instanceId)} ${selection.model}` : deps.engineName(selection.instanceId));
+
+ return {
+ backups,
+ /** This model alone, held by its own limit; null when it is not. */
+ modelHeld,
+ /** This model's own limit refused a turn: it is held until the reset the limit named, an hour when it named none,
+ * and at most MODEL_HOLD_MS. */
+ holdModel,
+ /** Every runtime event of a bot's thread, with the model it runs on: a model's own limit holds that model. */
+ noteRuntimeEvent(selection: ModelSelection | undefined, event: RuntimeEvent): void {
+ if (!selection || event.type !== "runtime.error" || (event.limit !== "model" && event.limit !== "credits")) return;
+ holdModel(selection, event.limit, event.limitResetsAt);
+ },
+ /** Once for this stretch of `from`'s limit: which AI carries on for `bot` meanwhile, or that it waits. */
+ tell(bot: Bot, from: ModelSelection, facts: { resetsAt?: number; scope?: LimitScope; backup?: ModelSelection }): void {
+ const scope = facts.scope ?? "engine";
+ const limited = scope === "engine" ? from.instanceId : modelKey(from);
+ if (!notices.first(bot.id, limited, facts.resetsAt)) return;
+ deps.tell(bot, limitNoticeText({
+ engine: scope === "engine" ? deps.engineName(from.instanceId) : `${deps.engineName(from.instanceId)} ${from.model}`,
+ bot: bot.name, ...(facts.resetsAt ? { resetsAt: facts.resetsAt } : {}), ...(scope === "credits" ? { credits: true } : {}),
+ ...(facts.backup ? { backup: label(facts.backup, from) } : {}),
+ }));
+ },
+ /** A conversation of `botId` moved from `from` to `to` because of `from`'s limit; it goes back once that resets. */
+ moved(botId: string, threadId: string, from: ModelSelection, to: ModelSelection, resetsAt?: number): void {
+ deps.record({ botId, threadId, from, to, resetsAt: resetsAt ?? null, at: now() });
+ },
+ /** True once per bot for each stretch of this limit: the one incident its Chief is told about, not one per refused turn. */
+ firstIncident(botId: string, from: ModelSelection, scope: LimitScope = "engine", resetsAt?: number): boolean {
+ return notices.first(incidentKey(botId), scope === "engine" ? from.instanceId : modelKey(from), resetsAt);
+ },
+ /** A turn on `selection` worked for this bot: its engine's next limit is a new stretch, with a notice of its own. */
+ worked(botId: string, selection: ModelSelection): void {
+ for (const who of [botId, incidentKey(botId)]) {
+ notices.ended(who, selection.instanceId);
+ notices.ended(who, modelKey(selection));
+ }
+ heldModels.delete(modelKey(selection));
+ },
+ };
+}
+
+export type LimitTakeover = ReturnType<typeof createLimitTakeover>;
diff --git a/server/host/quota-switch.ts b/server/host/quota-switch.ts
index d950f8938a..d56c97290e 100644
--- a/server/host/quota-switch.ts
+++ b/server/host/quota-switch.ts
@@ -9,7 +9,7 @@ import type { BotRecord, Message } from "../store.ts";
import type { UsageTrigger } from "../usage-ledger.ts";
import { resolveYourComputerAsk } from "../your-computer-consent.ts";
-export interface QuotaSwitchHostDeps extends Pick<QuotaSwitchDeps, "store" | "coordinator" | "turnStops"> {
+export interface QuotaSwitchHostDeps extends Pick<QuotaSwitchDeps, "store" | "coordinator" | "turnStops" | "takeover"> {
registry: Pick<ProviderRegistry, "instances" | "access">;
approvalBus: ApprovalBus;
hostedModels: ReturnType<typeof hostedModelPolicy>;
@@ -29,11 +29,11 @@ export interface QuotaSwitchHostDeps extends Pick<QuotaSwitchDeps, "store" | "co
export function createQuotaSwitchHost(deps: QuotaSwitchHostDeps) {
const {
store, coordinator, registry, turnStops, approvalBus, hostedModels, providerConfigs, policyModelRefusal,
- checkedTaskModelSwitch, threadBusy, directRequestOwners, startOrQueueDirectMessage,
+ checkedTaskModelSwitch, threadBusy, directRequestOwners, startOrQueueDirectMessage, takeover,
} = deps;
const quotaSwitch = createQuotaSwitch({
- store, coordinator, registry, turnStops,
+ store, coordinator, registry, turnStops, takeover,
access: instanceId => providerConfigs()[instanceId]?.access ?? registry.access(instanceId),
refusal: policyModelRefusal,
gate: (thread, selection) => checkedTaskModelSwitch(thread, selection, false, false, true),
diff --git a/server/index.ts b/server/index.ts
index 886a7da3e2..38833480ab 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -208,9 +208,9 @@ import {
} from "./contracts.ts";
import { RETRY_MAX_ATTEMPTS } from "./drivers/retry.ts";
import { recoveryCapabilityError } from "./automatic-recovery.ts";
-import { createQuotaSwitchHost } from "./host/quota-switch.ts";
+import { createQuotaSwitchHost } from "./host/quota-switch.ts"; import { quotaSwitchEnabled } from "./quota-switch.ts";
import { decodeGeneratedImage } from "./generated-image.ts";
-import { createMcpServersHost } from "./host/mcp-servers-host.ts";
+import { createMcpServersHost } from "./host/mcp-servers-host.ts"; import { createLimitTakeover } from "./host/limit-takeover.ts";
import {
isRemoteMcpServer,
listMcpServers,
@@ -6475,7 +6475,7 @@ bus.subscribe((event: RuntimeEvent) => {
const routineRun = privateImageEvent ? null : (routines?.handleRuntimeEvent(event) ?? null);
limitClock.noteRuntimeEvent(runningTurnEngines.get(event.threadId)?.instanceId, event);
const ownerBot = store.botByThread(event.threadId);
- const bot = ownerBot ? botForThread(ownerBot.id, event.threadId) ?? undefined : undefined;
+ const bot = ownerBot ? botForThread(ownerBot.id, event.threadId) ?? undefined : undefined; if (bot) { limitTakeover.noteRuntimeEvent(bot.modelSelection, event); if (event.type === "turn.completed" && event.ok) limitTakeover.worked(bot.id, bot.modelSelection); }
const group = bot ? undefined : store.groupByThread(event.threadId);
if (!bot && !group) return;
const speaker = group ? groupSpeakers.get(event.threadId) : undefined;
@@ -6879,7 +6879,7 @@ bus.subscribe((event: RuntimeEvent) => {
const failureDetail = turnStops.failureCause(event) ?? "the run ended without a result";
// Filed once the thread has settled, so the Chief's retry finds it free. A turn the person stopped is cancelled, whatever its engine said.
const facts = { ...turnStops.read(event.threadId, event.turnId)?.flags, stopReason: directRequestOwners.get(event.threadId)?.stopped ? "cancelled" : event.stopReason };
- const fileIncident = () => { if (broken) reportIncident({ kind: "failed", bot: broken, threadId: event.threadId, detail: failureDetail, facts }); };
+ const fileIncident = () => { if (broken && (!facts.limit || limitTakeover.firstIncident(broken.id, broken.modelSelection, facts.limit, facts.limitResetsAt))) reportIncident({ kind: "failed", bot: broken, threadId: event.threadId, detail: failureDetail, facts, notified: Boolean(facts.limit) }); };
if (failed && bot) void quotaSwitch.turnFailed(bot, event, internal);
else if (bot && event.ok) quotaSwitch.turnSucceeded(bot, event.threadId);
const question = bot && event.ok && !stopped && completedTurnId && !routineRun && chiefEscalationsEnabled(cfg) ? needsInputQuestion(store.activePath(event.threadId)
@@ -8604,8 +8604,9 @@ async function startTurn(
const clock = takesTurnClock(userTurnText) ? turnClockLine(Date.now(), hostTimeZone()) + nearLimitNote(limitClock.limit(instanceId), engineName(instanceId), hostTimeZone()) : "";
const shareNote = skillsHost.shareNote(bot, threadId, Boolean(privateWorkspace));
const startupRecovery = cfg.automaticRecovery?.enabled === true && (opts?.automaticRecoveryIndex ?? 0) < ((liveBot ?? bot).fallback?.length || (cfg.automaticRecovery.backup ? 1 : 0));
- const limitedUntil = startupRecovery ? limitClock.blockedUntil(instanceId) : null;
- if (limitedUntil) throw new TurnUsageLimitRefusedError(`limit-${randomUUID()}`, `${engineName(instanceId)} is at its usage limit.`, limitedUntil);
+ const engineHeld = limitClock.blockedUntil(instanceId), modelHeld = engineHeld ? null : limitTakeover.modelHeld({ instanceId, model }), limitScope = engineHeld ? "engine" as const : modelHeld?.scope ?? "engine", limitResets = engineHeld ? limitClock.resetAt(instanceId) ?? undefined : modelHeld?.resetsAt;
+ // A limit already known: the turn goes straight to an AI that can carry on, with the reset only when one was named.
+ if ((engineHeld || modelHeld) && (startupRecovery || (quotaSwitchEnabled() && limitTakeover.backups(bot.id, { instanceId, model }, limitScope).length))) throw new TurnUsageLimitRefusedError(`limit-${randomUUID()}`, `${engineName(instanceId)} is at its usage limit.`, limitResets && limitResets > Date.now() ? limitResets : undefined, limitScope, true);
const dispatch = await guardTurnDispatch(shareNote.after(quickFallback.sendTurn(instance, {
threadId,
botId: bot.id,
@@ -8683,7 +8684,7 @@ async function startTurn(
directTurnClaimIsCurrent(bot.id, dispatchClaimId, threadId);
if (e instanceof TurnNotStartedError) {
retireProviderTurn(e.turnId);
- if (e instanceof TurnUsageLimitRefusedError) limitClock.noteRefusal(instanceId, e.resetsAt);
+ if (e instanceof TurnUsageLimitRefusedError && !e.known) { if (e.scope === "engine") limitClock.noteLimit(instanceId, e.resetsAt); else limitTakeover.holdModel({ instanceId, model }, e.scope, e.resetsAt); }
if (!mayRecover) e = new DirectTurnSetupCancelled("turn stopped during provider setup");
}
handoffs.abandon(threadId, dispatchClaimId);
@@ -8731,11 +8732,11 @@ async function startTurn(
if (e instanceof PlaceUnavailableError) clearFailedAutoPin(bot.id, threadId, e.place);
let message = e instanceof Error ? e.message : String(e);
const current = store.projectBotForTask(bot.id, threadId);
- const backups = cfg.automaticRecovery?.enabled
+ const backups = e instanceof TurnUsageLimitRefusedError && current && quotaSwitchEnabled() ? limitTakeover.backups(bot.id, current.modelSelection, e.scope) : cfg.automaticRecovery?.enabled
? current?.fallback?.length ? current.fallback : cfg.automaticRecovery.backup ? [cfg.automaticRecovery.backup] : []
: [];
const nextIndex = backups.findIndex((candidate, index) => index >= (opts?.automaticRecoveryIndex ?? 0) &&
- registry.get(candidate.instanceId)?.enabled && (e instanceof TurnUsageLimitRefusedError ? limitBackupAllowed(instance, registry.get(candidate.instanceId)!, instanceConfigs(cfg)[candidate.instanceId])
+ registry.get(candidate.instanceId)?.enabled && (e instanceof TurnUsageLimitRefusedError ? (candidate.instanceId === instanceId ? e.scope !== "engine" : limitBackupAllowed(instance, registry.get(candidate.instanceId)!, instanceConfigs(cfg)[candidate.instanceId]))
: !(e instanceof TurnAuthenticationRefusedError) || candidate.instanceId !== instanceId) &&
(candidate.instanceId !== instanceId || candidate.model !== model));
const backup = backups[nextIndex];
@@ -8760,7 +8761,7 @@ async function startTurn(
store.switchTaskModel(bot.id, threadId, checked.selection, false, false, {
...hostedModels?.resetTask(current.modelSelection, checked.selection), rewound: true,
});
- if (e instanceof TurnUsageLimitRefusedError) limitFailovers.record({ botId: bot.id, threadId, from: current.modelSelection, to: checked.selection, resetsAt: e.resetsAt ?? null, at: Date.now() });
+ if (e instanceof TurnUsageLimitRefusedError) { limitFailovers.record({ botId: bot.id, threadId, from: current.modelSelection, to: checked.selection, resetsAt: e.resetsAt ?? null, at: Date.now() }); limitTakeover.tell(current, current.modelSelection, { ...(e.resetsAt ? { resetsAt: e.resetsAt } : {}), scope: e.scope, backup: checked.selection }); }
store.appendMessage(threadId, { role: "bot", kind: "activity", tool: {
name: e instanceof TurnUsageLimitRefusedError ? `recovery: ${failoverLine(engineName(instanceId), engineName(target.instanceId), e.resetsAt)}` : `recovery: Automatic recovery: ${instance.displayName || instance.driverKind} ${e instanceof TurnAuthenticationRefusedError ? "is signed out" : "could not start"}. Trying ${target.displayName || target.driverKind} · ${checked.selection.model} once in this thread.`, ok: true,
} });
@@ -8938,7 +8939,7 @@ async function stopBotForEmergencyApprovalDowngrade(botId: string): Promise<void
const engineName = (engine: string) => engineLabel(engine, registry.get(engine) ?? undefined);
const limitClock = new LimitResetClock({ accounts: () => planAccountsFromInstances(instanceConfigs(cfg)), onChange: () => routines?.retimeLimitResets(),
- waiting: () => Boolean(routines?.listRoutines().some((routine) => routine.enabled && routine.schedule.type === "limit_reset")) });
+ waiting: () => Boolean(routines?.listRoutines().some((routine) => routine.enabled && routine.schedule.type === "limit_reset")) }); const limitTakeover = createLimitTakeover({ file: join(DATA_DIR, "limit-notices.json"), configs: () => instanceConfigs(cfg), context: selectionContext, blockedUntil: (engine) => limitClock.blockedUntil(engine), engineName, engines: () => selectableInstances(registry.instances().map((engine) => ({ instanceId: engine.instanceId, driverKind: engine.driverKind, displayName: engine.displayName, enabled: engine.enabled, access: registry.access(engine.instanceId), models: engine.models, snapshot: registry.knownSnapshot(engine.instanceId) ?? { state: "unavailable" as const, reason: "not read yet" }, capabilities: engine.adapter.capabilities }))), chosen: (botId) => [...(store.bot(botId)?.fallback ?? []), ...(cfg.automaticRecovery?.backup ? [cfg.automaticRecovery.backup] : [])], tell: (about, text) => notify(buildNoticeNotification(about, store.bot(about.id)?.threadId ?? "", text)), record: (failover) => limitFailovers.record(failover) });
const limitFailovers = new LimitFailovers({ file: join(DATA_DIR, "limit-failovers.json"), blockedUntil: (engine) => limitClock.blockedUntil(engine), engineName,
threadModel: (botId, threadId) => store.projectBotForTask(botId, threadId)?.modelSelection ?? null,
note: (threadId, line) => store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: `recovery: ${line}`, ok: true } }),
@@ -8950,7 +8951,7 @@ const automationDestinations = createAutomationDestinations({ store, mainThread:
cloud: CLOUD_HOME ? { owner: CLOUD_OWNER_KEY!, opener: routineOpener, reportFromOthers: cloudReportFromOthers, opened: (threadId, person) => threadStarters.set(threadId, person) } : null });
routines = new RoutineManager({
emit: broadcast, limitResetAt: (engine) => limitClock.resetAt(engine), checks: proactive.checks,
- limitBackup: (botId) => cfg.automaticRecovery?.enabled === true && Boolean(store.bot(botId)?.fallback?.length || cfg.automaticRecovery.backup),
+ limitBackup: (botId, scope) => { const bot = store.bot(botId); return quotaSwitchEnabled() ? Boolean(bot && limitTakeover.backups(botId, bot.modelSelection, scope).length) : cfg.automaticRecovery?.enabled === true && Boolean(bot?.fallback?.length || cfg.automaticRecovery.backup); },
launchId: DESKTOP_MANAGED && /^[\w-]{1,100}$/.test(process.env.OMB_DESKTOP_LAUNCH_ID ?? "")
? process.env.OMB_DESKTOP_LAUNCH_ID : undefined,
skipStartupRuns: Boolean(CLOUD_HOME) && wokeFromSleep(DATA_DIR), // a Cloud home waking from a sleep it was stopped for
@@ -9808,7 +9809,7 @@ const approvalBus: ApprovalBus = { store, broadcast, notify, autoApply: fullAcce
onPeerApprovalPending: (from, target, action, sourceThreadId, message) => void reportEscalation({
kind: "peer-approval", bot: from, threadId: sourceThreadId, gate: peerApprovalGate(action, target.name), reason: message, alreadyNotified: true }) };
-const { quotaSwitch, harnessCardOutcome } = createQuotaSwitchHost({ store, coordinator, registry, turnStops, approvalBus, hostedModels, providerConfigs, policyModelRefusal, checkedTaskModelSwitch, threadBusy, directRequestOwners, startOrQueueDirectMessage });
+const { quotaSwitch, harnessCardOutcome } = createQuotaSwitchHost({ store, coordinator, registry, turnStops, approvalBus, hostedModels, providerConfigs, policyModelRefusal, checkedTaskModelSwitch, threadBusy, directRequestOwners, startOrQueueDirectMessage, takeover: limitTakeover });
// Peer approvals live only in memory: settle every peer card still open on disk, or it locks the composer forever.
{
diff --git a/server/limit-failover.ts b/server/limit-failover.ts
index d99c8dce6e..cbd47161fb 100644
--- a/server/limit-failover.ts
+++ b/server/limit-failover.ts
@@ -21,7 +21,13 @@ type Engine = { instanceId: string; driverKind: string };
export function limitBackupAllowed(from: Engine, to: Engine, toConfig?: Pick<InstanceConfig, "environment" | "access">): boolean {
if (to.instanceId === from.instanceId) return false;
if (to.driverKind !== from.driverKind || !SUBSCRIPTION_DRIVERS.has(from.driverKind)) return true;
- return toConfig?.access === "api" || PAY_PER_USE_KEYS.some((key) => Boolean(toConfig?.environment?.[key]?.trim()));
+ return billsEachUse(toConfig);
+}
+
+/** An engine instance that bills each use (a pay-per-use key, as its access or in its environment) instead of drawing on
+ * a plan's limit. */
+export function billsEachUse(config?: Pick<InstanceConfig, "environment" | "access">): boolean {
+ return config?.access === "api" || PAY_PER_USE_KEYS.some((key) => Boolean(config?.environment?.[key]?.trim()));
}
export function resetClock(at: number, timeZone = hostTimeZone()): string {
diff --git a/server/limit-notices.test.ts b/server/limit-notices.test.ts
new file mode 100644
index 0000000000..3065833100
--- /dev/null
+++ b/server/limit-notices.test.ts
@@ -0,0 +1,59 @@
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { LimitNotices, UNNAMED_STRETCH_MS, limitNoticeText } from "./limit-notices.ts";
+import { UNNAMED_LIMIT_MS } from "./limit-resets.ts";
+
+const dirs: string[] = [];
+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });
+
+function notices(now: { at: number }) {
+ const dir = mkdtempSync(join(tmpdir(), "omb-limit-notices-"));
+ dirs.push(dir);
+ return { file: join(dir, "limit-notices.json"), make: () => new LimitNotices(join(dir, "limit-notices.json"), () => now.at) };
+}
+
+describe("one notice per bot for each stretch of a limit", () => {
+ it("says it once while the limit lasts, again after it reset, and remembers it across a restart", () => {
+ const now = { at: 1_000_000 };
+ const { make } = notices(now);
+ const ledger = make();
+ const resetsAt = now.at + 60 * 60_000;
+ expect(ledger.first("kai", "codex", resetsAt)).toBe(true);
+ for (let turn = 0; turn < 5; turn += 1) expect(ledger.first("kai", "codex", resetsAt)).toBe(false);
+ expect(ledger.first("rosa", "codex", resetsAt), "another bot hears it once too").toBe(true);
+ expect(make().first("kai", "codex", resetsAt), "after a restart").toBe(false);
+ now.at = resetsAt + 1;
+ expect(ledger.first("kai", "codex", now.at + 60_000), "a new stretch").toBe(true);
+ });
+
+ it("keeps a limit that named no reset one stretch through the retry after its hour, and ends it when the engine works", () => {
+ const now = { at: 5_000_000 };
+ const ledger = notices(now).make();
+ expect(ledger.first("kai", "codex")).toBe(true);
+ now.at += UNNAMED_LIMIT_MS + 60_000;
+ expect(ledger.first("kai", "codex"), "the hourly retry, refused again").toBe(false);
+ now.at += UNNAMED_LIMIT_MS + 60_000;
+ expect(ledger.first("kai", "codex"), "still refusing: the same stretch").toBe(false);
+ ledger.ended("kai", "codex");
+ expect(ledger.first("kai", "codex")).toBe(true);
+ now.at += UNNAMED_STRETCH_MS + 1;
+ expect(ledger.first("kai", "codex"), "no refusal for the whole stretch: a new one").toBe(true);
+ });
+});
+
+describe("the notice", () => {
+ it("says in one line what carries on meanwhile, or that the bot waits", () => {
+ const resetsAt = new Date(2026, 9, 27, 14, 0).getTime();
+ expect(limitNoticeText({ engine: "Codex", bot: "Kai", resetsAt, backup: "Claude" }, "UTC").replace(/\d{1,2}:\d{2}\s?[AP]M/, "14:00"))
+ .toMatch(/^Codex reached its limit until (?:[A-Z][a-z]{2} )?14:00, so Kai is using Claude meanwhile\.$/);
+ expect(limitNoticeText({ engine: "Codex", bot: "Kai", backup: "Claude" })).toBe("Codex reached its limit, so Kai is using Claude meanwhile.");
+ expect(limitNoticeText({ engine: "Claude claude-opus-5-5", bot: "Iris", credits: true, backup: "Claude claude-sonnet-5" }))
+ .toBe("Claude claude-opus-5-5's extra usage credits are used up, so Iris is using Claude claude-sonnet-5 meanwhile.");
+ expect(limitNoticeText({ engine: "Codex", bot: "Kai" })).toBe("Codex reached its limit, so Kai waits: no other AI you have set up can take over.");
+ expect(limitNoticeText({ engine: "Claude claude-opus-5-5", bot: "Iris", credits: true, resetsAt: Date.now() + 86_400_000 }))
+ .toBe("Claude claude-opus-5-5's extra usage credits are used up, so Iris waits: no other AI you have set up can take over.");
+ });
+});
diff --git a/server/limit-notices.ts b/server/limit-notices.ts
new file mode 100644
index 0000000000..8df52dd4b6
--- /dev/null
+++ b/server/limit-notices.ts
@@ -0,0 +1,78 @@
+// What the person hears when an engine reaches its usage limit: once per bot for each stretch the engine is limited,
+// never once per refused turn. A stretch ends when its reset time passes, or when the engine works again. When the
+// engine named no reset, the stretch lasts UNNAMED_STRETCH_MS after its last refusal: longer than the hour the engine is
+// then held, so the try after that hour, refused again, is the same stretch.
+import { readFileSync } from "node:fs";
+
+import { writeFileAtomic } from "./atomic.ts";
+import { resetClock } from "./limit-failover.ts";
+import { UNNAMED_LIMIT_MS } from "./limit-resets.ts";
+
+type Told = Record<string, number>;
+
+/** How long a limit that named no reset counts as one stretch after its last refusal. */
+export const UNNAMED_STRETCH_MS = 3 * UNNAMED_LIMIT_MS;
+
+export interface LimitNoticeFacts {
+ /** The limited engine's name, as the person knows it: "Codex". */
+ engine: string;
+ bot: string;
+ /** When the limit resets, when the engine said. */
+ resetsAt?: number;
+ /** The AI that carries on meanwhile, or none. */
+ backup?: string;
+ /** Claude's extra usage credits ran out: only that model is limited. */
+ credits?: boolean;
+}
+
+/** "Codex reached its limit until 14:00, so Kai is using Claude meanwhile." */
+export function limitNoticeText(facts: LimitNoticeFacts, timeZone?: string): string {
+ const until = facts.resetsAt ? ` until ${resetClock(facts.resetsAt, timeZone)}` : "";
+ const what = facts.credits ? `${facts.engine}'s extra usage credits are used up` : `${facts.engine} reached its limit${until}`;
+ if (facts.backup) return `${what}, so ${facts.bot} is using ${facts.backup} meanwhile.`;
+ return facts.resetsAt && !facts.credits
+ ? `${what}, so ${facts.bot} waits until then: no other AI you have set up can take over.`
+ : `${what}, so ${facts.bot} waits: no other AI you have set up can take over.`;
+}
+
+export class LimitNotices {
+ private readonly file: string;
+ private readonly now: () => number;
+ private told: Told;
+
+ constructor(file: string, now: () => number = Date.now) {
+ this.file = file;
+ this.now = now;
+ try {
+ const raw = JSON.parse(readFileSync(file, "utf8")) as unknown;
+ this.told = raw && typeof raw === "object" && !Array.isArray(raw)
+ ? Object.fromEntries(Object.entries(raw as Record<string, unknown>).filter((entry): entry is [string, number] => Number.isFinite(entry[1])))
+ : {};
+ } catch {
+ this.told = {};
+ }
+ }
+
+ /** True the first time in this stretch of `engine`'s limit for `botId`; the stretch then lasts until `resetsAt`. */
+ first(botId: string, engine: string, resetsAt?: number): boolean {
+ const key = `${botId}\u0000${engine}`, now = this.now();
+ const until = resetsAt && resetsAt > now ? resetsAt : now + UNNAMED_STRETCH_MS;
+ const known = this.told[key];
+ this.told = Object.fromEntries(Object.entries(this.told).filter(([, end]) => end > now));
+ this.told[key] = Math.max(known && known > now ? known : 0, until);
+ this.save();
+ return !(known && known > now);
+ }
+
+ /** The engine works again for this bot: its next limit is a new stretch. */
+ ended(botId: string, engine: string): void {
+ const key = `${botId}\u0000${engine}`;
+ if (!(key in this.told)) return;
+ delete this.told[key];
+ this.save();
+ }
+
+ private save(): void {
+ try { writeFileAtomic(this.file, JSON.stringify(this.told), { mode: 0o600 }); } catch {}
+ }
+}
diff --git a/server/limit-reset.e2e.test.ts b/server/limit-reset.e2e.test.ts
index b1157f746f..49cfb33a5b 100644
--- a/server/limit-reset.e2e.test.ts
+++ b/server/limit-reset.e2e.test.ts
@@ -28,7 +28,7 @@ interface Fixture {
evidence: unknown[];
}
-async function withLimitFixture(setup: { recovery?: unknown; secondClaude?: boolean }, check: (fixture: Fixture) => Promise<void>) {
+async function withLimitFixture(setup: { recovery?: unknown; secondClaude?: boolean; codex?: false }, check: (fixture: Fixture) => Promise<void>) {
const fixture = await launchVerificationServer({});
const { dataDir, url, logPath } = fixture.info;
const limitedFile = join(dataDir, "claude-limited.json");
@@ -57,7 +57,7 @@ async function withLimitFixture(setup: { recovery?: unknown; secondClaude?: bool
const configPath = join(dataDir, "config.json");
const config = JSON.parse(readFileSync(configPath, "utf8"));
config.instances.claude.environment = { ...config.instances.claude.environment, FAKE_CLAUDE_LIMITED_FILE: limitedFile, FAKE_CLAUDE_PROMPTS: promptsFile, FAKE_CLAUDE_TOOL_CALLS: "[]" };
- config.instances.codex = { driver: "codex", config: { cli: fileURLToPath(new URL("./testing/fake-codex-app-server.ts", import.meta.url)) } };
+ if (setup.codex !== false) config.instances.codex = { driver: "codex", config: { cli: fileURLToPath(new URL("./testing/fake-codex-app-server.ts", import.meta.url)) } };
if (setup.secondClaude) config.instances.claudeWork = { ...config.instances.claude, displayName: "Second Claude sign-in" };
if (setup.recovery) config.automaticRecovery = setup.recovery;
writeFileSync(configPath, JSON.stringify(config));
@@ -75,7 +75,7 @@ async function withLimitFixture(setup: { recovery?: unknown; secondClaude?: bool
await expect.poll(async () => {
try { return (await fetch(url + "/api/health", { signal: AbortSignal.timeout(1_000) })).ok; } catch { return false; }
}, { timeout: 20_000 }).toBe(true);
- await expect.poll(async () => {
+ if (setup.codex !== false) await expect.poll(async () => {
const { instances } = await api("GET", "/api/instances") as { instances: any[] };
return instances.find((instance) => instance.instanceId === "codex")?.models.options.some((option: any) => option.id === codex.model);
}, { timeout: 20_000 }).toBe(true);
@@ -103,8 +103,8 @@ async function withLimitFixture(setup: { recovery?: unknown; secondClaude?: bool
const messagesOf = async (api: Fixture["api"], threadId: string) => (await api("GET", `/api/threads/${threadId}/messages?limit=200`)).messages as any[];
const recoveryLines = (messages: any[]) => messages.filter((message) => message.tool?.name?.startsWith("recovery:")).map((message) => message.tool.name as string);
-it("the stopped turn's Continue sets up a run that continues the conversation once the limit resets", async () => {
- await withLimitFixture({}, async ({ api, control, limit, lift, claudePrompts, evidence }) => {
+it("with no other AI to carry on, the stopped turn's Continue sets up a run that continues the conversation once the limit resets", async () => {
+ await withLimitFixture({ codex: false }, async ({ api, control, limit, lift, claudePrompts, evidence }) => {
const resetsAt = Math.floor(Date.now() / 1000) + 10;
limit(resetsAt);
const { bot } = await control("new-bot", "--name", "Scout");
@@ -183,7 +183,7 @@ it("continues on the backup engine with one line, and goes back to its own engin
}, 150_000);
it("never moves to another sign-in of the same engine; the stopped turn offers Continue instead", async () => {
- await withLimitFixture({ recovery: { enabled: true, backup: { instanceId: "claudeWork", model: "claude-sonnet-5" } }, secondClaude: true },
+ await withLimitFixture({ recovery: { enabled: true, backup: { instanceId: "claudeWork", model: "claude-sonnet-5" } }, secondClaude: true, codex: false },
async ({ api, control, limit, claudePrompts }) => {
const resetsAt = Math.floor(Date.now() / 1000) + 600;
limit(resetsAt);
@@ -199,7 +199,7 @@ it("never moves to another sign-in of the same engine; the stopped turn offers C
});
}, 120_000);
-it("a model out of extra-usage credits moves that turn to the backup, but never holds the engine", async () => {
+it("a model out of extra-usage credits moves its turns to the backup for a while, but never holds the engine's other models", async () => {
await withLimitFixture({ recovery: { enabled: true, backup: codex } }, async ({ api, control, refuse, lift, claudePrompts, evidence }) => {
const resetsAt = Math.floor(Date.now() / 1000) + 11 * 86_400;
refuse({ status: "rejected", resetsAt, overageDisabledReason: "out_of_credits", isUsingOverage: false, errorCode: "credits_required" });
@@ -211,18 +211,27 @@ it("a model out of extra-usage credits moves that turn to the backup, but never
expect((await api("GET", "/api/limit-resets")).engines).not.toContainEqual(expect.objectContaining({ engine: "claude", blocked: true }));
lift();
- const { task: other } = await api("POST", `/api/bots/${bot.id}/tasks`, { title: "Another thing" });
- await control("send", "--bot", bot.id, "--task", other.threadId, "--text", "And check today's commits");
+ // That model is held a while: the bot's next conversation on it goes straight to the backup, without asking Claude.
+ const { task: same } = await api("POST", `/api/bots/${bot.id}/tasks`, { title: "Another thing" });
+ await control("send", "--bot", bot.id, "--task", same.threadId, "--text", "And check today's commits");
+ expect((await control("wait", "--bot", bot.id, "--task", same.threadId, "--timeout", "30")).status).toBe("settled");
+ expect(claudePrompts()).toHaveLength(1);
+ // Claude's other models still run on Claude: the engine itself is never held.
+ const { instances } = await api("GET", "/api/instances") as { instances: any[] };
+ const model = instances.find((instance) => instance.instanceId === "claude").models.options.map((option: any) => option.id).find((id: string) => id !== bot.modelSelection.model);
+ const { task: other } = await api("POST", `/api/bots/${bot.id}/tasks`, { title: "One more" });
+ await api("PATCH", `/api/bots/${bot.id}/tasks/${other.threadId}`, { modelSelection: { instanceId: "claude", model } });
+ await control("send", "--bot", bot.id, "--task", other.threadId, "--text", "And list today's commits");
expect((await control("wait", "--bot", bot.id, "--task", other.threadId, "--timeout", "30")).status).toBe("settled");
expect(claudePrompts()).toHaveLength(2);
const reply = (await messagesOf(api, other.threadId)).findLast((message) => message.role === "bot" && message.kind === "text");
expect(reply).toMatchObject({ text: "hello from fake claude" });
- evidence.push({ reply });
+ evidence.push({ reply, model });
});
}, 120_000);
it("a turn that works on the engine afterwards ends a refusal's hold long before its reset", async () => {
- await withLimitFixture({}, async ({ api, control, limit, lift, evidence }) => {
+ await withLimitFixture({ codex: false }, async ({ api, control, limit, lift, evidence }) => {
const resetsAt = Math.floor(Date.now() / 1000) + 11 * 86_400;
limit(resetsAt);
const { bot } = await control("new-bot", "--name", "Scout");
@@ -239,3 +248,41 @@ it("a turn that works on the engine afterwards ends a refusal's hold long before
evidence.push({ after });
});
}, 120_000);
+
+it("with nothing set up for it, carries the person's request on with another AI they have, says so once, and goes back after the reset", async () => {
+ await withLimitFixture({}, async ({ api, control, limit, lift, claudePrompts, evidence }) => {
+ const resetsAt = Math.floor(Date.now() / 1000) + 25;
+ limit(resetsAt);
+ const { bot } = await control("new-bot", "--name", "Kai");
+ const threadId = bot.activeTaskId;
+ const claudeModel = (await api("GET", "/api/bots")).bots.find((entry: any) => entry.id === bot.id).modelSelection;
+ await control("send", "--bot", bot.id, "--task", threadId, "--text", "Draft the launch plan");
+ const reply = async (id: string) => (await messagesOf(api, id)).findLast((message) => message.role === "bot" && message.kind === "text")?.text;
+ await expect.poll(() => reply(threadId), { timeout: 40_000 }).toBe("done from fake codex");
+ const first = await messagesOf(api, threadId);
+ expect(first.map((message) => message.tool?.name)).toContain("notice: continuing on Codex after hitting the usage limit");
+ const task = async (id: string) => (await api("GET", "/api/bots")).bots.find((entry: any) => entry.id === bot.id).tasks.find((entry: any) => entry.threadId === id);
+ expect((await task(threadId)).modelSelection).toEqual(codex);
+ const notified = async () => (await api("GET", "/api/notifications")).notifications as any[];
+ await expect.poll(async () => (await notified()).filter((entry) => entry.kind === "notice").length, { timeout: 10_000 }).toBe(1);
+ expect((await notified()).find((entry) => entry.kind === "notice").body).toMatch(/^Verification fixture reached its limit until .+, so Kai is using Codex meanwhile\.$/);
+ expect((await notified()).filter((entry) => entry.kind === "incident" || entry.kind === "turn-failed"), "one notice, never an incident").toEqual([]);
+
+ // Known to be refusing: another conversation goes to Codex without spending a refused turn on Claude, and no new notice.
+ const { task: other } = await api("POST", `/api/bots/${bot.id}/tasks`, { title: "Another thing" });
+ await control("send", "--bot", bot.id, "--task", other.threadId, "--text", "And the budget");
+ expect((await control("wait", "--bot", bot.id, "--task", other.threadId, "--timeout", "30")).status).toBe("settled");
+ expect(recoveryLines(await messagesOf(api, other.threadId))).toEqual([expect.stringMatching(/so Codex took over\.$/)]);
+ expect(claudePrompts()).toHaveLength(1);
+ expect((await notified()).filter((entry) => entry.kind === "notice")).toHaveLength(1);
+
+ lift();
+ await expect.poll(() => Date.now() > resetsAt * 1000 + 500, { timeout: 40_000, interval: 500 }).toBe(true);
+ await control("send", "--bot", bot.id, "--task", threadId, "--text", "Now polish it");
+ expect((await control("wait", "--bot", bot.id, "--task", threadId, "--timeout", "30")).status).toBe("settled");
+ expect((await task(threadId)).modelSelection).toEqual(claudeModel);
+ expect(recoveryLines(await messagesOf(api, threadId))).toContain("recovery: Verification fixture's limit has reset, so this conversation is back on Verification fixture.");
+ expect(await reply(threadId)).toBe("hello from fake claude");
+ evidence.push({ first, notices: await notified() });
+ });
+}, 150_000);
diff --git a/server/limit-resets.test.ts b/server/limit-resets.test.ts
index b0b6a17475..f5fb38e3ab 100644
--- a/server/limit-resets.test.ts
+++ b/server/limit-resets.test.ts
@@ -4,7 +4,7 @@ import { join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { codexLimitResetsAt } from "./drivers/codex-errors.ts";
-import { engineLimitFromUsage, LimitResetClock, nearLimitNote } from "./limit-resets.ts";
+import { engineLimitFromUsage, LimitResetClock, nearLimitNote, UNNAMED_LIMIT_MS } from "./limit-resets.ts";
import type { RuntimeEvent } from "../shared/runtime-events.ts";
import { parseClaudeUsage, parseCodexUsage, type PlanProviderRow, type PlanUsageReport, type PlanWindows } from "./plan-usage.ts";
@@ -248,4 +248,34 @@ describe("LimitResetClock and the turns that follow a refusal", () => {
instance.noteRuntimeEvent(undefined, refused("t1"));
expect(instance.blockedUntil("claude")).toBeNull();
});
+
+ it("holds an engine an hour when its own limit names no reset, never showing that guess as a reset, until one is named or a turn works", () => {
+ let now = NOW;
+ const instance = new LimitResetClock({ accounts: () => accounts, now: () => now });
+ const limited = (threadId: string) => ({ ...refused(threadId), limit: "engine" }) as RuntimeEvent;
+ instance.noteRuntimeEvent("claude", started("t1"));
+ instance.noteRuntimeEvent(undefined, limited("t1"));
+ expect(instance.blockedUntil("claude")).toBe(NOW + UNNAMED_LIMIT_MS);
+ expect(instance.resetAt("claude"), "a guess is no reset time").toBeNull();
+ expect(instance.report().engines).toEqual([expect.objectContaining({ engine: "claude", blocked: true, resetsAt: null })]);
+ instance.noteRefusal("claude", NOW + 3 * HOUR);
+ expect(instance.resetAt("claude"), "a reset the engine names replaces the guess").toBe(NOW + 3 * HOUR);
+ instance.noteLimit("claude", undefined);
+ expect(instance.blockedUntil("claude"), "and a refusal naming none never shortens it").toBe(NOW + 3 * HOUR);
+ instance.noteRuntimeEvent("claude", started("t2"));
+ instance.noteRuntimeEvent(undefined, completed("t2", true));
+ expect(instance.blockedUntil("claude")).toBeNull();
+
+ instance.noteLimit("claude", undefined);
+ now = NOW + UNNAMED_LIMIT_MS + 1;
+ expect(instance.blockedUntil("claude"), "the guess runs out on its own").toBeNull();
+ });
+
+ it("never holds the engine for one model's own limit", () => {
+ const { instance } = clock();
+ instance.noteRuntimeEvent("claude", { ...refused("t1", NOW + 50 * HOUR), limit: "model" } as RuntimeEvent);
+ instance.noteRuntimeEvent("claude", { ...refused("t1"), limit: "credits" } as RuntimeEvent);
+ expect(instance.blockedUntil("claude")).toBeNull();
+ expect(instance.report().engines).toEqual([]);
+ });
});
diff --git a/server/limit-resets.ts b/server/limit-resets.ts
index fd95d8b807..7110ffc495 100644
--- a/server/limit-resets.ts
+++ b/server/limit-resets.ts
@@ -76,11 +76,16 @@ function fixtureUsage(path: string, now: number): PlanUsageReport {
}
}
+/** With no reset time named, a usage limit holds its engine this long after its last refusal. */
+export const UNNAMED_LIMIT_MS = 60 * 60_000;
+
export class LimitResetClock {
private readonly options: LimitClockOptions;
private readonly now: () => number;
private usage = new Map<string, EngineLimit>();
private readonly refusals = new Map<string, number>();
+ /** Engines held by a refusal that named no reset time: the hold is a guess, never shown as a reset. */
+ private readonly guessed = new Set<string>();
private readonly turnEngines = new Map<string, string>();
private checkedAt = 0;
private loading: Promise<void> | null = null;
@@ -95,7 +100,7 @@ export class LimitResetClock {
/** The reset a limit-reset automation for this engine waits for: a refusal's own time unless usage shows a later
* window still at its limit; otherwise the usage's. It may have passed, which means the limit has reset. */
resetAt(engine: string): number | null {
- const refused = this.refusal(engine);
+ const refused = this.guessed.has(engine) ? null : this.refusal(engine);
const usage = this.usage.get(engine);
if (refused === null) return usage?.resetsAt ?? null;
return usage?.blocked && usage.resetsAt !== null && usage.resetsAt > refused ? usage.resetsAt : refused;
@@ -119,7 +124,7 @@ export class LimitResetClock {
for (const engine of this.refusals.keys()) {
const until = this.blockedUntil(engine);
const known = engines.get(engine);
- if (until !== null) engines.set(engine, { ...(known ?? this.unnamed(engine)), blocked: true, usedPercent: 100, resetsAt: until });
+ if (until !== null) engines.set(engine, { ...(known ?? this.unnamed(engine)), blocked: true, usedPercent: 100, resetsAt: this.guessed.has(engine) ? known?.resetsAt ?? null : until });
}
return { checkedAt: this.checkedAt, engines: [...engines.values()] };
}
@@ -128,18 +133,38 @@ export class LimitResetClock {
* works on it afterwards ends the hold, since the account plainly has room again (another model, plan or account). */
noteRuntimeEvent(engine: string | undefined, event: RuntimeEvent): void {
if (event.type === "turn.started" && engine) this.turnEngines.set(event.threadId, engine);
- else if (event.type === "runtime.error") this.noteRefusal(engine ?? this.turnEngines.get(event.threadId), event.limitResetsAt);
+ else if (event.type === "runtime.error") {
+ const refused = engine ?? this.turnEngines.get(event.threadId);
+ // One model's own limit leaves the engine's other models working: only that model is held (host/limit-takeover).
+ if (event.limit === "engine") this.noteLimit(refused, event.limitResetsAt);
+ else if (event.limit === undefined) this.noteRefusal(refused, event.limitResetsAt);
+ }
else if (event.type === "turn.completed" || event.type === "session.exited") {
const ran = this.turnEngines.get(event.threadId) ?? engine;
this.turnEngines.delete(event.threadId);
- if (event.type === "turn.completed" && event.ok && ran && this.refusals.delete(ran)) this.options.onChange?.();
+ if (event.type === "turn.completed" && event.ok && ran && this.refusals.delete(ran)) { this.guessed.delete(ran); this.options.onChange?.(); }
}
}
+ /** The engine's own usage limit refused a turn: held until the reset it named, or for an hour after this refusal when
+ * it named none (a guess, never shown as a reset time). */
+ noteLimit(engine: string | undefined, resetsAt: number | undefined): void {
+ if (resetsAt !== undefined) return this.noteRefusal(engine, resetsAt);
+ // A reset the engine named still stands: a refusal that names none never shortens it.
+ if (!engine || ((this.refusal(engine) ?? 0) > this.now() && !this.guessed.has(engine))) return;
+ this.hold(engine, this.now() + UNNAMED_LIMIT_MS, true);
+ }
+
/** A turn on this engine was refused by its usage limit; `resetsAt` is when the engine said it resets. */
noteRefusal(engine: string | undefined, resetsAt: number | undefined): void {
- if (!engine || resetsAt === undefined || !Number.isFinite(resetsAt) || resetsAt <= this.now() || this.refusals.get(engine) === resetsAt) return;
- this.refusals.set(engine, resetsAt);
+ if (!engine || resetsAt === undefined || !Number.isFinite(resetsAt) || resetsAt <= this.now() || (this.refusals.get(engine) === resetsAt && !this.guessed.has(engine))) return;
+ this.hold(engine, resetsAt, false);
+ }
+
+ private hold(engine: string, until: number, guessed: boolean): void {
+ if (guessed) this.guessed.add(engine);
+ else this.guessed.delete(engine);
+ this.refusals.set(engine, until);
this.options.onChange?.();
if (this.soon) clearTimeout(this.soon);
this.soon = setTimeout(() => { this.soon = null; void this.refresh(true); }, SOON_AFTER_REFUSAL_MS);
@@ -203,6 +228,7 @@ export class LimitResetClock {
if (at === undefined) return null;
if (at < this.now() - REFUSAL_GRACE_MS) {
this.refusals.delete(engine);
+ this.guessed.delete(engine);
return null;
}
return at;
diff --git a/server/quota-switch.e2e.test.ts b/server/quota-switch.e2e.test.ts
index fed798cda1..4d51a12292 100644
--- a/server/quota-switch.e2e.test.ts
+++ b/server/quota-switch.e2e.test.ts
@@ -11,13 +11,14 @@ import { readHandoffs } from "./testing/handoff-rows.ts";
import { freePortBlock } from "./testing/ports.ts";
const LIMITED = "Limited Claude";
-const BACKUP = "Backup Claude";
+const OTHER_SIGN_IN = "Second Claude sign-in";
const FAKE_CLI = fileURLToPath(new URL("./testing/fake-claude-cli.ts", import.meta.url));
+const FAKE_CODEX = fileURLToPath(new URL("./testing/fake-codex-app-server.ts", import.meta.url));
const jsonLines = (path: string): any[] => existsSync(path)
? readFileSync(path, "utf8").split("\n").filter(Boolean).map((line) => JSON.parse(line)) : [];
async function withQuotaFixture(
- options: { env?: Record<string, string> },
+ options: { env?: Record<string, string>; otherSignInOnly?: boolean },
check: (fixture: {
api: (method: string, path: string, body?: unknown) => Promise<any>;
control: (...args: string[]) => Promise<any>;
@@ -39,7 +40,9 @@ async function withQuotaFixture(
writeFileSync(join(dataDir, "config.json"), JSON.stringify({
instances: {
claude: engine(LIMITED, { FAKE_CLAUDE_MODE: "usage-limit" }),
- backup: engine(BACKUP, { FAKE_CLAUDE_MODE: "happy", FAKE_CLAUDE_PROMPTS: backupFile, FAKE_CLAUDE_TOOL_CALLS: "[]" }),
+ ...(options.otherSignInOnly
+ ? { backup: engine(OTHER_SIGN_IN, { FAKE_CLAUDE_MODE: "happy", FAKE_CLAUDE_PROMPTS: backupFile, FAKE_CLAUDE_TOOL_CALLS: "[]" }) }
+ : { codex: { driver: "codex", config: { cli: FAKE_CODEX }, environment: { FAKE_CODEX_DUMP: backupFile } } }),
},
}));
const evidence: unknown[] = [{ url, options }];
@@ -77,9 +80,20 @@ async function withQuotaFixture(
await expect.poll(async () => {
try { return (await fetch(url + "/api/health", { signal: AbortSignal.timeout(1_000) })).ok; } catch { return false; }
}, { timeout: 90_000 }).toBe(true);
- await check({ api, control, respond, backupPrompts: () => jsonLines(backupFile), dataDir });
+ if (!options.otherSignInOnly) {
+ await expect.poll(async () => {
+ const { instances } = await api("GET", "/api/instances") as { instances: any[] };
+ return instances.find((instance) => instance.instanceId === "codex")?.models.options.length > 0;
+ }, { timeout: 30_000 }).toBe(true);
+ }
+ // What the other AI was sent: the fake Claude logs each prompt; the fake Codex keeps its calls in one dump.
+ const sent = () => {
+ if (options.otherSignInOnly) return jsonLines(backupFile);
+ try { return (JSON.parse(readFileSync(backupFile, "utf8")).calls as any[]).filter((call) => call.method === "turn/start"); } catch { return []; }
+ };
+ await check({ api, control, respond, backupPrompts: sent, dataDir });
} finally {
- evidence.push({ backupPrompts: jsonLines(backupFile), roots: readHandoffs(dataDir) });
+ evidence.push({ backupPrompts: existsSync(backupFile) ? readFileSync(backupFile, "utf8").slice(0, 20_000) : null, roots: readHandoffs(dataDir) });
const evidencePath = `${logPath}.quota-switch.json`;
writeFileSync(evidencePath, JSON.stringify(evidence, null, 2));
await waitForExit(server, { signal: "SIGTERM" });
@@ -88,132 +102,72 @@ async function withQuotaFixture(
}
}
-/** A bot whose conversation runs on the limited engine, and the turn that
- * meets the limit. */
-async function meetTheLimit(api: (method: string, path: string, body?: unknown) => Promise<any>, control: (...args: string[]) => Promise<any>, text: string) {
+/** A bot whose conversation runs on the limited engine, and the turn that meets the limit. `carriedOn`: another AI may
+ * already have taken the request over by the time the wait ends. */
+async function meetTheLimit(api: (method: string, path: string, body?: unknown) => Promise<any>, control: (...args: string[]) => Promise<any>, text: string, carriedOn = false) {
const { bot } = await control("new-bot", "--name", "Out of quota");
const threadId = bot.activeTaskId as string;
const limited = (await api("GET", "/api/bots")).bots.find((entry: any) => entry.id === bot.id).modelSelection;
await api("PATCH", `/api/bots/${bot.id}/tasks/${threadId}`, { modelSelection: { ...limited, instanceId: "claude" }, updateBotDefault: true });
await control("send", "--bot", bot.id, "--task", threadId, "--text", text);
- expect((await control("wait", "--bot", bot.id, "--task", threadId, "--timeout", "30")).status).toBe("failed");
+ expect(carriedOn ? ["failed", "settled"] : ["failed"]).toContain((await control("wait", "--bot", bot.id, "--task", threadId, "--timeout", "30")).status);
const messages = async () => (await api("GET", `/api/threads/${threadId}/messages?limit=100`)).messages as any[];
const state = async () => (await api("GET", "/api/bots")).bots.find((entry: any) => entry.id === bot.id);
return { bot, threadId, messages, state };
}
-it("offers the working engine once, and on the person's answer switches this conversation and resends the exact message", async () => {
- await withQuotaFixture({}, async ({ api, control, respond, backupPrompts, dataDir }) => {
+it("carries the request on with another AI by itself: the exact message once more there, one notice, the failed root left settled", async () => {
+ await withQuotaFixture({}, async ({ api, control, backupPrompts, dataDir }) => {
const text = "SUMMARISE_THE_QUARTER_4K";
- const { bot, threadId, messages, state } = await meetTheLimit(api, control, text);
+ const { bot, threadId, messages, state } = await meetTheLimit(api, control, text, true);
const { task: sibling } = await api("POST", `/api/bots/${bot.id}/tasks`, { title: "Sibling keeps its engine" });
- // One account of the failure, and one offer: the engine that works, by name.
- await expect.poll(async () => (await messages()).filter((message) => message.card?.quotaSwitch).length, { timeout: 20_000 }).toBe(1);
- const before = await messages();
- const failures = before.filter((message) => message.tool?.name?.startsWith("error:"));
+ await expect.poll(async () => (await messages()).findLast((message) => message.role === "bot" && message.kind === "text")?.text, { timeout: 30_000 }).toBe("done from fake codex");
+ const after = await messages();
+ const failures = after.filter((message) => message.tool?.name?.startsWith("error:"));
expect(failures).toHaveLength(1);
expect(failures[0].tool.name).toMatch(/This Claude account has reached its usage limit/);
- const offer = before.find((message) => message.card?.quotaSwitch);
- expect(offer.card).toMatchObject({
- title: `${LIMITED} is out of quota`,
- subtitle: "Continue this conversation with another AI?",
- options: [BACKUP, "Not now"],
- fixedOptions: true,
- quotaSwitch: { engines: [{ instanceId: "backup", name: BACKUP }], messageId: before.find((message) => message.role === "user").id },
- });
- expect(offer.card.tool).toBeUndefined();
- // Nothing moved without the answer: same engine, the failed turn's root settled, nothing else begun.
- expect((await state()).tasks.find((task: any) => task.threadId === threadId)).toMatchObject({ busy: false });
- expect((await state()).modelSelection.instanceId).toBe("claude");
- expect(backupPrompts()).toHaveLength(0);
- const rootsBefore = readHandoffs(dataDir).filter((node) => node.threadId === threadId);
- expect(rootsBefore.map((node) => [node.status, node.outcome, node.executions])).toEqual([["failed", "provider_error", 1]]);
- // The card names that root: the answer asks the runtime about the request that ran out, not about the thread.
- expect(offer.card.quotaSwitch.rootId).toBe(rootsBefore[0]!.id);
-
- expect(await respond(threadId, { requestId: offer.card.requestId, behavior: "answer", message: BACKUP }))
- .toEqual({ status: 200, body: { ok: true, outcome: "answered" } });
- await expect.poll(() => backupPrompts().length, { timeout: 20_000 }).toBe(1);
- expect((await control("wait", "--bot", bot.id, "--task", threadId, "--timeout", "30")).status).toBe("settled");
-
- const after = await messages();
- // The message whose turn failed, sent once more: twice in the conversation, once to the engine that works.
+ expect(after.some((message) => message.card?.quotaSwitch), "nothing to answer").toBe(false);
+ expect(after.filter((message) => message.tool?.name === "notice: continuing on Codex after hitting the usage limit")).toHaveLength(1);
+ // The message whose turn failed, sent once more: twice in the conversation, once to the AI that works.
expect(after.filter((message) => message.role === "user" && message.text === text)).toHaveLength(2);
expect(backupPrompts()).toHaveLength(1);
expect(JSON.stringify(backupPrompts()[0])).toContain(text);
- expect(after.findLast((message) => message.role === "bot" && message.kind === "text")).toMatchObject({ text: "hello from fake claude", turnSucceeded: true });
- expect(after.filter((message) => message.tool?.name === `notice: continuing on ${BACKUP} after hitting quota`)).toHaveLength(1);
- // Settled only once the switch went through, inside the answer's own request: so who answered is on the card.
- expect(after.find((message) => message.id === offer.id).card).toMatchObject({ answered: "answer", answeredText: BACKUP, answeredBy: { kind: "loopback" } });
- expect(after.filter((message) => message.card?.quotaSwitch)).toHaveLength(1);
- expect(after.filter((message) => message.tool?.name?.startsWith("error:"))).toHaveLength(1);
// This conversation moved; the bot's own engine and its other conversation did not.
const bots = await state();
- const instances = (await api("GET", "/api/instances")).instances as any[];
- expect(bots.tasks.find((task: any) => task.threadId === threadId)).toMatchObject({
- modelSelection: { instanceId: "backup", model: instances.find((instance) => instance.instanceId === "backup").models.default }, busy: false,
- });
+ expect(bots.tasks.find((task: any) => task.threadId === threadId)).toMatchObject({ modelSelection: { instanceId: "codex" }, busy: false });
expect(bots.modelSelection.instanceId).toBe("claude");
expect(bots.tasks.find((task: any) => task.threadId === sibling.threadId).modelSelection?.instanceId ?? bots.modelSelection.instanceId).toBe("claude");
-
// No job twice: the failed turn's root stayed settled, and the resend is one new root that completed.
- const roots = readHandoffs(dataDir).filter((node) => node.threadId === threadId);
- expect(roots.map((node) => [node.status, node.executions])).toEqual([["failed", 1], ["completed", 1]]);
- expect(roots[0]!.id).toBe(rootsBefore[0]!.id);
-
- // A second press on the settled card is refused as already answered: it
- // switches nothing, and its words never reach the bot as a message.
- const again = await respond(threadId, { requestId: offer.card.requestId, behavior: "answer", message: BACKUP });
- expect(again).toEqual({ status: 409, body: { error: "this question has already been answered" } });
- expect((await messages()).filter((message) => message.role === "user")).toHaveLength(2);
- expect(backupPrompts()).toHaveLength(1);
- expect(readHandoffs(dataDir).filter((node) => node.threadId === threadId)).toHaveLength(2);
+ expect(readHandoffs(dataDir).filter((node) => node.threadId === threadId).map((node) => [node.status, node.executions])).toEqual([["failed", 1], ["completed", 1]]);
+ // One notice for this bot; the Chief, told of the incident, hears its own if its own turn meets the limit too.
+ const notices = (await api("GET", "/api/notifications")).notifications.filter((entry: any) => entry.kind === "notice" && entry.botId === bot.id);
+ expect(notices.map((entry: any) => entry.body)).toEqual([expect.stringMatching(/^Limited Claude reached its limit.*, so Out of quota is using Codex meanwhile\.$/)]);
});
}, 240_000);
-it.each([
- { name: "Not now", behavior: "answer", message: "Not now", outcome: "answered" },
- { name: "typed words that name no offered engine", behavior: "answer", message: "use whichever is fastest", outcome: "answered" },
- // Decline-only service trust (hosted, Cloud home, OMB_LOOPBACK_TRUST=service): a decline naming an engine chooses nothing.
- { name: "a decline that carries the offered engine's label", behavior: "deny", message: BACKUP, outcome: "rejected" },
- { name: "an allow that carries the offered engine's label", behavior: "allow", message: BACKUP, outcome: "rejected" },
-])("changes nothing on $name", async ({ behavior, message, outcome }) => {
- await withQuotaFixture({}, async ({ api, control, respond, backupPrompts, dataDir }) => {
- const text = "LEAVE_THIS_WHERE_IT_IS_7M";
- const { threadId, messages, state } = await meetTheLimit(api, control, text);
- await expect.poll(async () => (await messages()).filter((entry) => entry.card?.quotaSwitch).length, { timeout: 20_000 }).toBe(1);
- const offer = (await messages()).find((entry) => entry.card?.quotaSwitch);
-
- expect(await respond(threadId, { requestId: offer.card.requestId, behavior, message }))
- .toEqual({ status: 200, body: { ok: true, outcome } });
-
- const after = await messages();
- expect(after.find((entry) => entry.id === offer.id).card).toMatchObject({ answered: "answer", answeredText: "Not now" });
- expect(after.filter((entry) => entry.role === "user")).toHaveLength(1);
- expect(after.some((entry) => entry.tool?.name?.startsWith("notice:"))).toBe(false);
- expect((await state()).tasks.find((task: any) => task.threadId === threadId)).toMatchObject({ busy: false });
- expect((await state()).modelSelection.instanceId).toBe("claude");
- // Nothing was switched and nothing was sent again: asked once more, the settled
- // card is refused, and the working engine was never run.
- expect(await respond(threadId, { requestId: offer.card.requestId, behavior: "answer", message: BACKUP }))
- .toEqual({ status: 409, body: { error: "this question has already been answered" } });
+it("never moves to another sign-in of the same AI: it says once that the bot waits, and sends nothing again", async () => {
+ await withQuotaFixture({ otherSignInOnly: true }, async ({ api, control, backupPrompts }) => {
+ const { bot, threadId, messages, state } = await meetTheLimit(api, control, "LEAVE_THIS_WHERE_IT_IS_7M");
+ const mine = async () => (await api("GET", "/api/notifications")).notifications.filter((entry: any) => entry.kind === "notice" && entry.botId === bot.id);
+ await expect.poll(async () => (await mine()).length, { timeout: 20_000 }).toBe(1);
+ const [notice] = await mine();
+ expect(notice.body).toMatch(/^Limited Claude reached its limit.*, so Out of quota waits.*: no other AI you have set up can take over\.$/);
+ expect((await messages()).filter((entry) => entry.role === "user")).toHaveLength(1);
expect((await state()).tasks.find((task: any) => task.threadId === threadId).modelSelection?.instanceId ?? "claude").toBe("claude");
expect(backupPrompts()).toHaveLength(0);
- expect(readHandoffs(dataDir).filter((node) => node.threadId === threadId).map((node) => node.status)).toEqual(["failed"]);
});
}, 240_000);
-it("raises no card when OMB_QUOTA_SWITCH=0 switches it off", async () => {
+it("moves nothing when OMB_QUOTA_SWITCH=0 switches it off", async () => {
await withQuotaFixture({ env: { OMB_QUOTA_SWITCH: "0" } }, async ({ api, control, backupPrompts }) => {
- const { bot, threadId, messages } = await meetTheLimit(api, control, "NO_OFFER_WHEN_OFF_2B");
- // A second failed turn is the event that proves the first one's offer was never coming.
- await control("send", "--bot", bot.id, "--task", threadId, "--text", "STILL_NO_OFFER_3C");
- expect((await control("wait", "--bot", bot.id, "--task", threadId, "--timeout", "30")).status).toBe("failed");
- const after = await messages();
- expect(after.filter((message) => message.tool?.name?.startsWith("error:"))).toHaveLength(2);
- expect(after.some((message) => message.kind === "options")).toBe(false);
+ const { bot, threadId, messages, state } = await meetTheLimit(api, control, "NO_MOVE_WHEN_OFF_2B");
+ const mine = async () => (await api("GET", "/api/notifications")).notifications.filter((entry: any) => entry.kind === "notice" && entry.botId === bot.id);
+ await expect.poll(async () => (await mine()).length, { timeout: 20_000 }).toBe(1);
+ expect((await mine())[0].body).toMatch(/, so Out of quota waits.*: no other AI you have set up can take over\.$/);
+ expect((await messages()).filter((message) => message.role === "user")).toHaveLength(1);
+ expect((await state()).tasks.find((task: any) => task.threadId === threadId).modelSelection?.instanceId ?? "claude").toBe("claude");
expect(backupPrompts()).toHaveLength(0);
});
}, 240_000);
diff --git a/server/quota-switch.test.ts b/server/quota-switch.test.ts
index 9bcaa59af5..c7b6802ae2 100644
--- a/server/quota-switch.test.ts
+++ b/server/quota-switch.test.ts
@@ -46,7 +46,7 @@ describe("quotaSwitchEnabled", () => {
});
});
-describe("quota-switch card", () => {
+describe("quota switch", () => {
let store: Store;
let bot: BotRecord;
let engines: QuotaSwitchEngine[];
@@ -79,12 +79,33 @@ describe("quota-switch card", () => {
requests.set(threadId, { generations: new Set([id]), turnId: `turn-${id}`, origin: { kind: "user", request: "asked" }, ...record });
return { id, event: { threadId, turnId: `turn-${id}`, ok: false, stopReason: "quota" } };
};
- /** The fold's report of that turn, broken on `why`. */
- const fails = (turn: ReturnType<typeof begin>, why = QUOTA, internal = false, on = thread()) => {
+ /** The fold's report of that turn, broken on `why`: the module decides what carries on. */
+ const ranOut = (turn: ReturnType<typeof begin>, why = QUOTA, internal = false, on = thread()) => {
cause = why;
return quota.turnFailed(on, turn.event, internal);
};
- /** A turn that failed and handed nothing on: its own end settles its root. */
+ /** The quota card an earlier version left open for that turn: the other engines here, then Not now. */
+ const fails = async (turn: ReturnType<typeof begin>, _why = QUOTA, _internal = false, on = thread()) => {
+ const others = engines.filter((candidate) => candidate.instanceId !== on.modelSelection.instanceId).slice(0, 3);
+ const offered = others.map((candidate, index) => {
+ const name = candidate.displayName || candidate.driverKind;
+ const taken = name === NOT_NOW || others.slice(0, index).some((other) => (other.displayName || other.driverKind) === name);
+ return { instanceId: candidate.instanceId, name: taken ? `${name} (${candidate.instanceId})` : name };
+ });
+ if (!offered.length) return null;
+ const messageId = requests.get(turn.event.threadId)?.messageId;
+ const original = store.activePath(turn.event.threadId).find((m) => m.id === messageId && m.role === "user" && m.kind === "text" && m.text && !m.peerAsk);
+ return store.appendMessage(turn.event.threadId, {
+ role: "bot", kind: "options",
+ card: {
+ title: "Claude is out of quota",
+ subtitle: original ? "Continue this conversation with another AI?" : "Switch this conversation to another AI? Send your message again afterwards.",
+ options: [...offered.map((offer) => offer.name), NOT_NOW], requestId: `card-${turn.id}`, fixedOptions: true,
+ quotaSwitch: { engines: offered, ...(original ? { messageId: original.id } : {}), rootId: turn.id },
+ },
+ });
+ };
+ /** A turn that failed and handed nothing on (its own end settles its root), with the card left open for it. */
const failed = (why = QUOTA, record: Partial<QuotaRequest> = {}) => {
const turn = begin(bot.threadId, record);
coordinator.endTurn(turn.id, { ok: false, text: why });
@@ -151,103 +172,109 @@ describe("quota-switch card", () => {
rmSync(DATA_DIR, { recursive: true, force: true });
});
- describe("what is offered", () => {
- it("offers the other engines that can run now, never the current one, and takes no free text", async () => {
- const messageId = said("how's the weather");
- const card = await failed(QUOTA, { messageId });
- expect(card?.card).toMatchObject({
- title: "Claude is out of quota",
- subtitle: "Continue this conversation with another AI?",
- options: ["Codex", "Cursor", NOT_NOW],
- fixedOptions: true,
- // the failed request's own root in the job runtime rides the card
- quotaSwitch: { engines: [{ instanceId: "codex", name: "Codex" }, { instanceId: "cursor", name: "Cursor" }], messageId, rootId: "g1" },
- });
- expect(card!.card!.requestId).toBeTruthy();
- expect(card!.card!.tool).toBeUndefined();
- expect(pending()?.id).toBe(card!.id);
- });
-
- it("offers at most three engines, then Not now", async () => {
- engines.push(engine("grok", "grokAgent", "Grok"), engine("gemini", "geminiAgent", "Gemini"));
- expect((await failed())!.card!.options).toEqual(["Codex", "Cursor", "Grok", NOT_NOW]);
- });
-
- it("raises no second card in a thread while one is pending", async () => {
- expect(await failed()).toBeTruthy();
- expect(await failed()).toBeNull();
- expect(cards()).toHaveLength(1);
+ describe("carrying on by itself", () => {
+ let told: Array<{ botId: string; from: ModelSelection; facts: unknown }>;
+ let moves: Array<{ threadId: string; from: ModelSelection; to: ModelSelection; resetsAt?: number }>;
+ let backups: ModelSelection[];
+ let flags: { limit?: "engine" | "model" | "credits"; limitResetsAt?: number } | undefined;
+ const CODEX = { instanceId: "codex", model: "codex-default" }, CURSOR = { instanceId: "cursor", model: "cursor-default" };
+ beforeEach(() => {
+ told = [];
+ moves = [];
+ backups = [CODEX, CURSOR];
+ flags = undefined;
+ deps.turnStops = { failureCause: () => cause, read: () => (flags ? { flags } : undefined) };
+ deps.takeover = {
+ backups: () => backups, tell: (who, from, facts) => { told.push({ botId: who.id, from, facts }); },
+ moved: (_botId, threadId, from, to, resetsAt) => { moves.push({ threadId, from, to, ...(resetsAt ? { resetsAt } : {}) }); },
+ };
+ quota = createQuotaSwitch(deps);
});
+ /** The person's request that the AI's usage limit refused. */
+ const limited = async (record: Partial<QuotaRequest> = {}, why = QUOTA) => {
+ const turn = begin(bot.threadId, record);
+ coordinator.endTurn(turn.id, { ok: false, text: why });
+ return ranOut(turn, why);
+ };
- it("raises one card when two failures of the same thread are read at once", async () => {
- const raised = await Promise.all([failed(), failed()]);
- expect(raised.filter(Boolean)).toHaveLength(1);
- expect(cards()).toHaveLength(1);
- });
+ it("moves the request to the first AI that can take it, sends the same message again there, offers no card and says so once", async () => {
+ const quoted = store.appendMessage(bot.threadId, { role: "bot", kind: "text", text: "It will rain on Friday." }).id;
+ const messageId = said("how's the weather", { dataContext: { cardId: "sales" }, replyToId: quoted });
+ expect(await limited({ messageId })).toBeNull();
- it("raises no card for an error that is not a quota or usage limit", async () => {
- expect(await failed("500 internal server error")).toBeNull();
- expect(await failed("Not logged in · Please run /login")).toBeNull();
expect(cards()).toHaveLength(0);
+ expect(gate.mock.calls[0]![1]).toEqual(CODEX);
+ expect(thread().modelSelection).toEqual(CODEX);
+ expect(store.bot(bot.id)!.modelSelection, "the bot's own model and its other conversations stay").toEqual(defaultSelection());
+ expect(resend).toHaveBeenCalledTimes(1);
+ const [, , message, replyTo, spoken] = resend.mock.calls[0]!;
+ expect(message).toMatchObject({ id: messageId, text: "how's the weather", dataContext: { cardId: "sales" } });
+ expect(replyTo).toMatchObject({ id: quoted });
+ expect(spoken).toEqual({});
+ expect(notices()).toContainEqual({ name: "notice: continuing on Codex after hitting the usage limit", ok: true });
+ expect(told).toEqual([{ botId: bot.id, from: defaultSelection(), facts: { scope: "engine", backup: CODEX } }]);
+ expect(moves, "so it goes back once the limit resets").toEqual([{ threadId: bot.threadId, from: defaultSelection(), to: CODEX }]);
});
- it("raises no card when no other engine is configured", async () => {
- engines = [engines[0]!];
- expect(await failed()).toBeNull();
- });
-
- it("never offers an engine that cannot run a turn when the card is built", async () => {
- engines = [
- engines[0]!,
- engine("gone", "codex", "Uninstalled", { snapshot: async () => ({ state: "unavailable", reason: "not installed" }) }),
- engine("out", "codex", "Signed out", { snapshot: async () => ({ state: "available", authenticated: false }) }),
- engine("off", "codex", "Switched off", { enabled: false }),
- engine("broken", "codex", "Broken", { snapshot: async () => { throw new Error("probe failed"); } }),
- engine("empty", "codex", "No model", { models: { default: "", options: [] } }),
- engine("barred", "codex", "Barred"),
- engine("codex", "codex", "Codex"),
- ];
- deps.refusal = (candidate) => candidate.instanceId === "barred" ? "Your organisation does not allow this engine." : undefined;
- expect((await failed())!.card!.options).toEqual(["Codex", NOT_NOW]);
+ it("goes by the engine's own limit flag and its reset when it gives them", async () => {
+ flags = { limit: "engine", limitResetsAt: 1_900_000_000_000 };
+ await limited({ messageId: said("hi") }, "This Claude account has reached its 5-hour limit, which resets Oct 28 at 2:00 PM.");
+ expect(thread().modelSelection).toEqual(CODEX);
+ expect(told[0]!.facts).toEqual({ resetsAt: 1_900_000_000_000, scope: "engine", backup: CODEX });
+ expect(moves).toEqual([{ threadId: bot.threadId, from: defaultSelection(), to: CODEX, resetsAt: 1_900_000_000_000 }]);
});
- it("offers a custom endpoint whatever its sign-in state says: it brings its own credential", async () => {
- engines = [engines[0]!, engine("local", "codex", "Local model", { snapshot: async () => ({ state: "available", authenticated: false }) })];
- deps.access = (instanceId) => instanceId === "local" ? "custom" : "subscription";
- expect((await failed())!.card!.options).toEqual(["Local model", NOT_NOW]);
+ it("for one model's own limit carries on with the same AI's other model", async () => {
+ engines[0] = engine("claude", "claudeAgent", "Claude", { models: { default: "claude-default", options: [{ id: "claude-default", label: "Default" }, { id: "claude-plan", label: "Plan" }] } });
+ flags = { limit: "credits" };
+ backups = [{ instanceId: "claude", model: "claude-plan" }];
+ await limited({ messageId: said("hi") });
+ expect(thread().modelSelection).toEqual({ instanceId: "claude", model: "claude-plan" });
+ expect(resend).toHaveBeenCalledTimes(1);
+ expect(notices()).toContainEqual({ name: "notice: continuing on Claude claude-plan after hitting the usage limit", ok: true });
+ expect(told[0]!.facts).toEqual({ scope: "credits", backup: { instanceId: "claude", model: "claude-plan" } });
+ });
+
+ it.each<[string, () => void]>([
+ ["one that cannot run a turn now", () => { engines[1] = engine("codex", "codex", "Codex", { snapshot: async () => ({ state: "unavailable", reason: "signed out" }) }); }],
+ ["one the model-switch gate refuses", () => { gate.mockImplementationOnce(() => ({ ok: false, error: "the bot is working" })); }],
+ ["one that does not support this AI's tools", () => { engines[0] = engine("claude", "claudeAgent", "Claude", { adapter: { capabilities: caps({ agentsMcp: true }) } }); engines[2] = engine("cursor", "cursorAgent", "Cursor", { adapter: { capabilities: caps({ agentsMcp: true }) } }); }],
+ ])("skips %s and carries on with the next", async (_name, arrange) => {
+ arrange();
+ await limited({ messageId: said("hi") });
+ expect(thread().modelSelection).toEqual(CURSOR);
+ expect(resend).toHaveBeenCalledTimes(1);
+ expect(told[0]!.facts).toMatchObject({ backup: CURSOR });
});
- it("builds the card without an engine that does not say how it is in time", async () => {
+ it("skips an AI that does not say how it is in time", async () => {
engines[1] = silent("codex", "Codex");
- const raising = failed(QUOTA, { messageId: said("hi") });
- // Codex was asked first; its wait is the one an engine probe gets elsewhere.
- expect(timers[0]).toMatchObject({ ms: PROBE_TIMEOUT_MS, cancelled: false });
- timers[0]!.fire();
- expect((await raising)!.card!.options).toEqual(["Cursor", NOT_NOW]);
- // an engine that answered stopped its clock
- expect(timers[1]).toMatchObject({ cancelled: true });
+ const going = limited({ messageId: said("hi") });
+ await vi.waitFor(() => expect(timers.filter((timer) => !timer.cancelled).map((timer) => timer.ms)).toEqual([PROBE_TIMEOUT_MS]));
+ timers.find((timer) => !timer.cancelled)!.fire();
+ await going;
+ expect(thread().modelSelection).toEqual(CURSOR);
});
- it("raises no card when every other engine is unavailable", async () => {
- engines = engines.map((candidate) => candidate.instanceId === "claude" ? candidate
- : { ...candidate, snapshot: async () => ({ state: "unavailable" as const }) });
- expect(await failed()).toBeNull();
- });
-
- it("never offers an engine known to be at its own limit, and offers it again once a turn on it succeeds", async () => {
+ it("never moves to an AI known to be at its own limit, until a turn on it works again", async () => {
const codexThread = store.createTask(bot.id, undefined, false)!.threadId;
- store.switchTaskModel(bot.id, codexThread, { instanceId: "codex", model: "codex-default" }, false, false);
+ store.switchTaskModel(bot.id, codexThread, CODEX, false, false);
const onCodex = store.projectBotForTask(bot.id, codexThread)!;
- // Codex runs out in another conversation; that one is offered Claude and Cursor.
- const elsewhere = await fails(begin(codexThread), "usage limit reached", false, onCodex);
- expect(elsewhere!.card!.options).toEqual(["Claude", "Cursor", NOT_NOW]);
- // Now Claude runs out here: Codex is known to be limited, so only Cursor is offered.
- const first = (await failed())!;
- expect(first.card!.options).toEqual(["Cursor", NOT_NOW]);
- await answer(first, NOT_NOW);
- // A turn on Codex completes: it works again.
+ await ranOut(begin(codexThread), "usage limit reached", true, onCodex);
+ await limited({ messageId: said("hi") });
+ expect(thread().modelSelection).toEqual(CURSOR);
quota.turnSucceeded(onCodex, codexThread);
- expect((await failed())!.card!.options).toEqual(["Codex", "Cursor", NOT_NOW]);
+ store.switchTaskModel(bot.id, bot.threadId, defaultSelection(), false, false);
+ await limited({ messageId: said("hi again") });
+ expect(thread().modelSelection).toEqual(CODEX);
+ });
+
+ it("says it waits when no AI can take it, and moves nothing", async () => {
+ backups = [];
+ await limited({ messageId: said("hi") });
+ expect(thread().modelSelection).toEqual(defaultSelection());
+ expect(resend).not.toHaveBeenCalled();
+ expect(told).toEqual([{ botId: bot.id, from: defaultSelection(), facts: { scope: "engine" } }]);
});
it.each<[string, { internal?: boolean; record?: Partial<QuotaRequest> | null }]>([
@@ -256,87 +283,60 @@ describe("quota-switch card", () => {
["a request whose record names another provider turn", { record: { turnId: "another-turn" } }],
["a request the person stopped", { record: { stopped: true } }],
["a turn with no request record", { record: null }],
- ])("raises no card for %s, and still remembers that its engine ran out", async (_name, { internal = false, record = {} }) => {
- const codexThread = store.createTask(bot.id, undefined, false)!.threadId;
- store.switchTaskModel(bot.id, codexThread, { instanceId: "codex", model: "codex-default" }, false, false);
- const turn = begin(codexThread, record ?? {});
- if (record === null) requests.delete(codexThread);
- expect(await fails(turn, QUOTA, internal, store.projectBotForTask(bot.id, codexThread)!)).toBeNull();
- expect(store.messagesFor(codexThread)).toEqual([]);
- expect((await failed())!.card!.options).toEqual(["Cursor", NOT_NOW]);
- });
-
- it("raises no card when the engine the thread runs on is no longer here: there is nothing to check a backup against", async () => {
- engines = engines.filter((candidate) => candidate.instanceId !== "claude");
- expect(await failed()).toBeNull();
- expect(cards()).toHaveLength(0);
- });
-
- it("posts no card for a thread that went on while the engines were being read", async () => {
- // Codex takes a while to say how it is; meanwhile the person's next turn works.
- let known!: (snapshot: ProviderSnapshot) => void;
- const slow = () => engine("codex", "codex", "Codex", { snapshot: () => new Promise((resolve) => { known = resolve; }) });
- engines[1] = slow();
- const raising = failed(QUOTA, { messageId: said("hi") });
- quota.turnSucceeded(thread(), bot.threadId);
- known({ state: "available", authenticated: true });
- expect(await raising).toBeNull();
- expect(cards()).toHaveLength(0);
- // a turn that works in another thread makes nothing stale here
- engines[1] = slow();
- const again = failed(QUOTA, { messageId: said("hi again") });
- const otherThread = store.createTask(bot.id, undefined, false)!.threadId;
- quota.turnSucceeded(store.projectBotForTask(bot.id, otherThread)!, otherThread);
- known({ state: "available", authenticated: true });
- expect(await again).toBeTruthy();
- });
-
- it("offers only engines that pass the backup check: the same tools, the same workspace", async () => {
- engines = [
- engine("claude", "claudeAgent", "Claude", { adapter: { capabilities: caps({ agentsMcp: true, images: true }) } }),
- engine("bare", "codex", "No team tools", { adapter: { capabilities: caps({ images: true }) } }),
- // an API model has no working folder (supportsWorkspaceFiles)
- engine("api", "openai-compat", "API model", { adapter: { capabilities: caps({ agentsMcp: true, images: true }) } }),
- engine("codex", "codex", "Codex", { adapter: { capabilities: caps({ agentsMcp: true, images: true, browserMcp: true }) } }),
- ];
- expect((await failed())!.card!.options).toEqual(["Codex", NOT_NOW]);
+ ])("sends nothing again for %s and only says what carries on", async (_name, { internal = false, record = {} }) => {
+ const turn = begin(bot.threadId, record ?? {});
+ if (record === null) requests.delete(bot.threadId);
+ await ranOut(turn, QUOTA, internal);
+ expect(thread().modelSelection).toEqual(defaultSelection());
+ expect(resend).not.toHaveBeenCalled();
+ expect(told).toEqual([{ botId: bot.id, from: defaultSelection(), facts: { scope: "engine", backup: CODEX } }]);
});
- it("never offers an engine this conversation's approval level cannot move to", async () => {
- // Auto-accept edits exists on Claude and Grok, not on Codex or Cursor.
- store.patchTask(bot.id, bot.threadId, { approvalMode: "edits", autoApprove: false });
- engines.push(engine("grok", "grokAgent", "Grok"));
- expect((await failed())!.card!.options).toEqual(["Grok", NOT_NOW]);
+ it("never sends again a line a bot delivered", async () => {
+ await limited({ messageId: said("Do the quarterly numbers", { peerAsk: { botId: "chief", name: "Chief" } }) });
+ expect(resend).not.toHaveBeenCalled();
+ expect(told).toHaveLength(1);
});
- it("tells two engines with the same name apart", async () => {
- engines = [engines[0]!, engine("work", "codex", "Codex"), engine("home", "codex", "Codex")];
- const card = (await failed())!;
- expect(card.card!.options).toEqual(["Codex", "Codex (home)", NOT_NOW]);
- await answer(card, "Codex (home)");
- expect(thread().modelSelection).toEqual({ instanceId: "home", model: "home-default" });
+ it("does nothing for an error that is not a usage limit", async () => {
+ await limited({ messageId: said("hi") }, "500 internal server error");
+ await limited({ messageId: said("hi") }, "Not logged in · Please run /login");
+ expect(told).toEqual([]);
+ expect(resend).not.toHaveBeenCalled();
});
- it("raises nothing when it is switched off", async () => {
+ it("only says what happens when it is switched off", async () => {
enabled = false;
- expect(await failed()).toBeNull();
- expect(cards()).toHaveLength(0);
+ await limited({ messageId: said("hi") });
+ expect(thread().modelSelection).toEqual(defaultSelection());
+ expect(told).toHaveLength(1);
});
- it("says on the card to send the message again when there is none to resend", async () => {
- const card = (await failed(QUOTA, { messageId: undefined }))!;
- expect(card.card!.subtitle).toBe("Switch this conversation to another AI? Send your message again afterwards.");
- expect(card.card!.quotaSwitch!.messageId).toBeUndefined();
+ it("leaves a conversation that went on while the next AI was being read", async () => {
+ let known!: (snapshot: ProviderSnapshot) => void;
+ engines[1] = engine("codex", "codex", "Codex", { snapshot: () => new Promise((resolve) => { known = resolve; }) });
+ const going = limited({ messageId: said("hi") });
+ await vi.waitFor(() => expect(known).toBeTypeOf("function"));
+ quota.turnSucceeded(thread(), bot.threadId);
+ known({ state: "available", authenticated: true });
+ await going;
+ expect(thread().modelSelection).toEqual(defaultSelection());
+ expect(resend).not.toHaveBeenCalled();
});
- it("raises no card for a turn that answered a bot's line, which is never the person's to send again", async () => {
- const peerLine = said("Do the quarterly numbers", { peerAsk: { botId: "chief", name: "Chief" } });
- expect(await failed(QUOTA, { messageId: peerLine })).toBeNull();
- expect(cards()).toHaveLength(0);
+ it("moves a request the job runtime still holds but sends nothing again: the runtime resumes it", async () => {
+ const turn = begin(bot.threadId, { messageId: said("ask the team for the numbers") });
+ const mate = store.createBot();
+ coordinator.enqueue({ botId: bot.id, threadId: bot.threadId }, turn.id, undefined, { botId: mate.id, threadId: mate.threadId }, "Pull the quarter's numbers");
+ coordinator.endTurn(turn.id, { ok: false, text: QUOTA });
+ await ranOut(turn);
+ expect(thread().modelSelection).toEqual(CODEX);
+ expect(resend).not.toHaveBeenCalled();
+ expect(notices()).toEqual([{ name: "notice: switched to Codex. Your request is still under way here and continues on Codex.", ok: true }]);
});
});
- describe("the person's answer", () => {
+ describe("answering a card an earlier version left open", () => {
it("switches this conversation through the model-switch gate and resends the exact message that failed", async () => {
const quoted = store.appendMessage(bot.threadId, { role: "bot", kind: "text", text: "It will rain on Friday." }).id;
const messageId = said("how's the weather", { dataContext: { cardId: "sales" }, replyToId: quoted });
@@ -569,7 +569,7 @@ describe("quota-switch card", () => {
const card = (await failed(QUOTA, { messageId: said("hi") }))!;
const codexThread = store.createTask(bot.id, undefined, false)!.threadId;
store.switchTaskModel(bot.id, codexThread, { instanceId: "codex", model: "codex-default" }, false, false);
- await fails(begin(codexThread), QUOTA, true, store.projectBotForTask(bot.id, codexThread)!);
+ await ranOut(begin(codexThread), QUOTA, true, store.projectBotForTask(bot.id, codexThread)!);
await answer(card, "Codex");
diff --git a/server/quota-switch.ts b/server/quota-switch.ts
index 815ea7911b..f6485f8f0f 100644
--- a/server/quota-switch.ts
+++ b/server/quota-switch.ts
@@ -4,7 +4,6 @@
import { approvalModeFor, modelSwitchNeedsAsk } from "../shared/approval-mode.ts";
import type { QuotaSwitchCardData } from "../shared/wire.ts";
import { recoveryCapabilityError } from "./automatic-recovery.ts";
-import { newId } from "./contracts.ts";
import type { EngineAccess, ModelCatalog, ModelSelection, ProviderAdapter, ProviderSnapshot } from "./contracts.ts";
import type { Coordinator } from "./coordinator.ts";
import { readyToRun, selectDefaultModelSelection, type SelectableInstance } from "./default-model-selection.ts";
@@ -14,6 +13,7 @@ import { spokenLineFields } from "./live-call-record.ts";
import type { WorkOrigin } from "./peer-provenance.ts";
import type { BotRecord, Message, Store, TaskRecord } from "./store.ts";
import type { TurnStops } from "./turn-outcome.ts";
+import type { LimitTakeover } from "./host/limit-takeover.ts";
export interface QuotaSwitchEngine {
instanceId: string;
@@ -39,7 +39,9 @@ export interface QuotaSwitchDeps {
store: Store;
coordinator: Pick<Coordinator, "all" | "node">;
registry: { instances(): QuotaSwitchEngine[] };
- turnStops: Pick<TurnStops, "failureCause">;
+ turnStops: Pick<TurnStops, "failureCause"> & Partial<Pick<TurnStops, "read">>;
+ /** Which AIs carry on while one is limited, and the one notice for each stretch of a limit. */
+ takeover?: Pick<LimitTakeover, "backups" | "tell" | "moved">;
/** A custom endpoint brings its own credential, so its sign-in state does not count. */
access?: (instanceId: string) => EngineAccess | undefined;
refusal?: (engine: QuotaSwitchEngine) => string | undefined;
@@ -64,12 +66,12 @@ export interface QuotaSwitch {
export type QuotaAnswer = "answered" | "rejected" | "unavailable";
-const MAX_ENGINES = 3;
export const NOT_NOW = "Not now";
const ENDED: ReadonlySet<string> = new Set(["completed", "failed", "cancelled"]);
-/** On unless OMB_QUOTA_SWITCH=0: the card is only an offer. */
+/** On unless OMB_QUOTA_SWITCH=0: a limited AI's work carries on with another AI by itself. Off, only the backups
+ * Automatic recovery names take over, as before. */
export function quotaSwitchEnabled(env: NodeJS.ProcessEnv = process.env): boolean {
return env.OMB_QUOTA_SWITCH?.trim() !== "0";
}
@@ -145,53 +147,87 @@ export function createQuotaSwitch(deps: QuotaSwitchDeps): QuotaSwitch {
.filter((node) => !node.parentId && node.threadId === threadId && request.generations.has(node.id))
.sort((a, b) => a.createdAt - b.createdAt).at(-1)?.id;
+ /** Moves the thread to `selection` and sends the person's message that hit the limit again there; false when that AI
+ * cannot take it now. No await from the readiness check to the resend: the gate, the switch and the resend see one state. */
+ const continueOn = async (botId: string, threadId: string, selection: ModelSelection, request: QuotaRequest, build: { stale: boolean }, resetsAt?: number): Promise<boolean> => {
+ const engines = deps.registry.instances();
+ const engine = engines.find((candidate) => candidate.instanceId === selection.instanceId);
+ const before = store.projectBotForTask(botId, threadId);
+ const current = before && engines.find((candidate) => candidate.instanceId === before.modelSelection.instanceId);
+ if (!engine || !before || !current) return false;
+ const ready = engine.instanceId === current.instanceId ? selection : await takeover(engine, before, current);
+ const bot = store.projectBotForTask(botId, threadId);
+ if (!ready || ready === "timed-out" || !bot || build.stale || !store.taskByThread(botId, threadId)) return false;
+ const checked = deps.gate(bot, selection);
+ if (!checked.ok) return false;
+ try {
+ store.switchTaskModel(botId, threadId, checked.selection, false, false, deps.reset?.(bot.modelSelection, checked.selection));
+ } catch {
+ return false;
+ }
+ deps.takeover?.moved(botId, threadId, before.modelSelection, checked.selection, resetsAt);
+ const name = engine.instanceId === current.instanceId ? `${nameOf(engine)} ${checked.selection.model}` : nameOf(engine);
+ const held = heldBy(botId, threadId, rootOf(threadId, request));
+ const original = held ? undefined : resendable(store, threadId, request.messageId);
+ if (held === "card") notice(threadId, `switched to ${name}. Your request waits on a card above and continues on ${name} once you act on it.`, true);
+ else if (held === "runtime") notice(threadId, `switched to ${name}. Your request is still under way here and continues on ${name}.`, true);
+ else if (held === "busy") notice(threadId, `switched to ${name}. This conversation is working, so your message was not sent again.`, true);
+ else if (held === "question") {
+ notice(threadId, `switched to ${name}. A teammate's question is waiting for your answer in this conversation, so your message was not sent again — answer it, then send your message again.`, false);
+ } else if (!original) {
+ notice(threadId, `switched to ${name}, but the message that hit the limit could not be found to resend — send it again.`, false);
+ } else {
+ notice(threadId, `continuing on ${name} after hitting the usage limit`, true);
+ try {
+ await deps.resend(botId, threadId, original, original.replyToId ? store.messagesFor(threadId).find((message) => message.id === original.replyToId) : undefined, spokenLineFields(original.via, original.callId));
+ } catch (error) {
+ if (store.taskByThread(botId, threadId)) notice(threadId, `could not continue on ${name} — ${(error instanceof Error ? error.message : String(error)).slice(0, 200)}`, false);
+ }
+ }
+ return true;
+ };
+
+ /** A turn its AI's usage limit refused: the person's own message carries on with the first AI that can take it, the
+ * person hears once for this stretch of the limit what carries on meanwhile, and the AI's later turns go there too until
+ * the limit resets (the turn start's own check). */
const turnFailed = async (bot: BotRecord, event: SettledTurn, internal: boolean): Promise<Message | null> => {
const { threadId } = event;
try {
// Read before any await: the record is this turn's only now.
const request = deps.request(threadId);
- if (classifyError({ text: deps.turnStops.failureCause(event) ?? "" }).reason !== "quota") return null;
- const currentId = bot.modelSelection.instanceId;
- limited.add(currentId);
+ const flags = deps.turnStops.read?.(threadId, event.turnId)?.flags;
+ const scope = flags?.limit ?? (classifyError({ text: deps.turnStops.failureCause(event) ?? "" }).reason === "quota" ? "engine" : undefined);
+ if (!scope) return null;
+ const thread = store.projectBotForTask(bot.id, threadId) ?? bot;
+ const from = thread.modelSelection;
+ if (scope === "engine") limited.add(from.instanceId);
+ // OMB_QUOTA_SWITCH=0: nothing carries on by itself; the person still hears once that the bot waits.
+ const backups = enabled() ? deps.takeover?.backups(bot.id, from, scope) ?? [] : [];
+ const tell = (backup?: ModelSelection) => deps.takeover?.tell(thread, from, { ...(flags?.limitResetsAt ? { resetsAt: flags.limitResetsAt } : {}), scope, ...(backup ? { backup } : {}) });
// Only the person's own request: never a routine's, a webhook's, a relayed or a guest's.
const own = !internal && request && !request.stopped && request.origin?.kind === "user"
&& (!request.turnId || !event.turnId || request.turnId === event.turnId);
- if (!own || !enabled() || openCard(threadId)) return null;
- const messageId = request.messageId;
- if (messageId && store.messagesFor(threadId).find((message) => message.id === messageId)?.peerAsk) return null;
- const engines = deps.registry.instances();
- const current = engines.find((engine) => engine.instanceId === currentId);
- if (!current) return null;
- const others = engines.filter((engine) => engine.instanceId !== currentId);
+ const relayed = request?.messageId && store.messagesFor(threadId).find((message) => message.id === request.messageId)?.peerAsk;
+ if (!own || !request || relayed || !enabled() || openCard(threadId)) {
+ tell(backups[0]);
+ return null;
+ }
const build = { threadId, stale: false };
building.add(build);
- const able = await Promise.all(others.map((engine) => takeover(engine, bot, current))).finally(() => building.delete(build));
- const offered: QuotaSwitchCardData["engines"] = [];
- for (const engine of others.filter((_, index) => able[index] && able[index] !== "timed-out").slice(0, MAX_ENGINES)) {
- // The label is the answer, so two engines of one name must differ.
- const name = nameOf(engine);
- const taken = name === NOT_NOW || offered.some((other) => other.name === name);
- offered.push({ instanceId: engine.instanceId, name: taken ? `${name} (${engine.instanceId})` : name });
+ try {
+ for (const selection of backups) {
+ if (await continueOn(bot.id, threadId, selection, request, build, flags?.limitResetsAt)) {
+ tell(selection);
+ return null;
+ }
+ }
+ } finally {
+ building.delete(build);
}
- // No await between this check and the write, so a thread never holds two open offers.
- if (!offered.length || build.stale || !store.taskByThread(bot.id, threadId) || openCard(threadId)) return null;
- const original = resendable(store, threadId, messageId);
- const rootId = rootOf(threadId, request);
- return store.appendMessage(threadId, {
- role: "bot",
- kind: "options",
- card: {
- title: `${nameOf(current)} is out of quota`,
- subtitle: original ? "Continue this conversation with another AI?"
- : "Switch this conversation to another AI? Send your message again afterwards.",
- options: [...offered.map((engine) => engine.name), NOT_NOW],
- requestId: newId(),
- fixedOptions: true,
- quotaSwitch: { engines: offered, ...(original ? { messageId: original.id } : {}), ...(rootId ? { rootId } : {}) },
- },
- });
+ tell();
+ return null;
} catch (error) {
- console.warn(`quota switch: no card for ${threadId}: ${error instanceof Error ? error.message : String(error)}`);
+ console.warn(`quota switch: could not continue ${threadId}: ${error instanceof Error ? error.message : String(error)}`);
return null;
}
};
diff --git a/server/routine-recovery.ts b/server/routine-recovery.ts
index 60439fa884..9370409d7a 100644
--- a/server/routine-recovery.ts
+++ b/server/routine-recovery.ts
@@ -23,6 +23,8 @@ export interface RoutineFailureFacts {
stalled?: boolean;
trialCredit?: string;
limitResetsAt?: number;
+ /** A usage limit refused it (the runtime error's `limit`). */
+ limit?: "engine" | "model" | "credits";
/** A backup engine takes over from one whose usage limit refused the run. */
backupReady?: boolean;
}
@@ -83,8 +85,8 @@ export function classifyRoutineFailure(failure: string, facts: RoutineFailureFac
if (facts.stalled) return { kind: "retry", cause: "stalled" };
const engine = engineFailureKind(failure);
const { reason, transient } = classifyError({ text: failure });
- if (facts.trialCredit || engine === "credits") return { kind: "owner", cause: "credits" };
- if (facts.limitResetsAt || facts.stopReason === "quota" || engine === "usage_limit") {
+ if (facts.trialCredit || (engine === "credits" && !facts.limit)) return { kind: "owner", cause: "credits" };
+ if (facts.limit || facts.limitResetsAt || facts.stopReason === "quota" || engine === "usage_limit") {
return { kind: "owner", cause: "usage_limit", ...(facts.limitResetsAt ? { resetsAt: facts.limitResetsAt } : {}) };
}
if (facts.stopReason === "auth_required" || reason === "auth") return { kind: "owner", cause: "signed_out" };
@@ -110,8 +112,8 @@ export function retriesTeammateThread(failure: string, facts: RoutineFailureFact
return classifyRoutineFailure(failure, facts).kind === "retry";
}
-export function engineFacts({ setup, stalled, trialCredit, limitResetsAt }: RuntimeEvent & { type: "runtime.error" }): RoutineFailureFacts {
- return { setup, stalled, trialCredit, limitResetsAt };
+export function engineFacts({ setup, stalled, trialCredit, limitResetsAt, limit }: RuntimeEvent & { type: "runtime.error" }): RoutineFailureFacts {
+ return { setup, stalled, trialCredit, limitResetsAt, limit };
}
/** Host-local, with its zone: on a Cloud home the host's zone need not be the reader's. */
diff --git a/server/routines.ts b/server/routines.ts
index 77649c8075..046c272893 100644
--- a/server/routines.ts
+++ b/server/routines.ts
@@ -259,7 +259,7 @@ export interface RoutineManagerOptions {
/** When an engine's usage limit resets (epoch ms), or null while that is not known. */
limitResetAt?: (engine: string) => number | null;
/** The bot has a backup engine to continue on when its own engine's usage limit refuses a run. */
- limitBackup?: (botId: string) => boolean;
+ limitBackup?: (botId: string, scope?: "engine" | "model" | "credits") => boolean;
/** Work this thread handed to another bot is still open, so its wait is not only on the person. */
handedOffWorkLive?: (threadId: string) => boolean;
launchId?: string;
@@ -1317,7 +1317,7 @@ export class RoutineManager {
private settleFailure(run: RoutineRun, failure: string, facts: RoutineFailureFacts) {
this.failureFacts.delete(run.id);
if (this.closing) return;
- const backupReady = facts.limitResetsAt !== undefined && this.options.limitBackup?.(run.botId) === true;
+ const backupReady = (facts.limit !== undefined || facts.limitResetsAt !== undefined) && this.options.limitBackup?.(run.botId, facts.limit) === true;
const recovery = recoverRun(run, failure, { ...facts, ...(backupReady ? { backupReady } : {}) }, this.now(), this.ownerNotices);
if (!recovery.queued) this.failRun(run, recovery.error, "failed", recovery.alert);
else {
diff --git a/server/turn-outcome.ts b/server/turn-outcome.ts
index bd324960cd..de31d1de8f 100644
--- a/server/turn-outcome.ts
+++ b/server/turn-outcome.ts
@@ -14,8 +14,8 @@ export interface TurnStop {
turnId?: string;
cause?: string;
error?: string;
- /** The engine's own flags on that error (a setup or credit refusal, a stall, a usage limit's reset). */
- flags?: Pick<RuntimeError, "setup" | "stalled" | "trialCredit" | "limitResetsAt">;
+ /** The engine's own flags on that error (a setup or credit refusal, a stall, a usage limit and its reset). */
+ flags?: Pick<RuntimeError, "setup" | "stalled" | "trialCredit" | "limitResetsAt" | "limit">;
handoffPath?: string;
}
@@ -34,8 +34,8 @@ export class TurnStops {
if (event.type === "cap.exhausted") stop.handoffPath = event.handoffPath;
else stop.error = error;
if (event.type === "runtime.error") {
- const { setup, stalled, trialCredit, limitResetsAt } = event;
- if (setup || stalled || trialCredit || limitResetsAt) stop.flags = { setup, stalled, trialCredit, limitResetsAt };
+ const { setup, stalled, trialCredit, limitResetsAt, limit } = event;
+ if (setup || stalled || trialCredit || limitResetsAt || limit) stop.flags = { setup, stalled, trialCredit, limitResetsAt, limit };
}
}
diff --git a/shared/runtime-events.ts b/shared/runtime-events.ts
index fbe3e5cd7f..6bae367626 100644
--- a/shared/runtime-events.ts
+++ b/shared/runtime-events.ts
@@ -189,8 +189,10 @@ export type RuntimeEvent = RuntimeEventBase &
// `trialCredit`: the trial's Claude credit refused the call.
// `stalled`: the engine went silent and the turn was stopped as stuck.
// `limitResetsAt`: epoch ms when the usage limit refusing this account resets, when the engine says.
+ // `limit`: a usage limit refused this turn: the account's on this engine ("engine"), one model's own window
+ // ("model"), or that model's extra usage credits ("credits"); the engine's other models still work for the last two.
| { type: "runtime.error"; message: string; setup?: boolean; terminal?: boolean; claudeUpdate?: boolean; trialCredit?: "used_up" | "ended" | "paused" | "too_low";
- stalled?: boolean; limitResetsAt?: number }
+ stalled?: boolean; limitResetsAt?: number; limit?: "engine" | "model" | "credits" }
/** Something the person should know that did not fail the turn — for
* example, a saved model the engine no longer offers was replaced. */
| { type: "runtime.notice"; message: string }