Skip to content

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

fix(#4507): go back to Codex once credits appear, when only the usage meter had moved the conversation

Rino Cheng459153abe81a
diff --git a/server/host/limit-takeover.test.ts b/server/host/limit-takeover.test.ts
index f37f787212..b5bbbdf2e3 100644
--- a/server/host/limit-takeover.test.ts
+++ b/server/host/limit-takeover.test.ts
@@ -6,8 +6,9 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import type { RuntimeEvent } from "../../shared/runtime-events.ts";
import type { ModelSelection } from "../../shared/wire.ts";
import type { InstanceConfigMap } from "../contracts.ts";
+import { LimitFailovers } from "../limit-failover.ts";
import { LimitResetClock, UNNAMED_LIMIT_MS } from "../limit-resets.ts";
-import { parseOpenCodeUsage } from "../plan-usage.ts";
+import { parseCodexUsage, parseOpenCodeUsage } from "../plan-usage.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");
@@ -455,3 +456,42 @@ it("sends a signed-out AI's turns only to the backups a turn its AI never starte
startup = [on("codex", "gpt-6")];
expect(instance.heldAtStart(KAI, on("claude", "claude-opus-5-5"))).toEqual({ scope: "signed-out" });
});
+
+describe("a conversation moved off Codex while its window was full", () => {
+ const rolling = (credits?: unknown) => ({ fetchedAt: new Date(NOW).toISOString(), providers: [{ id: "codex", name: "Codex", driver: "codex", ok: true, error: null, ...parseCodexUsage({
+ rate_limit: { secondary_window: { used_percent: 100, limit_window_seconds: 7 * 86400, reset_at: Math.floor((NOW + 90 * HOUR) / 1000) } },
+ ...(credits ? { credits } : {}),
+ }) }] });
+
+ function moved(refused = false) {
+ const dir = freshDir();
+ const now = { at: NOW };
+ const clock = new LimitResetClock({ accounts: () => [{ id: "codex", name: "Codex", driver: "codex", environment: {} }], now: () => now.at });
+ clock.noteUsage(rolling());
+ if (refused) clock.noteLimit("codex", NOW + 2 * HOUR);
+ let current = on("claude", "claude-sonnet-5");
+ const failovers = new LimitFailovers({ file: join(dir, "limit-failovers.json"), now: () => now.at, blockedUntil: (id, model) => clock.blockedUntil(id, model),
+ threadModel: () => current, switchBack: (row) => { current = row.from; return true; }, note: () => {}, engineName: (id) => NAMES[id] ?? id });
+ const { instance } = takeover({ chosen: () => [on("claude", "claude-sonnet-5")], blockedUntil: (id, model) => clock.blockedUntil(id, model),
+ resetAt: (id, model) => clock.resetAt(id, model), meterOnly: (id, model) => clock.meterOnly(id, model), record: (row) => failovers.record(row), now: () => now.at }, dir);
+ const codexOn = on("codex", "gpt-6");
+ const held = instance.heldAtStart(KAI, codexOn);
+ expect(held).toMatchObject({ scope: "engine" });
+ instance.carriedOn(KAI, "t1", codexOn, on("claude", "claude-sonnet-5"), held!);
+ current = on("claude", "claude-sonnet-5");
+ return { clock, failovers, instance, now, codexOn, held: held! };
+ }
+
+ it("goes back at its next turn once credits appear, though the window is still full", () => {
+ const { clock, failovers } = moved();
+ expect(failovers.restore("kai", "t1"), "the meter still holds Codex").toBe(false);
+ clock.noteUsage(rolling({ has_credits: true, unlimited: false, balance: "12.50" }));
+ expect(failovers.restore("kai", "t1")).toBe(true);
+ });
+
+ it("stays on the backup after a refusal from Codex itself, credits or not", () => {
+ const { clock, failovers } = moved(true);
+ clock.noteUsage(rolling({ has_credits: true, unlimited: false, balance: "12.50" }));
+ expect(failovers.restore("kai", "t1")).toBe(false);
+ });
+});
diff --git a/server/host/limit-takeover.ts b/server/host/limit-takeover.ts
index 768a5700e0..05f9fcdaab 100644
--- a/server/host/limit-takeover.ts
+++ b/server/host/limit-takeover.ts
@@ -54,6 +54,8 @@ export interface LimitTakeoverDeps {
blockedUntil(instanceId: string, model?: string): number | null;
/** When this engine's limit resets, when that is known. */
resetAt?(instanceId: string, model?: string): number | null;
+ /** Only the usage meter holds this engine, with no refusal of its own. */
+ meterOnly?(instanceId: string, model?: string): boolean;
/** The backups the person chose for this bot, or for every bot. */
chosen(botId: string): ModelSelection[];
/** The backups a signed-out AI's turns go to, as for a turn its AI never started: the bot's own list, or the
@@ -217,7 +219,8 @@ export function createLimitTakeover(deps: LimitTakeoverDeps) {
/** A conversation of `botId` moved from `from` to `to` because `from` was limited or signed out; it goes back once
* that ends. */
const moved = (botId: string, threadId: string, from: ModelSelection, to: ModelSelection, resetsAt?: number, scope?: TakeoverScope): void => {
- deps.record({ botId, threadId, from, to, resetsAt: resetsAt ?? null, at: now(), ...(scope === "signed-out" ? { why: "signed-out" as const } : {}) });
+ deps.record({ botId, threadId, from, to, resetsAt: resetsAt ?? null, at: now(), ...(scope === "signed-out" ? { why: "signed-out" as const } : {}),
+ ...(scope === "engine" && deps.meterOnly?.(from.instanceId, from.model) ? { meter: true as const } : {}) });
};
/** A turn on `selection` worked for this bot: its engine's next limit is a new stretch, and it is plainly signed in. */
diff --git a/server/index.ts b/server/index.ts
index 63be620033..b70a05db5c 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -8734,7 +8734,7 @@ async function stopBotForEmergencyApprovalDowngrade(botId: string): Promise<void
const 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, model) => limitClock.blockedUntil(engine, model), resetAt: (engine, model) => limitClock.resetAt(engine, model), 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); perf.noteFailover(failover.threadId, failover.why === "signed-out" ? "signed-out" : "limit"); } }); 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, model) => limitClock.blockedUntil(engine, model), resetAt: (engine, model) => limitClock.resetAt(engine, model), meterOnly: (engine, model) => limitClock.meterOnly(engine, model), 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); perf.noteFailover(failover.threadId, failover.why === "signed-out" ? "signed-out" : "limit"); } }); registry.onSignedIn((instanceId) => limitTakeover.signedIn(instanceId));
const limitFailovers = new LimitFailovers({ file: join(DATA_DIR, "limit-failovers.json"), blockedUntil: (engine, model) => limitClock.blockedUntil(engine, model), 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-failover.ts b/server/limit-failover.ts
index 2fc956e8e4..8b50ca3094 100644
--- a/server/limit-failover.ts
+++ b/server/limit-failover.ts
@@ -64,6 +64,8 @@ export interface LimitFailover {
at: number;
/** `from` was signed out, not limited: the conversation goes back once it is signed in again. */
why?: "signed-out";
+ /** Only the usage meter held `from`, not a refusal: the conversation goes back once the meter no longer holds it. */
+ meter?: true;
}
/** With no reset time known, a conversation tries its own engine again no sooner than this. */
@@ -90,7 +92,7 @@ function load(file: string): LimitFailover[] {
const rows = JSON.parse(readFileSync(file, "utf8")) as unknown;
return Array.isArray(rows) ? rows.filter((row): row is LimitFailover => typeof row?.botId === "string" && typeof row?.threadId === "string" &&
typeof row?.from?.instanceId === "string" && typeof row?.to?.instanceId === "string" && (row.resetsAt === null || Number.isFinite(row.resetsAt)) &&
- Number.isFinite(row.at) && (row.why === undefined || row.why === "signed-out")) : [];
+ Number.isFinite(row.at) && (row.why === undefined || row.why === "signed-out") && (row.meter === undefined || row.meter === true)) : [];
} catch {
return [];
}
@@ -124,8 +126,9 @@ export class LimitFailovers {
const now = this.deps.now?.() ?? Date.now();
const current = this.deps.threadModel(botId, threadId);
if (!current || !sameModelSelection(current, row.to)) return this.forget(threadId);
- const waitUntil = row.why === "signed-out" ? row.at : row.resetsAt ?? row.at + UNKNOWN_RESET_WAIT_MS;
- if (waitUntil > now || this.deps.blockedUntil(row.from.instanceId, row.from.model) !== null) return false;
+ const blocked = this.deps.blockedUntil(row.from.instanceId, row.from.model) !== null;
+ const waitUntil = row.why === "signed-out" ? row.at : row.meter ? row.at : row.resetsAt ?? row.at + UNKNOWN_RESET_WAIT_MS;
+ if (waitUntil > now || blocked) return false;
if (row.why === "signed-out" && this.deps.signedOut?.(row.from.instanceId)) return false;
if (!this.deps.switchBack(row)) return false;
this.forget(threadId);
diff --git a/server/limit-resets.ts b/server/limit-resets.ts
index f5ec5b36ad..977bb037f1 100644
--- a/server/limit-resets.ts
+++ b/server/limit-resets.ts
@@ -37,8 +37,7 @@ export function engineLimitFromUsage(row: PlanProviderRow): EngineLimit | null {
const full = windows.filter((line) => line.used >= 100);
if (full.length) {
const latest = full.reduce((left, right) => (right.resetsAt ?? 0) > (left.resetsAt ?? 0) ? right : left);
- // Claude goes on past a full window on its paid extra usage while that has room, and Codex on its ChatGPT credits;
- // the engine's own refusal still holds it.
+ // A full window is the meter only: the engine's own refusal still holds it.
return { ...base, window: latest.window, usedPercent: 100, resetsAt: full.some((line) => line.resetsAt === null) ? null : latest.resetsAt, blocked: !claudeHasExtraUsageRoom(row) && !codexHasCreditRoom(row) };
}
const fullest = [...windows].sort((left, right) => right.used - left.used || (left.resetsAt ?? Infinity) - (right.resetsAt ?? Infinity))[0]!;
@@ -151,6 +150,11 @@ export class LimitResetClock {
/** The engine's usage reading when its meter covers `model` (every model when none is named): OpenCode's meter is
* the Go subscription's and never covers Zen's free models. */
+ /** Whether only the usage meter holds this engine now, with no refusal of its own. */
+ meterOnly(engine: string, model?: string): boolean {
+ return this.refusal(engine) === null && this.blockedUntil(engine, model) !== null;
+ }
+
private meterFor(engine: string, model?: string): EngineLimit | undefined {
const usage = this.reading(engine);
return usage?.driver !== "opencode" || !model || (typedOpenCodeModel(model) ?? model).startsWith(OPENCODE_GO_MODEL_PREFIX) ? usage : undefined;
diff --git a/server/plan-usage.ts b/server/plan-usage.ts
index 1cfe17a4cb..488722fe72 100644
--- a/server/plan-usage.ts
+++ b/server/plan-usage.ts
@@ -209,8 +209,8 @@ export function parseCodexUsage(body: unknown): PlanWindows {
return { ...assigned, extra, models, plan: planLabel(root?.plan_type ?? root?.plan), ...(codexHasCredits(root?.credits) ? { codexCredits: true as const } : {}) };
}
-/** The ChatGPT usage endpoint's `credits` object: `has_credits`, `unlimited` and a `balance` string. Anything else
- * reads as no credits, so a full window keeps holding. */
+/** The ChatGPT usage endpoint's `credits` object: `has_credits`, `unlimited` and `balance`. Anything else reads as
+ * no credits. */
function codexHasCredits(value: unknown): boolean {
const credits = asRecord(value);
if (!credits) return false;
@@ -220,7 +220,7 @@ function codexHasCredits(value: unknown): boolean {
return typeof balance === "number" && Number.isFinite(balance) && balance > 0;
}
-/** Whether Codex's ChatGPT credits are on and not used up: sends then go on past a full window and are paid from them. */
+/** A local signal that Codex's ChatGPT credits are on and not used up, so a full window does not stop a send here. */
export function codexHasCreditRoom(row: Pick<PlanProviderRow, "driver" | "codexCredits">): boolean {
return row.driver === "codex" && row.codexCredits === true;
}