Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Sign-outs: recognise an expired OAuth session, repeat the notice daily
Milind Sonie5a4e223f36b
diff --git a/server/drivers/claude-auth-recovery.ts b/server/drivers/claude-auth-recovery.tsindex 83e6b9bdd2..caa334a7f8 100644--- a/server/drivers/claude-auth-recovery.ts+++ b/server/drivers/claude-auth-recovery.ts@@ -9,10 +9,13 @@ type Frame = {type Refusal = { text: string; kind: "auth" | "limit"; said?: string; resetsAt?: number; scope?: "engine" | "model" | "credits" };type Pending = { refusal?: Refusal; refused?: boolean; buffered: RuntimeEvent[]; settle: (error?: Error) => void };+/** Claude's saved sign-in ran out and could not refresh, in the CLI's own words ("OAuth session expired"). */+export const claudeOAuthExpired = (text: string): boolean => /\boauth\b.{0,40}\b(?:expired|revoked)\b/i.test(text);+/** Only CLI-marked API errors count; assistant prose about signing out does not. */export function claudeAuthFailure(frame: { error?: unknown; is_api_error_message?: unknown }, text: string): boolean {if (frame.is_api_error_message !== true && typeof frame.error !== "string") return false;- return frame.error === "authentication_failed" || classifyError({ text }).reason === "auth";+ return frame.error === "authentication_failed" || classifyError({ text }).reason === "auth" || claudeOAuthExpired(text);}/** Claude Code 2.1.295 refuses a signed-out turn with an `authentication_failed` error, and a turn past its usage limitdiff --git a/server/drivers/claude-auth.test.ts b/server/drivers/claude-auth.test.tsindex 169db24300..6951e1b844 100644--- a/server/drivers/claude-auth.test.ts+++ b/server/drivers/claude-auth.test.ts@@ -53,6 +53,13 @@ describe("claudeAuthFailure", () => {expect(claudeAuthFailure({ error: "api_error" }, "401 unauthorized")).toBe(true);});+ it("reads an expired OAuth session in a CLI-marked frame, and a model's prose about one as prose", () => {+ expect(claudeAuthFailure({ is_api_error_message: true }, "OAuth session expired. Please sign in again.")).toBe(true);+ expect(claudeAuthFailure({ error: "api_error" }, "Your OAuth token has expired")).toBe(true);+ expect(claudeAuthFailure({ error: "api_error", is_api_error_message: true }, "The session could not be extended")).toBe(false);+ expect(claudeAuthFailure({}, "The OAuth session expired on the demo site.")).toBe(false);+ });+it("leaves a model's own words alone", () => {expect(claudeAuthFailure({}, LOGIN_TEXT)).toBe(false);expect(claudeAuthFailure({}, "You are not logged in to npm; run npm login.")).toBe(false);diff --git a/server/drivers/claude.test.ts b/server/drivers/claude.test.tsindex 4c3238a1d3..30f1ae1b5d 100644--- a/server/drivers/claude.test.ts+++ b/server/drivers/claude.test.ts@@ -655,6 +655,13 @@ describe("ClaudeDriver turns (fake CLI)", () => {}, { timeout: 7_000 }).toBe(true);});+ it("reads an error result saying the OAuth session expired as a sign-out", async () => {+ await create("oauth-expired-result");+ await instance.adapter.sendTurn({ threadId: "t-oauth", text: "hi" });+ expect(await recorder.until((e) => e.type === "turn.completed")).toMatchObject({ ok: false, stopReason: "auth_required" });+ expect(recorder.events.find((e: any) => e.type === "runtime.error")).toMatchObject({ message: "OAuth session expired. Please sign in again.", setup: true });+ });+it("reports a synthetic sign-out refusal for recovery only after its process has stopped", async () => {const dump = join(scratch, "recover-signed-out-session.json");process.env.FAKE_CLAUDE_DUMP = dump;diff --git a/server/drivers/claude.ts b/server/drivers/claude.tsindex b808591eb5..1e782eb88c 100644--- a/server/drivers/claude.ts+++ b/server/drivers/claude.ts@@ -16,7 +16,7 @@ import { claudeAuthStatus } from "./claude-auth-status.ts";import { projectMcpServers } from "./claude-project-mcp.ts";import { botSettingsFor, withBotSettings } from "./claude-bot-settings.ts";import { claudeBilling, claudeCallUsage } from "./claude-billing.ts";-import { claudeAuthFailure, claudeAuthRecovery } from "./claude-auth-recovery.ts";+import { claudeAuthFailure, claudeAuthRecovery, claudeOAuthExpired } from "./claude-auth-recovery.ts";import { CLAUDE_MODEL_ID, STATIC_CLAUDE_MODELS, claudeModelExtras, endpointModelCatalog } from "./claude-model-extras.ts";import { claudeToolSearchSetting } from "./claude-tool-search.ts"; import { unusableBuiltIns } from "./claude-unusable-tools.ts"; import { EMAIL_READ_TOOL_NAMES } from "../../shared/email.ts";import { claudeElicitations } from "./claude-elicitation.ts";@@ -1598,8 +1598,8 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {if (o.is_error === true && !session.turn?.authFailed && (session.turn?.limit ||o.api_error === "usage_limit_reached" || USAGE_LIMIT.test(String(o.result ?? "")))) reachLimit(o, o.result);if (o.is_error === true && session.turn && !session.turn.settled && !session.turn.explained && !session.turn.stopRequested) {- session.turn.explained = true;- emit({ ...base(threadId, currentTurnId()), type: "runtime.error", message: claudeResultError(o) });+ session.turn.explained = true; session.turn.authFailed = claudeOAuthExpired(String(o.result ?? ""));+ emit({ ...base(threadId, currentTurnId()), type: "runtime.error", message: claudeResultError(o), ...(session.turn.authFailed ? { setup: true } : {}) });}if (!config.managed) void orgBlocks.refresh();// result.usage is per turn "in streaming-input sessions" (2.1.282) even on a retaineddiff --git a/server/host/limit-takeover.test.ts b/server/host/limit-takeover.test.tsindex 69c3b886b9..436067568b 100644--- a/server/host/limit-takeover.test.ts+++ b/server/host/limit-takeover.test.ts@@ -1,4 +1,4 @@-import { mkdtempSync, rmSync } from "node:fs";+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, describe, expect, it, vi } from "vitest";@@ -7,7 +7,7 @@ import type { RuntimeEvent } from "../../shared/runtime-events.ts";import type { ModelSelection } from "../../shared/wire.ts";import type { InstanceConfigMap } from "../contracts.ts";import { LimitResetClock, UNNAMED_LIMIT_MS } from "../limit-resets.ts";-import { MODEL_HOLD_MS, SIGNED_OUT_RECHECK_MS, createLimitTakeover, signedOutStop, type LimitTakeoverDeps, type TakeoverEngine } from "./limit-takeover.ts";+import { MODEL_HOLD_MS, SIGNED_OUT_RECHECK_MS, SIGNED_OUT_REPEAT_MS, createLimitTakeover, signedOutStop, type LimitTakeoverDeps, type TakeoverEngine } from "./limit-takeover.ts";const NOW = Date.parse("2026-10-27T10:00:00Z");const HOUR = 3_600_000;@@ -279,6 +279,55 @@ describe("a new conversation once an AI is known to be at its limit", () => {});});+describe("a sign-out that goes on", () => {+ const CLAUDE_ON = on("claude", "claude-opus-5-5");+ const ROSA = { id: "rosa", name: "Rosa" };++ it("says it again once a day across all bots, however often turns are refused in between, until it is signed in", () => {+ const { instance, told, now } = takeover({ where: "on the Cloud" });+ expect(instance.tell(KAI, CLAUDE_ON, { scope: "signed-out" })).not.toBeNull();+ for (let turn = 0; turn < 8; turn += 1) {+ now.at += 2 * HOUR;+ expect(instance.tell(KAI, CLAUDE_ON, { scope: "signed-out" })).toBeNull();+ }+ expect(told).toHaveLength(1);+ now.at += SIGNED_OUT_REPEAT_MS - 16 * HOUR + 1;+ expect(instance.tell(KAI, CLAUDE_ON, { scope: "signed-out" }), "a day after it was last said").not.toBeNull();+ expect(instance.tell(KAI, CLAUDE_ON, { scope: "signed-out" })).toBeNull();+ expect(instance.tell(ROSA, CLAUDE_ON, { scope: "signed-out" }), "another bot's first time is still its own").not.toBeNull();+ now.at += SIGNED_OUT_REPEAT_MS + 1;+ expect(instance.tell(KAI, CLAUDE_ON, { scope: "signed-out" })).not.toBeNull();+ expect(instance.tell(ROSA, CLAUDE_ON, { scope: "signed-out" }), "the day's one reminder went to Kai").toBeNull();+ instance.signedIn("claude");+ expect(told).toHaveLength(4);+ });++ it("speaks up when a bot had gone quiet under a long mark, and starts afresh after signing in", () => {+ const dir = freshDir();+ const before = takeover({}, dir);+ before.instance.noteSignedOut("claude");+ expect(before.instance.tell(KAI, CLAUDE_ON, { scope: "signed-out" })).not.toBeNull();+ expect(before.instance.tell(KAI, CLAUDE_ON, { scope: "signed-out" })).toBeNull();+ writeFileSync(join(dir, "limit-notices.json"), JSON.stringify({ [`kai\u0000signed-out\u0000claude`]: NOW + 29 * 24 * HOUR }));+ const after = takeover({}, dir);+ after.now.at = NOW + HOUR;+ expect(after.instance.tell(KAI, CLAUDE_ON, { scope: "signed-out" }), "once after the update, then on the schedule").not.toBeNull();+ expect(after.instance.tell(KAI, CLAUDE_ON, { scope: "signed-out" })).toBeNull();+ after.instance.noteSignedOut("claude");+ after.instance.signedIn("claude");+ after.instance.noteSignedOut("claude");+ expect(after.instance.tell(KAI, CLAUDE_ON, { scope: "signed-out" }), "a new sign-out is told at once").not.toBeNull();+ });++ it("names the bots with nothing to carry on for them, and leaves out those with a backup", () => {+ const mira = { id: "mira", name: "Mira", modelSelection: CLAUDE_ON };+ const lin = { id: "lin", name: "Lin", modelSelection: CLAUDE_ON };+ const { instance } = takeover({ where: "on the Cloud", botsOn: () => [mira, lin] as never, signedOutChosen: (botId) => botId === "lin" ? [on("codex", "gpt-6")] : [] });+ expect(instance.tell(KAI, CLAUDE_ON, { scope: "signed-out" }))+ .toBe("Claude is signed out on the Cloud. Sign in again in Settings → AI to keep using it. Until then Mira can't run: it has no backup.");+ });+});+describe("an AI that is signed out", () => {const event = (type: string, extra: Record<string, unknown> = {}) =>({ eventId: "e", provider: "claudeAgent", createdAt: new Date(NOW).toISOString(), threadId: "t1", type, ...extra }) as RuntimeEvent;diff --git a/server/host/limit-takeover.ts b/server/host/limit-takeover.tsindex 5988093f7d..d71b120dc7 100644--- a/server/host/limit-takeover.ts+++ b/server/host/limit-takeover.ts@@ -28,8 +28,11 @@ export const MODEL_HOLD_MS = 6 * 60 * 60_000;/** A signed-out AI is tried again by a new turn no sooner than this after its last refusal, in case it signed in again* some way this server did not see; a finished sign-in in the app, or a turn on it that works, ends the hold at once. */export const SIGNED_OUT_RECHECK_MS = UNNAMED_LIMIT_MS;-/** A sign-out's one notice stands until the AI is signed in again or works; past this it is said again. */+/** A sign-out's first notice to a bot stands until the AI is signed in again or works. */const SIGNED_OUT_STRETCH_MS = 30 * 24 * 60 * 60_000;+/** Refusals never end a sign-out's stretch, so the person is told again this often, once across all bots. */+export const SIGNED_OUT_REPEAT_MS = 24 * 60 * 60_000;+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" }@@ -68,6 +71,8 @@ export interface LimitTakeoverDeps {signedOutNow?(instanceId: string): boolean;/** A sign-out was first noticed: what the app shows of that AI's sign-in is read again. */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 }>;now?(): number;}@@ -199,14 +204,17 @@ export function createLimitTakeover(deps: LimitTakeoverDeps) {const refusedName = (from: ModelSelection, scope: TakeoverScope) => (scope === "model" || scope === "credits"? `${deps.engineName(from.instanceId)} ${from.model}` : deps.engineName(from.instanceId));- /** Once for this stretch of `from`'s limit or sign-out: which AI carries on for `bot` meanwhile, or that it waits.- * The words told, or null when this stretch was told already. */+ /** Once for this stretch of `from`'s limit or sign-out, and for a sign-out again every SIGNED_OUT_REPEAT_MS: which AI carries+ * on for `bot` meanwhile, or that it waits. The words told, or null when there is nothing to say now. */const tell = (bot: Bot, from: ModelSelection, facts: { resetsAt?: number; scope?: TakeoverScope; backup?: ModelSelection }): string | null => {const scope = facts.scope ?? "engine";const signOut = scope === "signed-out";- if (!notices.first(bot.id, limitedKey(from, scope), signOut ? now() + SIGNED_OUT_STRETCH_MS : facts.resetsAt)) return null;+ const first = notices.first(bot.id, limitedKey(from, scope), signOut ? now() + SIGNED_OUT_STRETCH_MS : facts.resetsAt);+ const scheduled = signOut && notices.due(EVERY_BOT, limitedKey(from, scope), SIGNED_OUT_REPEAT_MS);+ if (!first && !scheduled) return null;const backup = facts.backup ? { backup: label(facts.backup, from) } : {};- const text = signOut ? signedOutNoticeText({ engine: refusedName(from, scope), bot: bot.name, where: deps.where ?? "on this computer", ...backup })+ const stuck = signOut && !facts.backup ? (deps.botsOn?.(from.instanceId) ?? []).filter((one) => backups(one.id, one.modelSelection, "signed-out", approvalModeFor(one)).length === 0).map((one) => one.name) : [];+ const text = signOut ? signedOutNoticeText({ engine: refusedName(from, scope), bot: bot.name, where: deps.where ?? "on this computer", ...backup, ...(stuck.length ? { stuck } : {}) }): limitNoticeText({ engine: refusedName(from, scope), bot: bot.name, ...(facts.resetsAt ? { resetsAt: facts.resetsAt } : {}), ...(scope === "credits" ? { credits: true } : {}), ...backup });deps.tell(bot, text);return text;diff --git a/server/index.ts b/server/index.tsindex 2aee79bbd3..c3802b917b 100644--- a/server/index.ts+++ b/server/index.ts@@ -8776,7 +8776,7 @@ async function stopBotForEmergencyApprovalDowngrade(botId: string): Promise<voidconst engineName = (engine: string) => engineLabel(engine, registry.get(engine) ?? undefined);const limitClock = new LimitResetClock({ file: join(DATA_DIR, "limit-holds.json"), accounts: () => planAccountsFromInstances(instanceConfigs(cfg)), onChange: () => routines?.retimeLimitResets(),- waiting: () => Boolean(routines?.listRoutines().some((routine) => routine.enabled && routine.schedule.type === "limit_reset")) }); const limitTakeover = createLimitTakeover({ file: join(DATA_DIR, "limit-notices.json"), holdsFile: join(DATA_DIR, "limit-takeover-holds.json"), configs: () => instanceConfigs(cfg), context: selectionContext, blockedUntil: (engine) => limitClock.blockedUntil(engine), resetAt: (engine) => limitClock.resetAt(engine), enabled: () => quotaSwitchEnabled(), where: CLOUD_HOME ? "on the Cloud" : "on this computer", signedOutNow: (id) => registry.knownSnapshot(id)?.authenticated === false, signedOutNoticed: () => registry.forgetSnapshots(), engineName, engines: () => selectableInstances(registry.instances().map((engine) => ({ instanceId: engine.instanceId, driverKind: engine.driverKind, displayName: engine.displayName, enabled: engine.enabled, access: registry.access(engine.instanceId), models: engine.models, snapshot: registry.knownSnapshot(engine.instanceId) ?? { state: "unavailable" as const, reason: "not read yet" }, capabilities: engine.adapter.capabilities }))), chosen: (botId) => [...(store.bot(botId)?.fallback ?? []), ...(cfg.automaticRecovery?.backup ? [cfg.automaticRecovery.backup] : [])], signedOutChosen: (botId) => { const bot = store.bot(botId); return bot ? startupBackups(bot, cfg.automaticRecovery) : []; }, tell: (about, text) => notify(buildNoticeNotification(about, store.bot(about.id)?.threadId ?? "", text)), record: (failover) => limitFailovers.record(failover) }); registry.onSignedIn((instanceId) => limitTakeover.signedIn(instanceId));+ waiting: () => Boolean(routines?.listRoutines().some((routine) => routine.enabled && routine.schedule.type === "limit_reset")) }); const limitTakeover = createLimitTakeover({ file: join(DATA_DIR, "limit-notices.json"), holdsFile: join(DATA_DIR, "limit-takeover-holds.json"), configs: () => instanceConfigs(cfg), context: selectionContext, blockedUntil: (engine) => limitClock.blockedUntil(engine), resetAt: (engine) => limitClock.resetAt(engine), enabled: () => quotaSwitchEnabled(), where: CLOUD_HOME ? "on the Cloud" : "on this computer", signedOutNow: (id) => registry.knownSnapshot(id)?.authenticated === false, signedOutNoticed: () => registry.forgetSnapshots(), botsOn: (id) => store.bots.filter((bot) => !bot.hidden && bot.modelSelection.instanceId === id), engineName, engines: () => selectableInstances(registry.instances().map((engine) => ({ instanceId: engine.instanceId, driverKind: engine.driverKind, displayName: engine.displayName, enabled: engine.enabled, access: registry.access(engine.instanceId), models: engine.models, snapshot: registry.knownSnapshot(engine.instanceId) ?? { state: "unavailable" as const, reason: "not read yet" }, capabilities: engine.adapter.capabilities }))), chosen: (botId) => [...(store.bot(botId)?.fallback ?? []), ...(cfg.automaticRecovery?.backup ? [cfg.automaticRecovery.backup] : [])], signedOutChosen: (botId) => { const bot = store.bot(botId); return bot ? startupBackups(bot, cfg.automaticRecovery) : []; }, tell: (about, text) => notify(buildNoticeNotification(about, store.bot(about.id)?.threadId ?? "", text)), record: (failover) => limitFailovers.record(failover) }); registry.onSignedIn((instanceId) => limitTakeover.signedIn(instanceId));const limitFailovers = new LimitFailovers({ file: join(DATA_DIR, "limit-failovers.json"), blockedUntil: (engine) => limitClock.blockedUntil(engine), signedOut: (engine) => limitTakeover.stillSignedOut(engine), engineName,threadModel: (botId, threadId) => store.projectBotForTask(botId, threadId)?.modelSelection ?? null,note: (threadId, line, text) => store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: `recovery: ${line}`, ok: true, ...(text ? { nameCode: text.key, nameParams: text.params } : {}) } }),diff --git a/server/limit-notices.test.ts b/server/limit-notices.test.tsindex 3065833100..c8a9362f6e 100644--- a/server/limit-notices.test.ts+++ b/server/limit-notices.test.ts@@ -3,7 +3,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, describe, expect, it } from "vitest";-import { LimitNotices, UNNAMED_STRETCH_MS, limitNoticeText } from "./limit-notices.ts";+import { LimitNotices, UNNAMED_STRETCH_MS, limitNoticeText, signedOutNoticeText } from "./limit-notices.ts";import { UNNAMED_LIMIT_MS } from "./limit-resets.ts";const dirs: string[] = [];@@ -45,6 +45,33 @@ describe("one notice per bot for each stretch of a limit", () => {});describe("the notice", () => {+ it("says a scheduled line again only once its interval has passed, whatever was refused in between", () => {+ const now = { at: 1_000 };+ const ledger = notices(now).make();+ expect(ledger.due("every", "signed-out", 1_000)).toBe(true);+ expect(ledger.due("every", "signed-out", 1_000)).toBe(false);+ now.at += 999;+ expect(ledger.due("every", "signed-out", 1_000)).toBe(false);+ now.at += 1;+ expect(ledger.due("every", "signed-out", 1_000)).toBe(true);+ });++ it("does not let an older, longer mark silence a scheduled line", () => {+ const now = { at: 1_000 };+ const ledger = notices(now).make();+ expect(ledger.first("every", "signed-out", now.at + 30 * 24 * 60 * 60_000)).toBe(true);+ expect(ledger.due("every", "signed-out", 1_000), "a thirty-day mark is no schedule").toBe(true);+ expect(ledger.due("every", "signed-out", 1_000)).toBe(false);+ });++ it("names up to three bots a signed-out AI leaves stuck, and none when a backup carries on", () => {+ const base = { engine: "Claude", bot: "Kai", where: "on the Cloud" };+ expect(signedOutNoticeText({ ...base, stuck: ["Kai"] })).toBe("Claude is signed out on the Cloud. Sign in again in Settings → AI to keep using it. Until then Kai can't run: it has no backup.");+ expect(signedOutNoticeText({ ...base, stuck: ["Kai", "Rosa", "Lin", "Ada", "Bo"] })).toContain("Until then Kai, Rosa, Lin and 2 more can't run: they have no backup.");+ expect(signedOutNoticeText({ ...base, stuck: [] })).toBe("Claude is signed out on the Cloud. Sign in again in Settings → AI to keep using it.");+ expect(signedOutNoticeText({ ...base, backup: "Codex", stuck: ["Kai"] })).not.toContain("Until then");+ });+it("says in one line what carries on meanwhile, or that the bot waits", () => {const resetsAt = new Date(2026, 9, 27, 14, 0).getTime();expect(limitNoticeText({ engine: "Codex", bot: "Kai", resetsAt, backup: "Claude" }, "UTC").replace(/\d{1,2}:\d{2}\s?[AP]M/, "14:00"))diff --git a/server/limit-notices.ts b/server/limit-notices.tsindex 61fa1fa0aa..09777fcfac 100644--- a/server/limit-notices.ts+++ b/server/limit-notices.ts@@ -37,10 +37,11 @@ export function limitNoticeText(facts: LimitNoticeFacts, timeZone?: string): str/** "Claude is signed out on the Cloud. Sign in again in Settings → AI to keep using it.", and who carries on meanwhile* when a backup the person chose does. */-export function signedOutNoticeText(facts: { engine: string; bot: string; backup?: string; where: string }): string {- return facts.backup- ? `${facts.engine} is signed out ${facts.where}, so ${facts.bot} is using ${facts.backup} meanwhile. Sign in again in Settings → AI to keep using ${facts.engine}.`- : `${facts.engine} is signed out ${facts.where}. Sign in again in Settings → AI to keep using it.`;+export function signedOutNoticeText(facts: { engine: string; bot: string; backup?: string; where: string; stuck?: readonly string[] }): string {+ if (facts.backup) return `${facts.engine} is signed out ${facts.where}, so ${facts.bot} is using ${facts.backup} meanwhile. Sign in again in Settings → AI to keep using ${facts.engine}.`;+ const stuck = facts.stuck ?? [];+ const shown = stuck.slice(0, 3).join(", ") + (stuck.length > 3 ? ` and ${stuck.length - 3} more` : "");+ return `${facts.engine} is signed out ${facts.where}. Sign in again in Settings → AI to keep using it.${stuck.length ? ` Until then ${shown} can't run: ${stuck.length === 1 ? "it has" : "they have"} no backup.` : ""}`;}export class LimitNotices {@@ -72,6 +73,18 @@ export class LimitNotices {return !(known && known > now);}+ /** True when `everyMs` has passed since this was last said for `botId`, and then the clock restarts: a refusal in between+ * does not push the next telling back. A mark further out than `everyMs` was not left by this schedule, so it counts as told long ago. */+ due(botId: string, engine: string, everyMs: number): boolean {+ const key = `${botId}\u0000${engine}`, now = this.now();+ const next = this.told[key];+ if (next !== undefined && next > now && next - now <= everyMs) return false;+ this.told = Object.fromEntries(Object.entries(this.told).filter(([, end]) => end > now));+ this.told[key] = now + everyMs;+ this.save();+ return true;+ }+/** The engine works again for this bot: its next limit is a new stretch. */ended(botId: string, engine: string): void {const key = `${botId}\u0000${engine}`;diff --git a/server/testing/fake-claude-cli.ts b/server/testing/fake-claude-cli.tsindex 5b2ec50106..043d9b0ac6 100755--- a/server/testing/fake-claude-cli.ts+++ b/server/testing/fake-claude-cli.ts@@ -1005,6 +1005,13 @@ const playTurn = (prompt: JsonValue, late = false) => {process.stdout.write("this is not json\n{broken\n");}+ if (mode === "oauth-expired-result") {+ out({ type: "result", is_error: true, stop_reason: "stop_sequence", terminal_reason: "api_error", result: "OAuth session expired. Please sign in again.", total_cost_usd: runningCost.total });+ turnRunning = false;+ finishIfDone();+ return;+ }+// A signed-out CLI's frames, as Claude Code 2.1.296 sends them: only the frame's own error fields mark the failure.if (mode === "not-logged-in" || process.env.FAKE_CLAUDE_AUTH_AFTER_TURN === "1" && turnsPlayed > 0 || signedInAs === null) {if (process.env.FAKE_CLAUDE_AUTH_AFTER_WORK === "1") out({