Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Resend a bot-to-bot turn once to the backup AI when its limit hit before anything ran
AdityaUmale070de401f7cd
diff --git a/server/host/peer-limit-resend.test.ts b/server/host/peer-limit-resend.test.tsnew file mode 100644index 0000000000..9a2a150339--- /dev/null+++ b/server/host/peer-limit-resend.test.ts@@ -0,0 +1,146 @@+import { describe, expect, it, vi } from "vitest";+import type { Message } from "../store.ts";+import { createPeerLimitResend, nothingRan, type PeerLimitResendDeps, type PeerTurnOpts } from "./peer-limit-resend.ts";++type Outcome = { ok: boolean; text: string };+type Opts = PeerTurnOpts<Outcome> & { origin?: { kind: string } };++const ask: Message = { id: "ask-1", at: 100, role: "user", kind: "text", text: "Check the build", peerAsk: { botId: "chief", name: "Chief" } } as Message;+const LATER = Date.now() + 3_600_000;+const failure: Message = { id: "f", at: LATER, role: "bot", kind: "activity", tool: { name: "You've hit your usage limit", ok: false } } as Message;+const toolCall: Message = { id: "x", at: LATER, role: "bot", kind: "activity", turnId: "turn-1", tool: { name: "Bash", itemId: "item-1" } } as Message;+const reply: Message = { id: "r", at: LATER, role: "bot", kind: "text", turnId: "turn-1", text: "Half done" } as Message;+const LIMIT = "You've hit your usage limit";++describe("nothingRan", () => {+ it("counts only what the turn did, never its own limit failure", () => {+ expect(nothingRan([ask, failure], 100, "turn-1")).toBe(true);+ // Some engines send the limit sentence as reply text.+ expect(nothingRan([{ ...reply, text: LIMIT }], 100, "turn-1", LIMIT)).toBe(true);+ expect(nothingRan([toolCall, failure], 100, "turn-1")).toBe(false);+ expect(nothingRan([reply, failure], 100, "turn-1")).toBe(false);+ expect(nothingRan([{ ...reply, kind: "widget" } as Message], 100, "turn-1")).toBe(false);+ });++ it("ignores rows from before the turn, from another turn, and the hand-off's request card", () => {+ expect(nothingRan([{ ...toolCall, at: 50 }], 100, "turn-1")).toBe(true);+ expect(nothingRan([{ ...toolCall, turnId: "turn-0" }], 100, "turn-1")).toBe(true);+ // The request card is written just before the turn, sometimes in the same millisecond.+ expect(nothingRan([{ ...reply, at: Date.now() + 1_000, turnId: undefined, text: "@Helper Check the build", roomRequest: { id: "r1", phase: "request" } } as Message, failure], 100, "turn-1")).toBe(true);+ });+});++/** One bot on Claude with Codex as its backup, and a thread whose rows the test sets. */+function fixture(rows: Message[] = [], overrides: Partial<PeerLimitResendDeps<Opts, Outcome>> = {}, stopReason = "error") {+ const bot = { id: "helper", threadId: "t1", modelSelection: { instanceId: "claude", model: "opus" } };+ const engine = (instanceId: string, driverKind: string) => ({ instanceId, driverKind, displayName: driverKind, enabled: true, adapter: { capabilities: {} } });+ let generation: string | undefined = "gen-1";+ const startTurn = vi.fn(async (_botId: string, _text: string, _opts: Opts) => undefined);+ const settle = vi.fn((_generation: string, _outcome: Outcome) => undefined);+ const switchTaskModel = vi.fn();+ const appended: Message[] = [];+ const deps = {+ store: {+ botByThread: () => bot, projectBotForTask: () => bot, taskByThread: () => ({ cwd: "/work" }),+ activePath: () => 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 }] }),+ turnStops: { read: () => ({ error: `Claude says: ${LIMIT}`, flags: { limit: "engine" } }), failureCause: () => `Claude says: ${LIMIT}` },+ hostedModels: null,+ providerConfigs: () => ({}),+ quotaSwitchEnabled: () => true,+ policyModelRefusal: () => undefined,+ checkedTaskModelSwitch: (_bot: unknown, selection: unknown) => ({ ok: true, selection }),+ assertWithinBudget: () => undefined,+ handedOff: (id: string) => id === "child",+ guest: () => false,+ generation: () => generation,+ blocked: () => false,+ settle, release: vi.fn(), startTurn,+ ...overrides,+ } as unknown as PeerLimitResendDeps<Opts, Outcome>;+ const resend = createPeerLimitResend<Opts, Outcome>(deps);+ const failed = { type: "turn.completed", threadId: "t1", turnId: "turn-1", ok: false, stopReason } as const;+ return { resend, startTurn, settle, switchTaskModel, appended, failed, newGeneration: () => { generation = "gen-2"; } };+}+const peerOpts: Opts = { peerAsk: ask.peerAsk, origin: { kind: "outside" } };+const flush = () => new Promise((resolve) => setImmediate(resolve));++describe("peer limit resend", () => {+ it("resends a peer turn once on the backup when its limit came before anything ran, with its options unchanged", async () => {+ const { resend, startTurn, settle, switchTaskModel, failed } = fixture([ask, failure]);+ resend.track({ generation: "gen-1", botId: "helper", threadId: "t1", text: "Check the build", opts: peerOpts, userMessage: ask, latestUser: "ask-1" });+ resend.ended(failed, "gen-1", false);+ expect(resend.hold("gen-1", { ok: false, text: "limit" })).toBe(true);+ expect(resend.resend("t1")).toBe(true);+ await flush();+ expect(switchTaskModel).toHaveBeenCalledWith("helper", "t1", { instanceId: "codex", model: "gpt" }, false, false, { rewound: true });+ expect(startTurn).toHaveBeenCalledTimes(1);+ const [, text, opts] = startTurn.mock.calls[0];+ expect(text).toBe("Check the build");+ // Still the sender's line, never the person's: the same provenance, only marked as the one resend.+ expect(opts).toEqual({ ...peerOpts, threadId: "t1", userMessage: ask, editedMessageId: undefined, peerLimitResent: true });+ expect(opts.peerAsk).toBe(peerOpts.peerAsk);+ expect(opts.origin).toBe(peerOpts.origin);+ expect(settle).not.toHaveBeenCalled();+ // Once only.+ expect(resend.resend("t1")).toBe(false);+ });++ it("tracks only a relayed ask or a teammate's hand-off, never the person's own request, a routine's, a guest's or a resend", () => {+ const person = { ...ask, peerAsk: undefined } as Message;+ const cases: Array<[Opts, Message, boolean]> = [+ [peerOpts, ask, true],+ [{ coordination: { id: "child" } }, ask, true],+ [{}, person, false],+ [{ coordination: { id: "root" } }, person, false],+ [{ ...peerOpts, automationSource: { kind: "routine" } }, ask, false],+ [{ ...peerOpts, peerLimitResent: true }, ask, false],+ [{ coordination: { id: "child", resumed: true } }, ask, false],+ ];+ for (const [opts, userMessage, tracked] of cases) {+ const { resend, failed } = fixture([userMessage, failure]);+ resend.track({ generation: "gen-1", botId: "helper", threadId: "t1", text: "x", opts, userMessage });+ resend.ended(failed, "gen-1", false);+ expect(resend.hold("gen-1", { ok: false, text: "limit" }), JSON.stringify(opts)).toBe(tracked);+ }+ const guest = fixture([ask, failure], { guest: () => true });+ guest.resend.track({ generation: "gen-1", botId: "helper", threadId: "t1", text: "x", opts: peerOpts, userMessage: ask });+ guest.resend.ended(guest.failed, "gen-1", false);+ expect(guest.resend.hold("gen-1", { ok: false, text: "limit" })).toBe(false);+ });++ it("never resends after a tool call or a reply, or for a sign-out or any other failure", () => {+ const signedOut = { turnStops: { read: () => ({ error: "Not signed in" }), failureCause: () => "Not signed in" } } as never;+ const otherFailure = { turnStops: { read: () => ({ error: "Something broke" }), failureCause: () => "Something broke" } } as never;+ for (const [rows, overrides, stopReason] of [[[ask, toolCall, failure], {}, "error"], [[ask, reply, failure], {}, "error"], [[ask, failure], signedOut, "auth_required"], [[ask, failure], otherFailure, "error"]] as const) {+ const { resend, startTurn, failed } = fixture([...rows], overrides, stopReason);+ resend.track({ generation: "gen-1", botId: "helper", threadId: "t1", text: "x", opts: peerOpts, userMessage: ask });+ resend.ended(failed, "gen-1", false);+ expect(resend.hold("gen-1", { ok: false, text: "limit" })).toBe(false);+ expect(resend.resend("t1")).toBe(false);+ expect(startTurn).not.toHaveBeenCalled();+ }+ });++ 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);+ 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" });+ expect(none.resend.resend("t1")).toBe(true);+ await flush();+ expect(none.startTurn).not.toHaveBeenCalled();+ expect(none.settle).toHaveBeenCalledWith("gen-1", { ok: false, text: "limit" });++ const replaced = fixture([ask, failure]);+ replaced.resend.track({ generation: "gen-1", botId: "helper", threadId: "t1", text: "x", opts: peerOpts, userMessage: ask });+ replaced.resend.ended(replaced.failed, "gen-1", false);+ replaced.resend.hold("gen-1", { ok: false, text: "limit" });+ replaced.newGeneration();+ expect(replaced.resend.resend("t1")).toBe(false);+ expect(replaced.settle).toHaveBeenCalledWith("gen-1", { ok: false, text: "limit" });+ expect(replaced.startTurn).not.toHaveBeenCalled();+ });+});diff --git a/server/host/peer-limit-resend.ts b/server/host/peer-limit-resend.tsnew file mode 100644index 0000000000..f4e01e4119--- /dev/null+++ b/server/host/peer-limit-resend.ts@@ -0,0 +1,185 @@+import { approvalModeFor } from "../../shared/approval-mode.ts";+import { recoveryCapabilityError } from "../automatic-recovery.ts";+import type { InstanceConfigMap } from "../contracts.ts";+import type { ProviderRegistry } from "../harness/registry.ts";+import type { hostedModelPolicy } from "../hosted-models.ts";+import { limitBackupAllowed } from "../limit-failover.ts";+import { turnLimitScope, type QuotaSwitchDeps, type SettledTurn } from "../quota-switch.ts";+import type { BotRecord, Message, Store } from "../store.ts";+import type { TurnStops } from "../turn-outcome.ts";+import type { LimitTakeover, TakeoverScope } from "./limit-takeover.ts";++/** The start options a bot-to-bot turn keeps when it is resent: all of them, so it never gains authority. */+export interface PeerTurnOpts<Outcome> {+ threadId?: string;+ userMessage?: Message;+ editedMessageId?: string;+ peerAsk?: unknown;+ cardContinuation?: boolean;+ coordination?: { id: string; resumed?: unknown; settle?: (outcome: Outcome) => void };+ onSettled?: (outcome: Outcome) => void;+ computerSelectionContinuation?: unknown;+ goalRunId?: string;+ automationSource?: unknown;+ compactOnly?: boolean;+ /** This bot-to-bot turn is already the one resend on the backup AI. */+ peerLimitResent?: boolean;+}++/** A bot-to-bot turn (a relayed ask or a teammate's assignment) that may go to the bot's backup AI once. */+export interface PeerTurn<Opts> {+ generation: string;+ botId: string;+ threadId: string;+ text: string;+ opts: Opts;+ userMessage: Message;+ /** The last person/peer line when the turn began: a newer one wins over a stale resend. */+ latestUser?: string;+ since: number;+}++export interface Claimed<Opts, Outcome> extends PeerTurn<Opts> {+ scope: Exclude<TakeoverScope, "signed-out">;+ /** The failed attempt's outcome, reported when the resend cannot run. */+ held?: Outcome;+}++export interface PeerLimitResendDeps<Opts, Outcome> {+ store: Pick<Store, "botByThread" | "projectBotForTask" | "taskByThread" | "activePath" | "appendMessage" | "switchTaskModel">;+ registry: Pick<ProviderRegistry, "get">;+ takeover(): Pick<LimitTakeover, "backups" | "carriedOn">;+ turnStops: Pick<TurnStops, "read" | "failureCause">;+ hostedModels: ReturnType<typeof hostedModelPolicy>;+ providerConfigs(): InstanceConfigMap;+ quotaSwitchEnabled(): boolean;+ policyModelRefusal(instance: { instanceId: string; driverKind: string }): string | undefined;+ checkedTaskModelSwitch(+ current: BotRecord, raw: unknown, updateBotDefault: boolean, resetApprovalToAsk: boolean, requireAvailableModel?: boolean,+ ): ReturnType<QuotaSwitchDeps["gate"]>;+ /** Throws when the spend cap is reached. */+ assertWithinBudget(): void;+ /** A teammate's hand-off: its node has a parent. */+ handedOff(nodeId: string): boolean;+ /** A thread a guest drives. */+ guest(threadId: string): boolean;+ /** The thread's running turn generation. */+ generation(threadId: string): string | undefined;+ /** A busy thread, queued steering or the person's Stop: a resend never runs over them. */+ blocked(botId: string, threadId: string): boolean;+ /** Reports a hand-off's outcome (settleDirectCoordination). */+ settle(generation: string, outcome: Outcome): void;+ /** Lets go of the failed attempt's hand-off: the resend owns its result. */+ release(generation: string): void;+ startTurn(botId: string, text: string, opts: Opts): Promise<unknown>;+}++/**+ * True when the failed turn left nothing behind: no tool call, no reply, no file. Its own failure row, the+ * engine's limit sentence (`stopError`, sometimes sent as reply text) and the hand-off's request card, written+ * just before the turn (sometimes in the same millisecond), do not count.+ */+export function nothingRan(rows: readonly Message[], since: number, turnId: string | undefined, stopError?: string): boolean {+ const said = stopError?.trim();+ return !rows.some((row) => row.at >= since && row.role === "bot" && row.roomRequest?.phase !== "request" && (!turnId || !row.turnId || row.turnId === turnId) && (+ row.kind === "activity" ? Boolean(row.tool?.itemId)+ : row.kind === "text" ? Boolean(row.text?.trim()) && row.text!.trim() !== said+ : true));+}++/**+ * Resends a bot-to-bot turn once to the bot's backup AI when its own AI hit a usage limit before anything ran. The+ * resend keeps the turn's options as they were (sender, provenance, the hand-off it answers), so it never gains authority.+ */+export function createPeerLimitResend<Opts extends PeerTurnOpts<Outcome>, Outcome extends { ok: boolean; text: string }>(deps: PeerLimitResendDeps<Opts, Outcome>) {+ const { store, registry } = deps;+ /** The thread's running bot-to-bot turn. */+ const running = new Map<string, PeerTurn<Opts>>();+ /** Turns that met a limit before anything ran, until their resend is taken. */+ const claimed = new Map<string, Claimed<Opts, Outcome>>();++ /** At a turn's start: follows a relayed ask or a teammate's assignment, never the person's own, a routine's or a guest's. */+ function track(turn: Omit<PeerTurn<Opts>, "since">): void {+ const { opts } = turn;+ if (opts.peerLimitResent || opts.computerSelectionContinuation || opts.goalRunId || opts.automationSource || opts.compactOnly+ || opts.coordination?.resumed || deps.guest(turn.threadId)) return;+ if (opts.coordination ? !deps.handedOff(opts.coordination.id) : opts.cardContinuation || !(opts.peerAsk ?? turn.userMessage.peerAsk)) return;+ running.set(turn.threadId, { ...turn, since: Date.now() });+ }++ /** At the turn's end, before its hand-off hears the outcome: keeps it for a resend only for a usage limit met before anything ran. */+ function ended(event: SettledTurn & { threadId: string; turnId?: string; ok: boolean }, generation: string, capped: boolean): void {+ const turn = running.get(event.threadId);+ if (turn?.generation !== generation) return;+ running.delete(event.threadId);+ // Held only where the bot's own turn end resends it or reports the failure (never a room's thread).+ const stop = event.ok || capped || !store.botByThread(event.threadId) || !deps.quotaSwitchEnabled() ? undefined : deps.turnStops.read(event.threadId, event.turnId);+ const scope = stop && turnLimitScope(event, stop.flags, deps.turnStops.failureCause(event));+ if (!scope || scope === "signed-out" || !nothingRan(store.activePath(event.threadId), turn.since, event.turnId, stop?.error)) return;+ claimed.set(event.threadId, { ...turn, scope });+ }++ /** Keeps the failed attempt's outcome for its hand-off while the resend is pending; false when none is. */+ function hold(generation: string, outcome: Outcome): boolean {+ const turn = [...claimed.values()].find((candidate) => candidate.generation === generation);+ if (!turn) return false;+ turn.held ??= outcome;+ return true;+ }++ /** The claimed turn, once: whoever takes it resends it or settles its held outcome. */+ function take(threadId: string): Claimed<Opts, Outcome> | undefined {+ const turn = claimed.get(threadId);+ claimed.delete(threadId);+ return turn;+ }++ /** Once the turn has settled: resends a claimed turn on the backup AI; true when it will. Otherwise its hand-off hears the failure as before. */+ function resend(threadId: string): boolean {+ const turn = take(threadId);+ if (!turn) return false;+ const giveUp = (why?: string): false => {+ if (why && store.taskByThread(turn.botId, threadId)) store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: why, ok: false } });+ if (turn.held) deps.settle(turn.generation, turn.held);+ return false;+ };+ if (deps.generation(threadId) !== turn.generation) return giveUp();+ setImmediate(() => {+ // Stop, deletion, a new send, or any replacement generation wins.+ const current = store.projectBotForTask(turn.botId, threadId);+ if (!current || deps.generation(threadId) !== turn.generation || deps.blocked(turn.botId, threadId)+ || (turn.latestUser && store.activePath(threadId).findLast(m => m.role === "user" && m.kind === "text")?.id !== turn.latestUser)) 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 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]));+ });+ if (!backup) return giveUp();+ const checked = deps.checkedTaskModelSwitch(current, backup, false, false, true);+ const target = checked.ok ? registry.get(checked.selection.instanceId) : null;+ const refusal = !checked.ok ? checked.error : !target || !target.enabled ? "The backup AI is unavailable."+ : !store.taskByThread(turn.botId, threadId)?.cwd ? "This older thread has no pinned working folder. Choose its backup manually."+ : deps.policyModelRefusal(target) ?? (instance ? recoveryCapabilityError(+ { driverKind: instance.driverKind, capabilities: instance.adapter.capabilities },+ { driverKind: target.driverKind, capabilities: target.adapter.capabilities }) : undefined);+ if (refusal || !checked.ok) return giveUp(refusal && `Could not resend this to the backup AI: ${refusal}`);+ try {+ deps.assertWithinBudget();+ store.switchTaskModel(turn.botId, threadId, checked.selection, false, false, { ...deps.hostedModels?.resetTask(from, checked.selection), rewound: true });+ } catch (error) {+ return giveUp(`Could not resend this to the backup AI: ${error instanceof Error ? error.message : String(error)}`);+ }+ for (const tool of deps.takeover().carriedOn(current, threadId, from, checked.selection, { scope: turn.scope })) store.appendMessage(threadId, { role: "bot", kind: "activity", tool });+ deps.release(turn.generation);+ void deps.startTurn(turn.botId, turn.text, { ...turn.opts, threadId, userMessage: turn.userMessage, editedMessageId: undefined, peerLimitResent: true }).catch(error => {+ const why = `Could not resend this to the backup AI: ${error instanceof Error ? error.message : String(error)}`;+ (turn.opts.coordination?.settle ?? turn.opts.onSettled)?.({ ok: false, text: turn.held ? `${turn.held.text} ${why}` : why } as Outcome);+ if (store.taskByThread(turn.botId, threadId)) store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: why, ok: false } });+ });+ });+ return true;+ }++ return { track, ended, hold, resend };+}diff --git a/server/index.ts b/server/index.tsindex 6f5d35afc4..5da86b1c7d 100644--- a/server/index.ts+++ b/server/index.ts@@ -212,7 +212,7 @@ import {} from "./contracts.ts";import { RETRY_MAX_ATTEMPTS } from "./drivers/retry.ts";import { recoveryCapabilityError, startupBackups } from "./automatic-recovery.ts";-import { createQuotaSwitchHost } from "./host/quota-switch.ts"; import { quotaSwitchEnabled } from "./quota-switch.ts";+import { createQuotaSwitchHost } from "./host/quota-switch.ts"; import { quotaSwitchEnabled } from "./quota-switch.ts"; import { createPeerLimitResend } from "./host/peer-limit-resend.ts";import { decodeGeneratedImage } from "./generated-image.ts";import { createMcpServersHost } from "./host/mcp-servers-host.ts"; import { createMcpKeys } from "./vault/mcp-keys.ts"; import { createLimitTakeover, signedOutStop } from "./host/limit-takeover.ts";import {@@ -2011,7 +2011,7 @@ function hostTurnResult(node: HandoffView | undefined, generation: string, outco}function settleDirectCoordination(generation: string | undefined, settled: DirectTurnOutcome) {- if (!generation) return; const outcome = stoppedHandoffs.settle(generation, settled); // a hand-off given up before its outcome arrived+ if (!generation || (directCoordinationSettlers.has(generation) && peerLimitResend.hold(generation, settled))) return; const outcome = stoppedHandoffs.settle(generation, settled); // a hand-off given up before its outcome arrived; a held one waits for its resend on the backup AIconst moving = [...computerSelectionTurns.values()].find(turn => turn.generation === generation && turn.handoff && turn.selected); if (moving && directCoordinationSettlers.has(generation)) { moving.handoff!.outcome ??= outcome; return; } // kept for the turn continuing in the browserconst settler = directCoordinationSettlers.get(generation);directCoordinationSettlers.delete(generation);@@ -4980,7 +4980,7 @@ const TURN_STALL_MS = Math.max(60_000, stallLimitMs(process.env.OMB_TURN_STALL_Mconst TOOL_STALL_MS = Math.max(TURN_STALL_MS, stallLimitMs(process.env.OMB_TOOL_STALL_MS, 2 * 60 * 60_000));const COMPUTER_WAIT_MAX_MS = Math.max(1_000, Number(process.env.OMB_COMPUTER_WAIT_MAX_MS) || 30 * 60_000);const roomStallCompletions = new RoomTurnStallRegistry();-const turnStops = new TurnStops();+const turnStops = new TurnStops(); const peerLimitResend = createPeerLimitResend<NonNullable<Parameters<typeof startTurn>[2]>, DirectTurnOutcome>({ store, registry, takeover: () => limitTakeover, turnStops, hostedModels, providerConfigs, quotaSwitchEnabled: () => quotaSwitchEnabled(), policyModelRefusal, checkedTaskModelSwitch, assertWithinBudget: () => assertWithinBudget(cfg, DATA_DIR), handedOff: (id) => coordinator.node(id)?.parentId !== undefined, guest: (threadId) => guestDrivenTurns.has(threadId) || cloudGuestDriven(threadId), generation: (threadId) => directTurnGenerationByThread.get(threadId), blocked: (botId, threadId) => threadBusy(botId, threadId) || hasQueuedSteeredMessages(botId, threadId) || Boolean(directRequestOwners.get(threadId)?.stopped), settle: settleDirectCoordination, release: (generation) => directCoordinationSettlers.delete(generation), startTurn }); // bot-to-bot turns whose AI met its usage limit before anything ran go once to the backup AIfunction stoppedTurnText(threadId: string, turnId: string | undefined, cause?: string, stopReason?: string | null): string {const stop = turnStops.read(threadId, turnId);const reason = cause ?? stop?.cause ?? stop?.error ?? `The turn did not complete (${stopReason?.trim() || "no reason given"})`;@@ -5085,7 +5085,7 @@ bus.subscribe((event: RuntimeEvent) => {...(handoffPath ? { cap: { note: STEP_CAP_NOTE, handoffPath } } : {}) };const owner = directFollowupTurns.complete(event.threadId, event.turnId, outcome);if (owner) {- settleDirectCoordination(owner.generation, outcome);+ peerLimitResend.ended(event, owner.generation, Boolean(handoffPath)); settleDirectCoordination(owner.generation, outcome);settleDirectFollowup(owner.generation);}}@@ -6745,12 +6745,12 @@ bus.subscribe((event: RuntimeEvent) => {releaseLocalVmThread(event.threadId);}releaseTurnResources(resourceOwner);- if (!isCurrent()) return;+ if (!isCurrent()) return void peerLimitResend.resend(event.threadId);if (store.taskByThread(bot.id, event.threadId)?.activity !== "dead") {store.setTaskActivity(bot.id, event.threadId, resourceOwner?.computerParkedOn !== undefined ? "parked.computer" : "idle");}directTurnBots.delete(event.threadId);- if (continueComputerSelection(event.threadId, generation, event.ok)) return;+ if (continueComputerSelection(event.threadId, generation, event.ok) || peerLimitResend.resend(event.threadId)) return;// An asynchronous screenshot finishes after the bus subscribers that normally drain have run.if (resumeQueued) {drainQueuedSends();@@ -7542,7 +7542,7 @@ async function beginTurn(onDispatchError?: (message: string) => void;compactOnly?: boolean;automaticRecoveryAttempted?: boolean;- automaticRecoveryIndex?: number;+ automaticRecoveryIndex?: number; peerLimitResent?: boolean; // already the one resend of a bot-to-bot turn on the backup AIonTurnSettled?: () => void;/** The turn's outcome, for a caller that runs it outside any coordinated work. */onSettled?: (outcome: HostTurnResult) => void;@@ -7743,7 +7743,7 @@ async function beginTurn(if (pendingSource) store.patchMessage(threadId, pendingSource, { requestPending: true });const settleOutcome = opts?.coordination?.settle ?? opts?.onSettled;if (settleOutcome) directCoordinationSettlers.set(dispatchClaimId, { nodeId: opts?.coordination?.id ?? dispatchClaimId, settle: settleOutcome });- directFollowupSettlers.set(dispatchClaimId, { threadId, settle: opts?.onTurnSettled });+ directFollowupSettlers.set(dispatchClaimId, { threadId, settle: opts?.onTurnSettled }); peerLimitResend.track({ generation: dispatchClaimId, botId: bot.id, threadId, text, opts: opts ?? {}, userMessage, latestUser: recoveryUserMessageId });directTurnDispatchClaims.set(threadId, { id: dispatchClaimId, botId, threadId, phase: "setup" }); liveTurns.dispatchStarted(threadId);directTurnBots.set(threadId, bot);beginInternalCapabilityGeneration(threadId, dispatchClaimId);diff --git a/server/peer-limit-resend.e2e.test.ts b/server/peer-limit-resend.e2e.test.tsnew file mode 100644index 0000000000..3a6c360191--- /dev/null+++ b/server/peer-limit-resend.e2e.test.ts@@ -0,0 +1,133 @@+// A teammate's hand-off whose AI meets its usage limit before doing anything goes once to the bot's backup AI.+import { spawn, type ChildProcess } from "node:child_process";+import { closeSync, existsSync, openSync, readFileSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { fileURLToPath } from "node:url";+import { expect, it } from "vitest";+import { launchVerificationServer, runControlOmb, verificationServerEnvironment } from "../scripts/control-omb.ts";+import { waitForExit } from "./testing/cleanup.ts";+import { readHandoffs } from "./testing/handoff-rows.ts";++const LIMIT = "You've hit your weekly limit · resets Oct 12 at 2:30pm (Asia/Calcutta)";+const BACKUP_REPLY = "done from fake codex";+/** The Chief settles once it has handed off; the hand-off itself (and any resend) finishes later. */+async function finishedHandoff(dataDir: string, botId: string) {+ await expect.poll(() => readHandoffs(dataDir).find((node) => node.botId === botId)?.status, { timeout: 60_000 })+ .toMatch(/^(completed|failed)$/);+ return readHandoffs(dataDir).find((node) => node.botId === botId)!;+}+const jsonLines = (path: string): any[] => existsSync(path)+ ? readFileSync(path, "utf8").split("\n").filter(Boolean).map((line) => JSON.parse(line)) : [];++/** A Chief on one Claude sign-in hands work to a specialist on another ("helper"), with Codex as the other AI. */+async function withHandoffFixture(helperPlan: Record<string, unknown>, check: (fixture: {+ api: (method: string, path: string, body?: unknown) => Promise<any>;+ control: (...args: string[]) => Promise<any>;+ dataDir: string; codexTurns: () => any[]; turns: () => any[]; chief: any; specialist: any; brief: string; evidence: unknown[];+}) => Promise<void>) {+ const fixture = await launchVerificationServer({}, undefined, undefined, undefined, undefined, { scripted: true }, ["codex"]);+ const { dataDir, url, logPath } = fixture.info;+ const codexDump = join(dataDir, "codex-dump.json");+ const planPath = join(dataDir, "room-plan.json");+ const evidence: unknown[] = [{ url }];+ let server: ChildProcess | undefined;+ const api = async (method: string, path: string, body?: unknown) => {+ const response = await fetch(url + path, {+ method, headers: { "content-type": "application/json", origin: url },+ ...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: AbortSignal.timeout(30_000),+ });+ const result: any = await response.json();+ expect(response.ok, `${method} ${path}: ${JSON.stringify(result)}`).toBe(true);+ return result;+ };+ const control = async (...args: string[]) => {+ const result = await runControlOmb([...args, "--url", url]) as any;+ evidence.push({ command: args, result });+ return result;+ };+ try {+ await waitForExit(fixture.child, { signal: "SIGTERM" });+ const configPath = join(dataDir, "config.json");+ const config = JSON.parse(readFileSync(configPath, "utf8"));+ config.instances.helper = { ...config.instances.claude, displayName: "Helper Claude" };+ config.instances.codex.environment = { FAKE_CODEX_DUMP: codexDump, FAKE_CODEX_DUMP_TURNS_ONLY: "1" };+ writeFileSync(configPath, JSON.stringify(config));+ const log = openSync(logPath, "a", 0o600);+ server = spawn(process.execPath, ["--experimental-strip-types", fileURLToPath(new URL("./index.ts", import.meta.url))], {+ cwd: fileURLToPath(new URL("..", import.meta.url)),+ env: verificationServerEnvironment({}, dataDir, Number(new URL(url).port)), stdio: ["ignore", log, log],+ });+ closeSync(log);+ await expect.poll(async () => {+ try { return (await fetch(url + "/api/health", { signal: AbortSignal.timeout(1_000) })).ok; } catch { return false; }+ }, { timeout: 30_000 }).toBe(true);+ 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);+ // The starter Chief would answer a failed run with a turn of its own; stepped down, only the turns under test run.+ const { bots } = await api("GET", "/api/bots") as { bots: Array<{ id: string; chiefOfStaff?: boolean }> };+ await api("PATCH", `/api/bots/${bots.find((bot) => bot.chiefOfStaff)!.id}`, { chiefOfStaff: false });+ const { bot: chief } = await control("new-bot", "--name", "Limit Chief", "--section", "Leadership");+ const { bot: specialist } = await control("new-bot", "--name", "Limit specialist", "--section", "Engineering");+ await api("PATCH", `/api/bots/${chief.id}`, { chiefOfStaff: true, managedSections: ["Engineering"], acknowledgePeerScope: true });+ const own = (await api("GET", "/api/bots")).bots.find((entry: any) => entry.id === specialist.id).modelSelection;+ await api("PATCH", `/api/bots/${specialist.id}/tasks/${specialist.activeTaskId}`, { modelSelection: { ...own, instanceId: "helper" }, updateBotDefault: true });+ const brief = "CHECK_THE_FIXTURE_REPORT_5Q";+ writeFileSync(planPath, JSON.stringify({+ [chief.id]: { turns: [+ { steps: [{ arguments: { bot_ids: [specialist.id], request_key: "limit-check", message: brief } }], reply: "Assigned the check" },+ { reply: "Chief read the specialist's answer" },+ ] },+ [specialist.id]: { turns: [{ expectContextIncludes: [brief], ...helperPlan }] },+ }));+ const codexTurns = () => {+ try { return (JSON.parse(readFileSync(codexDump, "utf8")).calls as any[]).filter((call) => call.method === "turn/start"); } catch { return []; }+ };+ await check({ api, control, dataDir, codexTurns, turns: () => jsonLines(`${planPath}.evidence.jsonl`), chief, specialist, brief, evidence });+ } finally {+ evidence.push({ nodes: readHandoffs(dataDir), turns: jsonLines(`${planPath}.evidence.jsonl`) });+ writeFileSync(`${logPath}.peer-limit-resend.json`, JSON.stringify(evidence, null, 2));+ await waitForExit(server, { signal: "SIGTERM" });+ await fixture.close();+ console.info(JSON.stringify({ logPath, fixtureRemoved: !existsSync(dataDir) }));+ }+}++it("resends a hand-off that met the usage limit before anything ran once to the backup AI, with the same sender", async () => {+ await withHandoffFixture({ failWith: LIMIT }, async ({ api, control, dataDir, codexTurns, turns, chief, specialist, brief, evidence }) => {+ await control("send", "--bot", chief.id, "--task", chief.activeTaskId, "--text", "Ask Engineering to check the fixture report.");+ const child = await finishedHandoff(dataDir, specialist.id);+ evidence.push({ child });+ // Once on the limited AI, then once on the backup, which answered the hand-off.+ expect(turns().filter((turn) => turn.botId === specialist.id)).toHaveLength(1);+ expect(codexTurns()).toHaveLength(1);+ expect(JSON.stringify(codexTurns()[0])).toContain(brief);+ expect(child).toMatchObject({ status: "completed", result: BACKUP_REPLY });+ const messages = (await api("GET", `/api/threads/${child.threadId}/messages?limit=100`)).messages as any[];+ evidence.push({ messages });+ // Still the Chief's hand-off: no line became the person's own, and it was handed over once.+ expect(messages.some((message) => message.role === "user")).toBe(false);+ expect(messages.filter((message) => message.roomRequest?.id === child.id && message.roomRequest.phase === "request")).toHaveLength(1);+ expect(messages.filter((message) => message.text === BACKUP_REPLY)).toHaveLength(1);+ await expect.poll(async () => (await api("GET", "/api/bots")).bots.find((bot: any) => bot.id === specialist.id)+ .tasks.find((task: any) => task.threadId === child.threadId).busy, { timeout: 30_000 }).toBe(false);+ const after = (await api("GET", "/api/bots")).bots.find((bot: any) => bot.id === specialist.id);+ expect(after.tasks.find((task: any) => task.threadId === child.threadId)).toMatchObject({ modelSelection: { instanceId: "codex" } });+ expect(after.modelSelection.instanceId).toBe("helper");+ await expect.poll(async () => ((await api("GET", `/api/threads/${chief.activeTaskId}/messages?limit=100`)).messages as any[])+ .filter((message) => message.roomRequest?.id === child.id && message.roomRequest.phase === "result").length, { timeout: 30_000 }).toBe(1);+ });+}, 180_000);++it("leaves a hand-off that already said something where it failed: nothing is sent again", async () => {+ await withHandoffFixture({ progressAfterGate: "Started reading the report", failWith: LIMIT }, async ({ api, control, dataDir, codexTurns, turns, chief, specialist }) => {+ await control("send", "--bot", chief.id, "--task", chief.activeTaskId, "--text", "Ask Engineering to check the fixture report.");+ const child = await finishedHandoff(dataDir, specialist.id);+ expect(turns().filter((turn) => turn.botId === specialist.id)).toHaveLength(1);+ expect(codexTurns()).toHaveLength(0);+ expect(child.status).toBe("failed");+ const after = (await api("GET", "/api/bots")).bots.find((bot: any) => bot.id === specialist.id);+ expect(after.tasks.find((task: any) => task.threadId === child.threadId).modelSelection?.instanceId ?? after.modelSelection.instanceId).toBe("helper");+ });+}, 180_000);diff --git a/server/quota-switch.ts b/server/quota-switch.tsindex 83d3ba55c2..fcb5933bed 100644--- a/server/quota-switch.ts+++ b/server/quota-switch.ts@@ -71,6 +71,13 @@ export const NOT_NOW = "Not now";const ENDED: ReadonlySet<string> = new Set(["completed", "failed", "cancelled"]);+/** Why a failed turn stopped, when it was its AI's usage limit or a sign-out. A tool call's failure names the tool,+ * never the engine's own limit, whatever its words. */+export function turnLimitScope(event: SettledTurn, flags: { limit?: TakeoverScope } | undefined, cause: string | undefined): TakeoverScope | undefined {+ return signedOutStop(event.stopReason, cause) ? "signed-out"+ : flags?.limit ?? (event.stopReason !== "tool_error" && classifyError({ text: cause ?? "" }).reason === "quota" ? "engine" : undefined);+}+/** 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 {@@ -201,10 +208,7 @@ export function createQuotaSwitch(deps: QuotaSwitchDeps): QuotaSwitch {// Read before any await: the record is this turn's only now.const request = deps.request(threadId);const flags = deps.turnStops.read?.(threadId, event.turnId)?.flags;- const cause = deps.turnStops.failureCause(event);- // A tool call's failure names the tool, never the engine's own limit, whatever its words.- const scope: TakeoverScope | undefined = signedOutStop(event.stopReason, cause) ? "signed-out"- : flags?.limit ?? (event.stopReason !== "tool_error" && classifyError({ text: cause ?? "" }).reason === "quota" ? "engine" : undefined);+ const scope = turnLimitScope(event, flags, deps.turnStops.failureCause(event));if (!scope) return null;const thread = store.projectBotForTask(bot.id, threadId) ?? bot;const from = thread.modelSelection;