Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(limits): a teammate's job its AI's limit refused carries on with another AI
Absterrg0baa56c2399a9
diff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex 5fdde594ea..47969dcf47 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -1140,7 +1140,10 @@ no AI to carry on, it says the bot waits instead. Nobody is asked.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 thatAI, in that conversation alone; the bot's own model and its other- conversations stay where they are. While the limit lasts, every new turn and+ conversations stay where they are. A teammate's job that met it (work handed+ on with `coordinate_bots`) runs again on that AI in the job's conversation,+ so the bot that asked gets its result, not a failure; the report says which+ AI did the work when it was not the teammate's own. While the limit lasts, every new turn andconversation of every bot that uses the limited AI (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.diff --git a/server/coordinator.ts b/server/coordinator.tsindex ccdb162e0d..c9741b6a79 100644--- a/server/coordinator.ts+++ b/server/coordinator.ts@@ -3,6 +3,7 @@ import type { WorkOrigin } from "./peer-provenance.ts";import type { LegacyThreadResolver } from "./runtime/import-legacy.ts";import type { Answerer, Assignment, EnvelopeNames, Level, Limits, Mode, Origin, Outcome, Owner, Reply, Requester, StatusView, TurnEvidence } from "./runtime/types.ts";import type { ModelSelection } from "../shared/wire.ts";+import type { TakeoverScope } from "./host/limit-takeover.ts";/** One coordinate_bots call, as the internal route hands it to the server. */export type CoordinateBotsCall = {@@ -98,6 +99,9 @@ export interface HostTurnResult {/** The host's stall watchdog stopped the turn, including a room turn a stall ended during setup, before it had an* outcome: it failed as `stalled`, not as a provider error. */stalled?: boolean;+ /** Its AI's usage limit or sign-out refused the turn, so another AI the person set up may carry its job on: which one,+ * and when the limit said it resets. */+ refusedBy?: { scope: TakeoverScope; resetsAt?: number };}export interface HandoffOpener {diff --git a/server/host/handoff-limits.test.ts b/server/host/handoff-limits.test.tsnew file mode 100644index 0000000000..1d4a61c821--- /dev/null+++ b/server/host/handoff-limits.test.ts@@ -0,0 +1,64 @@+import { describe, expect, it } from "vitest";++import type { ModelSelection } from "../../shared/wire.ts";+import type { HandoffView, HostTurnResult } from "../coordinator.ts";+import { createHandoffLimits } from "./handoff-limits.ts";++const claude: ModelSelection = { instanceId: "claude", model: "claude-opus" };++function world(options: { carries?: boolean; enabled?: boolean; ran?: ModelSelection } = {}) {+ const calls: string[] = [];+ const limits = createHandoffLimits({+ store: {+ projectBotForTask: () => ({ modelSelection: options.ran ?? claude }) as never,+ bot: () => ({ modelSelection: claude }) as never,+ },+ limitClock: { noteLimit: (engine, resetsAt) => { calls.push(`limit ${engine} ${resetsAt}`); } },+ takeover: {+ noteSignedOut: (engine) => { calls.push(`signed-out ${engine}`); },+ holdModel: (selection, scope, resetsAt) => { calls.push(`${scope} ${selection.model} ${resetsAt}`); },+ heldAtStart: () => (options.carries === false ? null : { scope: "engine" }),+ },+ enabled: () => options.enabled ?? true,+ engineName: (engine) => (engine === "codex" ? "Codex" : engine),+ });+ return { limits, calls };+}++const job = { botId: "lead", threadId: "lead-job", parentId: "chief-turn" } as HandoffView;+const refused = (refusedBy: HostTurnResult["refusedBy"], okToolCalls = 0): HostTurnResult =>+ ({ ok: false, text: "This Claude account has reached its usage limit", refusedBy, evidence: { okToolCalls, toolCalls: 1 } as never });++describe("a hand-off job its AI's limit refused", () => {+ it("holds the refusal and runs again with a note to carry on, with no no-progress strike", () => {+ const { limits, calls } = world();+ const carried = limits.carriedOn(job, refused({ scope: "engine", resetsAt: 9 }));+ expect(calls).toEqual(["limit claude 9"]);+ expect(carried?.cap?.note).toMatch(/another AI carries this request on now/);+ expect(carried?.evidence).not.toHaveProperty("okToolCalls");+ expect(limits.carriedOn(job, refused({ scope: "model" }, 2))?.evidence?.okToolCalls).toBe(2);+ expect(limits.carriedOn(job, refused({ scope: "signed-out" }))).toBeDefined();+ expect(calls.slice(1)).toEqual(["model claude-opus undefined", "signed-out claude"]);+ });++ it("fails as before when no AI can carry it on, when failover is off, or when it is not a teammate's own job", () => {+ const stuck = world({ carries: false });+ expect(stuck.limits.carriedOn(job, refused({ scope: "engine" }))).toBeUndefined();+ expect(stuck.calls).toEqual(["limit claude undefined"]);+ const off = world({ enabled: false });+ expect(off.limits.carriedOn(job, refused({ scope: "engine" }))).toBeUndefined();+ expect(off.limits.carriedOn({ ...job, groupId: "room" }, refused({ scope: "engine" }))).toBeUndefined();+ const { limits, calls } = world();+ expect(limits.carriedOn({ ...job, parentId: undefined }, refused({ scope: "engine" }))).toBeUndefined();+ expect(limits.carriedOn(job, { ok: false, text: "crashed" })).toBeUndefined();+ expect([...off.calls, ...calls]).toEqual([]);+ });+});++describe("the AI a job ran on", () => {+ it("is named only when it is not the teammate's own", () => {+ expect(world().limits.servedBy(job)).toEqual({});+ expect(world({ ran: { instanceId: "codex", model: "gpt-5" } }).limits.servedBy(job)).toEqual({ servedBy: "Codex gpt-5" });+ expect(world({ ran: { ...claude, model: "claude-sonnet" } }).limits.servedBy(job)).toEqual({ servedBy: "claude claude-sonnet" });+ });+});diff --git a/server/host/handoff-limits.ts b/server/host/handoff-limits.tsnew file mode 100644index 0000000000..0115c362f1--- /dev/null+++ b/server/host/handoff-limits.ts@@ -0,0 +1,47 @@+import type { ModelSelection } from "../../shared/wire.ts";+import type { HandoffView, HostTurnResult } from "../coordinator.ts";+import type { LimitResetClock } from "../limit-resets.ts";+import type { Store } from "../store.ts";+import type { LimitTakeover } from "./limit-takeover.ts";++const LIMIT_CARRIED_NOTE = "Your previous turn stopped because its AI reached its usage limit or was signed out, and another AI carries this request on now; continue from where it stopped.";++type Refusal = NonNullable<HostTurnResult["refusedBy"]>;++export interface HandoffLimitsDeps {+ store: Pick<Store, "projectBotForTask" | "bot">;+ limitClock: Pick<LimitResetClock, "noteLimit">;+ takeover: Pick<LimitTakeover, "noteSignedOut" | "holdModel" | "heldAtStart">;+ /** OMB_QUOTA_SWITCH: off, nothing carries on by itself. */+ enabled(): boolean;+ engineName(instanceId: string): string;+}++export function createHandoffLimits(deps: HandoffLimitsDeps) {+ /** A refusal recorded as one at a turn's start is: every turn of that AI while it holds, this job's next run included,+ * starts on an AI that can carry it on. */+ const hold = (selection: ModelSelection, refusal: Refusal): void => {+ if (refusal.scope === "signed-out") deps.takeover.noteSignedOut(selection.instanceId);+ else if (refusal.scope === "engine") deps.limitClock.noteLimit(selection.instanceId, refusal.resetsAt);+ else deps.takeover.holdModel(selection, refusal.scope, refusal.resetsAt);+ };++ return {+ /** The AI a job's conversation ran on, for its evidence, when it is not its bot's own. */+ servedBy(node: HandoffView): { servedBy?: string } {+ const ran = deps.store.projectBotForTask(node.botId, node.threadId)?.modelSelection, own = deps.store.bot(node.botId)?.modelSelection;+ return ran && own && (ran.instanceId !== own.instanceId || ran.model !== own.model) ? { servedBy: `${deps.engineName(ran.instanceId)} ${ran.model}` } : {};+ },+ /** A hand-off job its AI's usage limit or sign-out refused runs again while another AI can carry it on: its next+ * turn's start moves its conversation alone there, as for any turn of that AI. Undefined for any other outcome. */+ carriedOn(node: HandoffView, result: HostTurnResult): HostTurnResult | undefined {+ const refusal = result.refusedBy, thread = deps.store.projectBotForTask(node.botId, node.threadId);+ if (result.ok || !refusal || !node.parentId || node.groupId || !thread || !deps.enabled()) return undefined;+ hold(thread.modelSelection, refusal);+ if (deps.takeover.heldAtStart(thread, thread.modelSelection) === null) return undefined;+ // A refusal is not the job stalling: no tool call that worked is progress-unknown, never a no-progress strike.+ const { okToolCalls, ...rest } = result.evidence ?? {};+ return { ...result, evidence: okToolCalls ? { ...rest, okToolCalls } : rest, cap: { note: LIMIT_CARRIED_NOTE } };+ },+ };+}diff --git a/server/host/limit-takeover.ts b/server/host/limit-takeover.tsindex d71b120dc7..34080c6f15 100644--- a/server/host/limit-takeover.ts+++ b/server/host/limit-takeover.ts@@ -83,6 +83,20 @@ interface SavedHolds { models?: Record<string, ModelHold>; signedOut?: Record<stexport function signedOutStop(stopReason: string | null | undefined, said: string | undefined): boolean {return stopReason === "auth_required" && !(said && (engineFailureKind(said) === "credits" || classifyError({ text: said }).reason === "quota"));}+/** What refused a turn another AI may carry on: its AI's usage limit (`limit`, when the engine said which one) or its+ * sign-out; undefined for any other failure. A tool call's failure names the tool, never the engine's own limit,+ * whatever its words. */+export function takeoverRefusal(stopReason: string | null | undefined, said: string | undefined, limit: LimitScope | undefined): TakeoverScope | undefined {+ if (signedOutStop(stopReason, said)) return "signed-out";+ return limit ?? (stopReason !== "tool_error" && classifyError({ text: said ?? "" }).reason === "quota" ? "engine" : undefined);+}+/** That refusal as a job's outcome carries it: which one, and when the limit said it resets. */+export function turnRefusal(stopReason: string | null | undefined, said: string | undefined,+ flags: { limit?: LimitScope; limitResetsAt?: number } | undefined): { scope: TakeoverScope; resetsAt?: number } | undefined {+ const scope = takeoverRefusal(stopReason, said, flags?.limit);+ const resetsAt = scope === "signed-out" ? undefined : flags?.limitResetsAt;+ return scope ? { scope, ...(resetsAt ? { resetsAt } : {}) } : undefined;+}/** A row a conversation shows when its turn carried on elsewhere: `setup` marks the one signing in fixes. */export interface CarriedOnRow extends ServerToolText { name: string; ok: boolean; setup?: boolean }diff --git a/server/index.ts b/server/index.tsindex 6f5d35afc4..a958f26fb8 100644--- a/server/index.ts+++ b/server/index.ts@@ -214,7 +214,7 @@ 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 { 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 { createMcpServersHost } from "./host/mcp-servers-host.ts"; import { createMcpKeys } from "./vault/mcp-keys.ts"; import { createLimitTakeover, signedOutStop, turnRefusal } from "./host/limit-takeover.ts"; import { createHandoffLimits } from "./host/handoff-limits.ts";import {isRemoteMcpServer,parseStoredMcpServer,@@ -1994,7 +1994,7 @@ function hostTurnResult(node: HandoffView | undefined, generation: string, outcoconst seat = computerParks.get(generation);computerParks.delete(generation);if (!node) return outcome;- const result: DirectTurnOutcome = { ...outcome, evidence: { ...outcome.evidence, ...turnEvidence(turnRows(node)) } };+ const result: DirectTurnOutcome = { ...outcome, evidence: { ...outcome.evidence, ...turnEvidence(turnRows(node)), ...handoffLimits.servedBy(node) } };if (outcome.ok && !node.groupId) signInSettle.verified(node.botId, node.threadId, node.startedAt ?? node.createdAt);const cards = resumableCards(node.threadId, node.startedAt ?? node.createdAt, node.groupId ? node.botId : undefined).filter((card) => !coordinator.active().some((other) => other.id !== node.id && other.threadId === node.threadId && other.status === "waiting" && other.cards?.includes(card.id)));if (result.stalled) stopCards(node.threadId, new Set(cards.map((card) => card.id)));@@ -2005,7 +2005,7 @@ function hostTurnResult(node: HandoffView | undefined, generation: string, outcoconst { okToolCalls: _unknown, ...evidence } = result.evidence ?? {};return { ...result, evidence, cap: { note: COMPUTER_FREE_NOTE } };}- if (result.cap || result.stalled || !cards.length) return result;+ const carried = handoffLimits.carriedOn(node, result); if (carried) return carried; if (result.cap || result.stalled || !cards.length) return result;parkedNodesToReconcile.add(node.id);return { ...result, cards: { question: `Waiting on the person: ${cards.map((card) => card.waits).join("; ")}`, ids: cards.map((card) => card.id) } };}@@ -5080,9 +5080,9 @@ bus.subscribe((event: RuntimeEvent) => {message.role === "bot" && message.kind === "text" && message.turnId === event.turnId)?.text : undefined;const text = event.ok ? reply || event.stopReason || "The bot finished without a text reply": stoppedTurnText(event.threadId, event.turnId, undefined, event.stopReason);- const handoffPath = event.ok ? undefined : turnStops.read(event.threadId, event.turnId)?.handoffPath;+ const stop = event.ok ? undefined : turnStops.read(event.threadId, event.turnId), handoffPath = stop?.handoffPath, refusedBy = event.ok ? undefined : turnRefusal(event.stopReason, turnStops.failureCause(event), stop?.flags);const outcome: DirectTurnOutcome = { ok: event.ok, text: unansweredApprovals.annotate(event.threadId, event.turnId, text.slice(0, 12_000), event.ok), ...approvalAsk(store.botByThread(event.threadId)?.id, event.threadId, event.turnId),- ...(handoffPath ? { cap: { note: STEP_CAP_NOTE, handoffPath } } : {}) };+ ...(handoffPath ? { cap: { note: STEP_CAP_NOTE, handoffPath } } : {}), ...(refusedBy ? { refusedBy } : {}) };const owner = directFollowupTurns.complete(event.threadId, event.turnId, outcome);if (owner) {settleDirectCoordination(owner.generation, outcome);@@ -8771,7 +8771,7 @@ const limitFailovers = new LimitFailovers({ file: join(DATA_DIR, "limit-failoverswitchBack: ({ botId, threadId, from, to }) => {const current = store.projectBotForTask(botId, threadId), checked = current ? checkedTaskModelSwitch(current, from, false, false, true) : null;return Boolean(checked?.ok && store.switchTaskModel(botId, threadId, checked.selection, false, false, { ...hostedModels?.resetTask(to, checked.selection), rewound: true }));- } });+ } }); const handoffLimits = createHandoffLimits({ store, limitClock, takeover: limitTakeover, enabled: quotaSwitchEnabled, engineName });const automationDestinations = createAutomationDestinations({ store, mainThread: botMainThread, runs: () => routines?.listRuns() ?? [],cloud: CLOUD_HOME ? { owner: CLOUD_OWNER_KEY!, opener: (id, routine) => (routine && teamRoutines.opener(routine)) || routineOpener(id), reportFromOthers: cloudReportFromOthers, opened: (threadId, person) => threadStarters.set(threadId, person), outside: (threadId) => outsideLineage.mark(threadId) } : null });const routineModelChecks: RoutineModelChecks = { check: (raw) => checkedModelSelection(raw), bot: (botId) => store.bot(botId), engineSwitchNeedsAsk };diff --git a/server/quota-switch.e2e.test.ts b/server/quota-switch.e2e.test.tsindex 4d51a12292..50880327c3 100644--- a/server/quota-switch.e2e.test.ts+++ b/server/quota-switch.e2e.test.ts@@ -18,13 +18,15 @@ 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>; otherSignInOnly?: boolean },+ options: { env?: Record<string, string>; otherSignInOnly?: boolean; roomPlan?: boolean },check: (fixture: {api: (method: string, path: string, body?: unknown) => Promise<any>;control: (...args: string[]) => Promise<any>;respond: (threadId: string, body: unknown) => Promise<{ status: number; body: any }>;backupPrompts: () => any[];dataDir: string;+ plan: Record<string, any>;+ evidence: () => any[];}) => Promise<void>,) {const port = await freePortBlock([0, 1]);@@ -35,6 +37,8 @@ async function withQuotaFixture(mkdirSync(evidenceDir, { recursive: true });const logPath = join(evidenceDir, `quota-switch-${Date.now()}-${process.pid}.log`);const backupFile = join(dataDir, "backup-prompts.jsonl");+ const planPath = join(dataDir, "room-plan.json");+ const plan: Record<string, any> = {};const engine = (displayName: string, environment: Record<string, string>) =>({ driver: "claudeAgent", displayName, config: { cli: FAKE_CLI }, environment });writeFileSync(join(dataDir, "config.json"), JSON.stringify({@@ -42,7 +46,7 @@ async function withQuotaFixture(claude: engine(LIMITED, { FAKE_CLAUDE_MODE: "usage-limit" }),...(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 } } }),+ : { codex: { driver: "codex", config: { cli: FAKE_CODEX }, environment: { FAKE_CODEX_DUMP: backupFile, ...(options.roomPlan ? { FAKE_CODEX_ROOM_PLAN: planPath } : {}) } } }),},}));const evidence: unknown[] = [{ url, options }];@@ -91,7 +95,9 @@ async function withQuotaFixture(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 });+ writeFileSync(planPath, "{}");+ const planned = new Proxy(plan, { set: (target, key, value) => { target[key as string] = value; writeFileSync(planPath, JSON.stringify(target)); return true; } });+ await check({ api, control, respond, backupPrompts: sent, dataDir, plan: planned, evidence: () => jsonLines(`${planPath}.evidence.jsonl`) });} finally {evidence.push({ backupPrompts: existsSync(backupFile) ? readFileSync(backupFile, "utf8").slice(0, 20_000) : null, roots: readHandoffs(dataDir) });const evidencePath = `${logPath}.quota-switch.json`;@@ -147,6 +153,41 @@ it("carries the request on with another AI by itself: the exact message once mor});}, 240_000);+it("carries a teammate's job on with another AI by itself: the job runs once more there and its result reaches the Chief, never a failure", async () => {+ await withQuotaFixture({ roomPlan: true }, async ({ api, control, dataDir, plan, evidence }) => {+ const chief = (await control("new-bot", "--name", "Clive", "--section", "Leadership")).bot;+ const lead = (await control("new-bot", "--name", "Out of quota", "--section", "Engineering")).bot;+ await api("PATCH", `/api/bots/${chief.id}`, { chiefOfStaff: true, managedSections: ["Engineering"], acknowledgePeerScope: true });+ const codex = (await api("GET", "/api/instances")).instances.find((instance: any) => instance.instanceId === "codex").models.default;+ await api("PATCH", `/api/bots/${chief.id}/tasks/${chief.activeTaskId}`, { modelSelection: { instanceId: "codex", model: codex }, updateBotDefault: true });+ const limited = (await api("GET", "/api/bots")).bots.find((entry: any) => entry.id === lead.id).modelSelection;+ await api("PATCH", `/api/bots/${lead.id}/tasks/${lead.activeTaskId}`, { modelSelection: { ...limited, instanceId: "claude" }, updateBotDefault: true });+ plan[lead.id] = { reply: "EXPORT_BUILT_7Q" };+ plan[chief.id] = { steps: [{ arguments: { bot_ids: [lead.id], message: "Build the CSV export BRIEF_4M" } }], reply: "Assigned", resumeReply: "Reviewed the export" };++ await control("send", "--bot", chief.id, "--task", chief.activeTaskId, "--text", "Have Engineering build the CSV export.");+ await expect.poll(() => readHandoffs(dataDir).find((node) => node.botId === lead.id)?.status, { timeout: 60_000 }).toBe("completed");+ expect((await control("wait", "--bot", chief.id, "--task", chief.activeTaskId, "--timeout", "60")).status).toBe("settled");++ const job = readHandoffs(dataDir).find((node) => node.botId === lead.id)!;+ expect(job.executions).toBe(2);+ const done = evidence().filter((turn) => turn.botId === lead.id);+ expect(done).toHaveLength(1);+ expect(JSON.stringify(done[0].prompt)).toContain("BRIEF_4M");+ const leadState = (await api("GET", "/api/bots")).bots.find((entry: any) => entry.id === lead.id);+ expect(leadState.tasks.find((task: any) => task.threadId === job.threadId).modelSelection.instanceId).toBe("codex");+ expect(leadState.modelSelection.instanceId).toBe("claude");++ const chiefLines = (await api("GET", `/api/threads/${chief.activeTaskId}/messages?limit=100`)).messages as any[];+ expect(chiefLines.filter((line) => line.tool?.name?.includes("failed"))).toEqual([]);+ const reviewed = evidence().filter((turn) => turn.botId === chief.id).map((turn) => JSON.stringify(turn.prompt)).join("\n");+ expect(reviewed).toContain("EXPORT_BUILT_7Q");+ expect(reviewed).toContain(`done by Codex ${codex}, not the assignee's own AI`);+ const notices = (await api("GET", "/api/notifications")).notifications.filter((entry: any) => entry.kind === "notice" && entry.botId === lead.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("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");diff --git a/server/quota-switch.ts b/server/quota-switch.tsindex 83d3ba55c2..212ff31fa8 100644--- a/server/quota-switch.ts+++ b/server/quota-switch.ts@@ -8,13 +8,12 @@ import { recoveryCapabilityError } from "./automatic-recovery.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";-import { classifyError } from "./drivers/retry.ts";import { PROBE_TIMEOUT_MS } from "./engine-install.ts";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 { takeoverRefusal, type LimitTakeover, type TakeoverScope } from "./host/limit-takeover.ts";export interface QuotaSwitchEngine {instanceId: string;@@ -202,9 +201,7 @@ export function createQuotaSwitch(deps: QuotaSwitchDeps): QuotaSwitch {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 = takeoverRefusal(event.stopReason, cause, flags?.limit);if (!scope) return null;const thread = store.projectBotForTask(bot.id, threadId) ?? bot;const from = thread.modelSelection;diff --git a/server/runtime/envelope.ts b/server/runtime/envelope.tsindex 377c51bf4d..48a90500e4 100644--- a/server/runtime/envelope.ts+++ b/server/runtime/envelope.ts@@ -165,6 +165,8 @@ function evidenceLine(evidence: TurnEvidence | undefined): string {const more = evidence.outward.length > FILES_SHOWN ? `, +${evidence.outward.length - FILES_SHOWN} more` : "";if (shown.length) parts.push(`outward actions done (${shown.join(", ")}${more})`);}+ const served = quote(evidence.servedBy, NAME_MAX);+ if (served) parts.push(`done by ${served}, not the assignee's own AI`);const summary = quote(evidence.summary, QUOTE_MAX);if (!parts.length && !summary) return "The harness observed nothing of this turn.";return `Observed by the harness: ${parts.join(", ")}${summary ? `${parts.length ? "; " : ""}${summary}` : ""}.`;diff --git a/server/runtime/store.ts b/server/runtime/store.tsindex 46cfae0e07..d7985bf3d8 100644--- a/server/runtime/store.ts+++ b/server/runtime/store.ts@@ -15,6 +15,7 @@ const evidenceSchema = z.object({okToolCalls: z.number().int().nonnegative().optional(),errors: z.array(z.string()).optional(),outward: z.array(z.string()).optional(),+ servedBy: z.string().optional(),});const assignmentSchema = z.object({diff --git a/server/runtime/types.ts b/server/runtime/types.tsindex d16088065b..3cdc4cd7a6 100644--- a/server/runtime/types.ts+++ b/server/runtime/types.ts@@ -173,6 +173,8 @@ export interface TurnEvidence {/** Outward actions this execution completed — sends, posts, publishes, commits, pushes, payments —* as short labels ("GMAIL_SEND_EMAIL", "git push", "COMPOSIO_PROXY_EXECUTE"). */outward?: string[];+ /** The AI that did this execution's work when it is not the assignee's own, as "<engine> <model>". */+ servedBy?: string;}export type EventKind =