Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(limits): say in the server log why each backup was passed over (#5657)
laijsg19d06188c1c17
diff --git a/server/host/limit-takeover.test.ts b/server/host/limit-takeover.test.tsindex f37f787212..d7ff5cbdb6 100644--- a/server/host/limit-takeover.test.ts+++ b/server/host/limit-takeover.test.ts@@ -130,6 +130,57 @@ describe("which AI carries on while one is limited", () => {it("has none for an AI it doesn't know", () => {expect(takeover().instance.backups("kai", on("gone", "m"))).toEqual([]);});++ it("says why it left out each backup the person chose, and leaves the choice as it was", () => {+ const unread = engine("cursor", "cursorAgent", ["auto"], { snapshot: { state: "unavailable", reason: "not read yet" } });+ const fewerTools = engine("claude", "claudeAgent", ["claude-opus-5-5"], { capabilities: { agentsMcp: true } as unknown as TakeoverEngine["capabilities"] });+ const secondCodex = engine("codex-2", "codex", ["gpt-6"]);+ const chosen = [on("codex", "gpt-6-mini"), on("gone", "m"), on("cursor", "auto"), on("codex-2", "gpt-6"), on("claude", "claude-opus-5-5"),+ on("opencode", "go-gone"), on("opencode", "go-default"), on("cursor", "auto")];+ const { instance } = takeover({ engines: () => [CODEX, unread, secondCodex, fewerTools, GO], chosen: () => chosen });+ const weighed = instance.weighBackups("kai", on("codex", "gpt-6"));+ expect(weighed.backups).toEqual([on("opencode", "go-default")]);+ expect(weighed.backups).toEqual(instance.backups("kai", on("codex", "gpt-6")));+ expect(weighed.skipped, "each once, in the person's order").toEqual([+ { selection: on("codex", "gpt-6-mini"), why: "limited" },+ { selection: on("gone", "m"), why: "not-configured" },+ { selection: on("cursor", "auto"), why: "not-ready", detail: "not read yet" },+ { selection: on("codex-2", "gpt-6"), why: "same-plan" },+ { selection: on("claude", "claude-opus-5-5"), why: "missing-capability", detail: "The backup does not support all of this AI's tools and attachments." },+ { selection: on("opencode", "go-gone"), why: "unknown-model" },+ ]);+ });++ it("says a backup is at its own limit, holding that model, signed out, or one the thread's approval level must ask about", () => {+ const chosen = { chosen: () => [on("claude", "claude-opus-5-5"), on("opencode", "go-default")] };+ const limited = takeover({ blockedUntil: (id) => (id === "claude" ? NOW + HOUR : null), ...chosen }).instance;+ expect(limited.weighBackups("kai", on("codex", "gpt-6")).skipped).toEqual([{ selection: on("claude", "claude-opus-5-5"), why: "limited" }]);+ const held = takeover(chosen).instance;+ held.holdModel(on("claude", "claude-opus-5-5"), "model");+ expect(held.weighBackups("kai", on("codex", "gpt-6")).skipped).toEqual([{ selection: on("claude", "claude-opus-5-5"), why: "model-held" }]);+ const signedOut = takeover(chosen).instance;+ signedOut.noteSignedOut("claude");+ expect(signedOut.weighBackups("kai", on("codex", "gpt-6")).skipped).toEqual([{ selection: on("claude", "claude-opus-5-5"), why: "signed-out" }]);+ expect(takeover(chosen).instance.weighBackups("kai", on("codex", "gpt-6"), "engine", "edits").skipped.map((one) => one.why)).toContain("needs-approval");+ expect(takeover({ chosen: () => [on("claude", "claude-opus-5-5")] }).instance.weighBackups("kai", on("claude", "claude-opus-5-5"), "model").skipped,+ "the refused model itself is no backup passed over").toEqual([]);+ });++ it("writes each backup it passed over to the server log", () => {+ const lines: string[] = [];+ const { instance } = takeover({ log: (line) => lines.push(line) });+ instance.passedOver(KAI, on("codex", "gpt-6"), "engine", [+ { selection: on("cursor", "auto"), why: "not-ready", detail: "not read yet" },+ { selection: on("claude", "claude-opus-5-5"), why: "probe-timed-out" },+ ]);+ instance.passedOver(KAI, on("codex", "gpt-6"), "engine", []);+ instance.passedOver(KAI, on("codex", "gpt-6"), "engine", [{ selection: on("ollama", "llama"), why: "not-ready", detail: "Can't reach Ollama at http://me:[email protected]:11434" }]);+ expect(lines.pop(), "an address's credential stays out of the log").not.toContain("hunter2pass");+ expect(lines).toEqual([+ "limit takeover: Kai (kai) on codex/gpt-6 (engine) passed over backup cursor/auto: not-ready (not read yet)",+ "limit takeover: Kai (kai) on codex/gpt-6 (engine) passed over backup claude/claude-opus-5-5: probe-timed-out",+ ]);+ });});describe("a model's own limit", () => {diff --git a/server/host/limit-takeover.ts b/server/host/limit-takeover.tsindex 768a5700e0..2b2e723e50 100644--- a/server/host/limit-takeover.ts+++ b/server/host/limit-takeover.ts@@ -15,6 +15,7 @@ import { classifyError } from "../drivers/retry.ts";import { failoverLine, limitBackupAllowed, signedOutLine, type LimitFailover } from "../limit-failover.ts";import { LimitNotices, limitNoticeText, signedOutNoticeText } from "../limit-notices.ts";import { UNNAMED_LIMIT_MS } from "../limit-resets.ts";+import { redactSecretsInText } from "../redact.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@@ -37,6 +38,10 @@ const EVERY_BOT = "every-bot";/** 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 BackupSkip = "not-configured" | "not-ready" | "limited" | "model-held" | "signed-out" | "same-plan" | "needs-approval"+ | "missing-capability" | "unknown-model" | "probe-timed-out" | "switch-refused" | "conversation-changed";+export interface SkippedBackup { selection: ModelSelection; why: BackupSkip; detail?: string }+export type TakeoverEngine = SelectableInstance & { displayName?: string; capabilities: ProviderAdapter["capabilities"] };type Bot = { id: string; name: string };/** A bot as one of its threads sees it: its approval level decides which AI it may move to by itself. */@@ -73,6 +78,7 @@ export interface LimitTakeoverDeps {signedOutNoticed?(instanceId: string): void;/** The bots that run on this AI, for the sign-out notice's list of those with nothing to carry on for them. */botsOn?(instanceId: string): Array<ThreadBot & { modelSelection: ModelSelection }>;+ log?(line: string): void;now?(): number;}@@ -160,38 +166,65 @@ export function createLimitTakeover(deps: LimitTakeoverDeps) {notices.endedEverywhere(signedOutKey(instanceId));};- const usable = (engines: TakeoverEngine[], current: TakeoverEngine, selection: ModelSelection, scope: TakeoverScope, approval?: ApprovalMode): boolean => {+ const notReady = (engine: TakeoverEngine): string => engine.enabled === false ? "switched off"+ : engine.snapshot.state !== "available" ? engine.snapshot.reason ?? "unavailable"+ : engine.snapshot.authenticated === false ? "signed out" : deps.context.refusal?.(engine) ?? "not ready";++ const skipped = (engines: TakeoverEngine[], current: TakeoverEngine, selection: ModelSelection, scope: TakeoverScope, approval?: ApprovalMode): Omit<SkippedBackup, "selection"> | null => {const engine = engines.find((candidate) => candidate.instanceId === selection.instanceId);- if (!engine || !readyToRun(engine, deps.context) || deps.blockedUntil(engine.instanceId, selection.model) !== null || modelHeld(selection) !== null) return false;+ if (!engine) return { why: "not-configured" };+ if (!readyToRun(engine, deps.context)) return { why: "not-ready", detail: notReady(engine) };+ if (deps.blockedUntil(engine.instanceId, selection.model) !== null) return { why: "limited" };+ if (modelHeld(selection) !== null) return { why: "model-held" };if (engine.instanceId !== current.instanceId) {- if (signedOutHeld(engine.instanceId)) return false;+ if (signedOutHeld(engine.instanceId)) return { why: "signed-out" };// Another sign-in to the same plan never carries a limit (that rotates accounts); it may stand in for one signed out.- if (scope !== "signed-out" && !limitBackupAllowed(current, engine, deps.configs()[engine.instanceId])) return false;+ if (scope !== "signed-out" && !limitBackupAllowed(current, engine, deps.configs()[engine.instanceId])) return { why: "same-plan" };// The same rule as switching by hand: a level the other AI has no such mode for needs the person first.- if (approval && modelSwitchNeedsAsk(approval, current.driverKind, engine.driverKind)) return false;+ if (approval && modelSwitchNeedsAsk(approval, current.driverKind, engine.driverKind)) return { why: "needs-approval" };}- if (recoveryCapabilityError(current, engine)) return false;- return engine.models.default === selection.model || engine.models.options.some((model) => model.id === selection.model);+ const missing = recoveryCapabilityError(current, engine);+ if (missing) return { why: "missing-capability", detail: missing };+ return engine.models.default === selection.model || engine.models.options.some((model) => model.id === selection.model) ? null : { why: "unknown-model" };};/** The AIs that may carry on while `from` is limited or signed out, best first: for one model's limit the same AI's own* default model, then the backups the person chose. No other AI is picked for them: with none of those usable the bot- * waits for the reset or a sign-in. `approval`: the thread's level, when known. */- function backups(botId: string, from: ModelSelection, scope: TakeoverScope = "engine", approval?: ApprovalMode): ModelSelection[] {+ * waits for the reset or a sign-in. `approval`: the thread's level, when known. `skipped`: each backup left out, and why. */+ function weighBackups(botId: string, from: ModelSelection, scope: TakeoverScope = "engine", approval?: ApprovalMode): { backups: ModelSelection[]; skipped: SkippedBackup[] } {const engines = deps.engines();const current = engines.find((engine) => engine.instanceId === from.instanceId);- if (!current) return [];+ if (!current) return { backups: [], skipped: [] };const out: ModelSelection[] = [];+ const left: SkippedBackup[] = [];const add = (selection: ModelSelection) => {- if (selection.instanceId === from.instanceId && (scope === "engine" || scope === "signed-out" || selection.model === from.model)) return;- if (out.some((known) => known.instanceId === selection.instanceId && known.model === selection.model)) return;- if (usable(engines, current, selection, scope, approval)) out.push({ instanceId: selection.instanceId, model: selection.model });+ const pick = { instanceId: selection.instanceId, model: selection.model };+ if (pick.instanceId === from.instanceId && pick.model === from.model) return;+ if ([...out, ...left.map((one) => one.selection)].some((known) => known.instanceId === pick.instanceId && known.model === pick.model)) return;+ if (pick.instanceId === from.instanceId && (scope === "engine" || scope === "signed-out")) {+ left.push({ selection: pick, why: scope === "signed-out" ? "signed-out" : "limited" });+ return;+ }+ const why = skipped(engines, current, pick, scope, approval);+ if (why) left.push({ selection: pick, ...why });+ else out.push(pick);};if (scope === "model" || scope === "credits") add({ instanceId: current.instanceId, model: current.models.default });for (const selection of scope === "signed-out" ? deps.signedOutChosen?.(botId) ?? deps.chosen(botId) : deps.chosen(botId)) add(selection);- return out;+ return { backups: out, skipped: left };+ }++ function backups(botId: string, from: ModelSelection, scope: TakeoverScope = "engine", approval?: ApprovalMode): ModelSelection[] {+ return weighBackups(botId, from, scope, approval).backups;}+ const passedOver = (bot: Bot, from: ModelSelection, scope: TakeoverScope, left: readonly SkippedBackup[]): void => {+ for (const { selection, why, detail } of left) {+ // A status reason or a refusal may carry an engine's address with its credential in it.+ (deps.log ?? console.warn)(redactSecretsInText(`limit takeover: ${bot.name} (${bot.id}) on ${from.instanceId}/${from.model} (${scope}) passed over backup ${selection.instanceId}/${selection.model}: ${why}${detail ? ` (${detail})` : ""}`));+ }+ };+const label = (selection: ModelSelection, from: ModelSelection) => (selection.instanceId === from.instanceId? `${deps.engineName(selection.instanceId)} ${selection.model}` : deps.engineName(selection.instanceId));/** What refused, as the person knows it: the AI, or for one model's own limit that AI's model. */@@ -232,6 +265,8 @@ export function createLimitTakeover(deps: LimitTakeoverDeps) {return {backups,+ weighBackups,+ passedOver,/** 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,diff --git a/server/host/peer-limit-resend.test.ts b/server/host/peer-limit-resend.test.tsindex 5ee7363881..ad04f78492 100644--- a/server/host/peer-limit-resend.test.ts+++ b/server/host/peer-limit-resend.test.ts@@ -47,7 +47,7 @@ function fixture(rows: Message[] = [], overrides: Partial<PeerLimitResendDeps<OpactivePath: () => rows, appendMessage: (_threadId: string, row: Message) => { appended.push(row); return row; }, switchTaskModel,},registry: { get: (id: string) => id === "codex" ? engine("codex", "codex") : engine("claude", "claude") },- takeover: () => ({ backups: () => [{ instanceId: "codex", model: "gpt" }], carriedOn: () => [{ name: "recovery: Claude is at its limit, Codex carries on", ok: true }] }),+ takeover: () => ({ weighBackups: () => ({ backups: [{ instanceId: "codex", model: "gpt" }], skipped: [] }), passedOver: () => {}, carriedOn: () => [{ name: "recovery: Claude is at its limit, Codex carries on", ok: true }] }),turnStops: { read: () => ({ error: `Claude says: ${LIMIT}`, flags: { limit: "engine" } }), failureCause: () => `Claude says: ${LIMIT}` },hostedModels: null,providerConfigs: () => ({}),@@ -127,7 +127,7 @@ describe("peer limit resend", () => {});it("reports the held failure as before when no backup can take it or a newer turn took the thread", async () => {- const none = fixture([ask, failure], { takeover: () => ({ backups: () => [], carriedOn: () => [] }) } as never);+ const none = fixture([ask, failure], { takeover: () => ({ weighBackups: () => ({ backups: [], skipped: [] }), passedOver: () => {}, carriedOn: () => [] }) } as never);none.resend.track({ generation: "gen-1", botId: "helper", threadId: "t1", text: "x", opts: peerOpts, userMessage: ask });none.resend.ended(none.failed, "gen-1", false);none.resend.hold("gen-1", { ok: false, text: "limit" });diff --git a/server/host/peer-limit-resend.ts b/server/host/peer-limit-resend.tsindex 0b576848a2..62239c348e 100644--- a/server/host/peer-limit-resend.ts+++ b/server/host/peer-limit-resend.ts@@ -52,7 +52,7 @@ type EndedTurn = SettledTurn & { threadId: string; turnId?: string; ok: booleanexport interface PeerLimitResendDeps<Opts, Outcome> {store: Pick<Store, "botByThread" | "projectBotForTask" | "taskByThread" | "activePath" | "appendMessage" | "switchTaskModel">;registry: Pick<ProviderRegistry, "get">;- takeover(): Pick<LimitTakeover, "backups" | "carriedOn">;+ takeover(): Pick<LimitTakeover, "weighBackups" | "passedOver" | "carriedOn">;turnStops: Pick<TurnStops, "read" | "failureCause">;hostedModels: ReturnType<typeof hostedModelPolicy>;providerConfigs(): InstanceConfigMap;@@ -184,7 +184,9 @@ export function createPeerLimitResend<Opts extends PeerTurnOpts<Outcome>, Outcom// A file the turn made lands after its end was judged: anything it left by now still means no resend.|| !nothingRan(store.activePath(threadId), turn.since, turn.turnId, turn.stopError)) return giveUp();const from = current.modelSelection, instance = registry.get(from.instanceId);- const backup = deps.takeover().backups(turn.botId, from, turn.scope, approvalModeFor(current)).find(candidate => {+ const { backups, skipped } = deps.takeover().weighBackups(turn.botId, from, turn.scope, approvalModeFor(current));+ deps.takeover().passedOver(current, from, turn.scope, skipped);+ const backup = backups.find(candidate => {const target = registry.get(candidate.instanceId);return target?.enabled && (candidate.instanceId !== from.instanceId || candidate.model !== from.model)&& (candidate.instanceId === from.instanceId ? turn.scope !== "engine" : !instance || limitBackupAllowed(instance, target, deps.providerConfigs()[candidate.instanceId]));diff --git a/server/index.ts b/server/index.tsindex df7cd87924..f22d1752c5 100644--- a/server/index.ts+++ b/server/index.ts@@ -8469,8 +8469,9 @@ async function beginTurn(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), takeoverScope = e instanceof TurnUsageLimitRefusedError ? e.scope : e instanceof TurnAuthenticationRefusedError ? "signed-out" as const : undefined;- const backups = takeoverScope && current && quotaSwitchEnabled() ? limitTakeover.backups(bot.id, current.modelSelection, takeoverScope, approvalModeFor(current))- : current ? startupBackups(current, cfg.automaticRecovery) : [];+ const weighed = takeoverScope && current && quotaSwitchEnabled() ? limitTakeover.weighBackups(bot.id, current.modelSelection, takeoverScope, approvalModeFor(current)) : null;+ if (weighed && takeoverScope && current) limitTakeover.passedOver(current, current.modelSelection, takeoverScope, weighed.skipped);+ const backups = weighed ? weighed.backups : current ? startupBackups(current, cfg.automaticRecovery) : [];const nextIndex = backups.findIndex((candidate, index) => index >= (opts?.automaticRecoveryIndex ?? 0) &®istry.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) &&diff --git a/server/quota-switch.test.ts b/server/quota-switch.test.tsindex 424c2eea7d..f44a57a6dd 100644--- a/server/quota-switch.test.ts+++ b/server/quota-switch.test.ts@@ -9,6 +9,7 @@ import { PROBE_TIMEOUT_MS } from "./engine-install.ts";import { closeMessageDb } from "./message-db.ts";import { createQuotaSwitch, NOT_NOW, quotaSwitchEnabled, type QuotaRequest, type QuotaSwitch, type QuotaSwitchDeps, type QuotaSwitchEngine } from "./quota-switch.ts";import { Store, type BotRecord, type Message } from "./store.ts";+import type { SkippedBackup } from "./host/limit-takeover.ts";import { toolFailureMessage } from "./drivers/tool-failure.ts";const QUOTA = "You've hit your weekly limit · resets Oct 12 at 2:30pm (Asia/Calcutta)";@@ -177,16 +178,19 @@ describe("quota switch", () => {let told: Array<{ botId: string; from: ModelSelection; facts: unknown }>;let moves: Array<{ threadId: string; from: ModelSelection; to: ModelSelection; resetsAt?: number }>;let backups: ModelSelection[];+ let passed: SkippedBackup[];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];+ passed = [];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 }); return null; },+ weighBackups: () => ({ backups, skipped: [] }), passedOver: (_bot, _from, _scope, left) => { passed.push(...left); },+ tell: (who, from, facts) => { told.push({ botId: who.id, from, facts }); return null; },moved: (_botId, threadId, from, to, resetsAt) => { moves.push({ threadId, from, to, ...(resetsAt ? { resetsAt } : {}) }); },};quota = createQuotaSwitch(deps);@@ -246,25 +250,37 @@ describe("quota switch", () => {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) => {+ it.each<[string, () => void, Omit<SkippedBackup, "selection">]>([+ ["one that cannot run a turn now", () => { engines[1] = engine("codex", "codex", "Codex", { snapshot: async () => ({ state: "unavailable", reason: "signed out" }) }); }, { why: "not-ready" }],+ ["one the model-switch gate refuses", () => { gate.mockImplementationOnce(() => ({ ok: false, error: "the bot is working" })); }, { why: "switch-refused", detail: "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 }) } }); }, { why: "missing-capability" }],+ ])("skips %s, says why, and carries on with the next", async (_name, arrange, why) => {arrange();await limited({ messageId: said("hi") });expect(thread().modelSelection).toEqual(CURSOR);expect(resend).toHaveBeenCalledTimes(1);expect(told[0]!.facts).toMatchObject({ backup: CURSOR });+ expect(passed).toEqual([{ selection: CODEX, ...why }]);});- it("skips an AI that does not say how it is in time", async () => {+ it("skips an AI that does not say how it is in time, and says so", async () => {engines[1] = silent("codex", "Codex");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);+ expect(passed).toEqual([{ selection: CODEX, why: "probe-timed-out" }]);+ });++ it("says why a backup was left out even when nothing is sent again", async () => {+ const left: SkippedBackup = { selection: CODEX, why: "same-plan" };+ deps.takeover = { ...deps.takeover!, weighBackups: () => ({ backups: [CURSOR], skipped: [left] }) };+ quota = createQuotaSwitch(deps);+ await ranOut(begin(bot.threadId, { messageId: said("hi") }), QUOTA, true);+ expect(resend).not.toHaveBeenCalled();+ expect(passed).toEqual([left]);+ expect(told[0]!.facts).toMatchObject({ backup: CURSOR });});it("never moves to an AI known to be at its own limit, until a turn on it works again", async () => {@@ -353,7 +369,7 @@ describe("quota switch", () => {beforeEach(() => {scopes = [];deps.takeover = {- backups: (_botId, _from, scope) => { scopes.push(scope); return backups; },+ weighBackups: (_botId, _from, scope) => { scopes.push(scope); return { backups, skipped: [] }; }, passedOver: () => {},tell: (who, from, facts) => { told.push({ botId: who.id, from, facts }); return told.length === 1 ? NOTICE : null; },moved: (_botId, threadId, from, to, resetsAt, scope) => { moves.push({ threadId, from, to, ...(resetsAt ? { resetsAt } : {}), ...(scope ? { scope } : {}) } as never); },};diff --git a/server/quota-switch.ts b/server/quota-switch.tsindex 2c9c64d657..b5e807557b 100644--- a/server/quota-switch.ts+++ b/server/quota-switch.ts@@ -14,7 +14,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 { signedOutStop, type LimitTakeover, type TakeoverScope } from "./host/limit-takeover.ts";+import { signedOutStop, type BackupSkip, type LimitTakeover, type SkippedBackup, type TakeoverScope } from "./host/limit-takeover.ts";export interface QuotaSwitchEngine {instanceId: string;@@ -42,7 +42,7 @@ export interface QuotaSwitchDeps {registry: { instances(): QuotaSwitchEngine[] };turnStops: Pick<TurnStops, "failureCause"> & Partial<Pick<TurnStops, "read">>;/** Which AIs carry on while one is limited or signed out, and the one notice for each stretch of either. */- takeover?: Pick<LimitTakeover, "backups" | "tell" | "moved">;+ takeover?: Pick<LimitTakeover, "weighBackups" | "passedOver" | "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;@@ -134,44 +134,47 @@ export function createQuotaSwitch(deps: QuotaSwitchDeps): QuotaSwitch {};/** One rule for the card and for the answer. */- const takeover = async (engine: QuotaSwitchEngine, bot: BotRecord, current: QuotaSwitchEngine | undefined): Promise<ModelSelection | "timed-out" | null> => {+ const takeover = async (engine: QuotaSwitchEngine, bot: BotRecord, current: QuotaSwitchEngine | undefined): Promise<ModelSelection | BackupSkip> => {// No current engine: no backup check can be made, so none passes.- if (!current || limited.has(engine.instanceId)) return null;+ if (!current) return "not-configured";+ if (limited.has(engine.instanceId)) return "limited";if (recoveryCapabilityError({ driverKind: current.driverKind, capabilities: current.adapter.capabilities },{ driverKind: engine.driverKind, capabilities: engine.adapter.capabilities },- )) return null;- if (modelSwitchNeedsAsk(approvalModeFor(bot), current.driverKind, engine.driverKind)) return null;+ )) return "missing-capability";+ if (modelSwitchNeedsAsk(approvalModeFor(bot), current.driverKind, engine.driverKind)) return "needs-approval";const context = { refusal: () => deps.refusal?.(engine) };const instance = await described(engine);- if (!instance) return "timed-out";- if (!readyToRun(instance, context)) return null;+ if (!instance) return "probe-timed-out";+ if (!readyToRun(instance, context)) return "not-ready";const selection = selectDefaultModelSelection([instance], undefined, context);- return selection.instanceId && selection.model ? selection : null;+ return selection.instanceId && selection.model ? selection : "unknown-model";};/** The newest root: a backup engine's retry or a change of computer begins another root for the same request. */const rootOf = (threadId: string, request: QuotaRequest): string | undefined => coordinator.newestRoot(threadId, request.generations)?.id;/** Moves the thread to `selection` and sends the person's message that hit the limit (or met a signed-out AI) 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. */+ * there; null once it does, else why 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,- scope: TakeoverScope = "engine"): Promise<boolean> => {+ scope: TakeoverScope = "engine"): Promise<Omit<SkippedBackup, "selection"> | null> => {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;+ if (!before) return { why: "conversation-changed" };+ if (!engine || !current) return { why: "not-configured" };const ready = engine.instanceId === current.instanceId ? selection : await takeover(engine, before, current);+ if (typeof ready === "string") return { why: ready };const bot = store.projectBotForTask(botId, threadId);- if (!ready || ready === "timed-out" || !bot || build.stale || !store.taskByThread(botId, threadId)) return false;+ if (!bot || build.stale || !store.taskByThread(botId, threadId)) return { why: "conversation-changed" };const checked = deps.gate(bot, selection);- if (!checked.ok) return false;+ if (!checked.ok) return { why: "switch-refused", detail: checked.error };try {store.switchTaskModel(botId, threadId, checked.selection, false, false, deps.reset?.(bot.modelSelection, checked.selection));- } catch {- return false;+ } catch (error) {+ return { why: "switch-refused", detail: error instanceof Error ? error.message : String(error) };}deps.takeover?.moved(botId, threadId, before.modelSelection, checked.selection, resetsAt, scope);const name = engine.instanceId === current.instanceId ? `${nameOf(engine)} ${checked.selection.model}` : nameOf(engine);@@ -193,7 +196,7 @@ export function createQuotaSwitch(deps: QuotaSwitchDeps): QuotaSwitch {if (store.taskByThread(botId, threadId)) notice(threadId, `could not continue on ${name}: ${(error instanceof Error ? error.message : String(error)).slice(0, 200)}`, false, false, { key: "chat.notice.backupCouldNotContinue", params: { name, error: (error instanceof Error ? error.message : String(error)).slice(0, 200) } });}}- return true;+ return null;};/** A turn its AI's usage limit refused, or that met its AI signed out: the person's own message carries on with the@@ -212,7 +215,7 @@ export function createQuotaSwitch(deps: QuotaSwitchDeps): QuotaSwitch {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, approvalModeFor(thread)) ?? [] : [];+ const { backups, skipped } = enabled() ? deps.takeover?.weighBackups(bot.id, from, scope, approvalModeFor(thread)) ?? { backups: [], skipped: [] } : { backups: [], skipped: [] };const resetsAt = scope === "signed-out" ? undefined : flags?.limitResetsAt;// A sign-out is told once, first and without a backup's name: what the person must do is sign in again.const told = scope === "signed-out" ? deps.takeover?.tell(thread, from, { scope }) : undefined;@@ -225,6 +228,7 @@ export function createQuotaSwitch(deps: QuotaSwitchDeps): QuotaSwitch {&& (!request.turnId || !event.turnId || request.turnId === event.turnId);const relayed = request?.messageId && store.messagesFor(threadId).find((message) => message.id === request.messageId)?.peerAsk;if (!own || !request || relayed || !enabled() || openCard(threadId)) {+ deps.takeover?.passedOver(thread, from, scope, skipped);tell(backups[0]);return null;}@@ -232,13 +236,16 @@ export function createQuotaSwitch(deps: QuotaSwitchDeps): QuotaSwitch {building.add(build);try {for (const selection of backups) {- if (await continueOn(bot.id, threadId, selection, request, build, resetsAt, scope)) {+ const why = await continueOn(bot.id, threadId, selection, request, build, resetsAt, scope);+ if (!why) {tell(selection);return null;}+ skipped.push({ selection, ...why });}} finally {building.delete(build);+ deps.takeover?.passedOver(thread, from, scope, skipped);}tell();return null;@@ -303,8 +310,8 @@ export function createQuotaSwitch(deps: QuotaSwitchDeps): QuotaSwitch {const card = offer();const bot = store.projectBotForTask(botId, threadId);if (!card || !bot) return false;- if (selection === "timed-out") return refuse(`${chosen.name} did not answer in time — nothing switched. Try again in a moment.`);- if (!selection) return refuse(`${chosen.name} is no longer available — nothing switched.`);+ if (selection === "probe-timed-out") return refuse(`${chosen.name} did not answer in time — nothing switched. Try again in a moment.`);+ if (typeof selection === "string") return refuse(`${chosen.name} is no longer available — nothing switched.`);const already = bot.modelSelection.instanceId === selection.instanceId;if (!already) {const checked = deps.gate(bot, selection);