Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Codex: fresh usage ends a waiting failover's reset too
erywim58a080607bd4
diff --git a/server/index.ts b/server/index.tsindex 2d5930c9d1..94ef50c862 100644--- a/server/index.ts+++ b/server/index.ts@@ -8644,7 +8644,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, model) => limitClock.blockedUntil(engine, model), resetAt: (engine, model) => limitClock.resetAt(engine, model), meterOnly: (engine, model) => limitClock.meterOnly(engine, model), holdScope: (engine, model) => limitClock.holdScope(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) => chosenBackups(store.bot(botId), cfg.automaticRecovery), 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"); } }); const signInResume = createSignInResumeHost({ dataDir: DATA_DIR, store, registry, takeover: limitTakeover, engineName, startTurn, replyTarget: resolveReplyTarget, startupRead: enginesRead, busy: (botId, threadId) => threadBusy(botId, threadId) || hasQueuedSteeredMessages(botId, threadId), atCapacity: (botId, threadId) => botAtThreadCapacity(botId, threadId) });+ waiting: () => Boolean(routines?.listRoutines().some((routine) => routine.enabled && routine.schedule.type === "limit_reset")), onHoldReleased: (engine, heldUntil) => { if (registry.get(engine)?.driverKind === "codex") limitFailovers.recoverHold(engine, heldUntil); } }); 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), holdScope: (engine, model) => limitClock.holdScope(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) => chosenBackups(store.bot(botId), cfg.automaticRecovery), 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"); } }); const signInResume = createSignInResumeHost({ dataDir: DATA_DIR, store, registry, takeover: limitTakeover, engineName, startTurn, replyTarget: resolveReplyTarget, startupRead: enginesRead, busy: (botId, threadId) => threadBusy(botId, threadId) || hasQueuedSteeredMessages(botId, threadId), atCapacity: (botId, threadId) => botAtThreadCapacity(botId, threadId) });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.test.ts b/server/limit-failover.test.tsindex 71d12044c5..9e88b56638 100644--- a/server/limit-failover.test.ts+++ b/server/limit-failover.test.ts@@ -123,4 +123,32 @@ describe("LimitFailovers", () => {f.failovers.record({ botId: "scout", threadId: "t", from: to, to: { instanceId: "grok", model: "grok-5" }, resetsAt: NOW + 2 * HOUR, at: NOW });expect(f.failovers.list()).toEqual([expect.objectContaining({ from, to: { instanceId: "grok", model: "grok-5" } })]);});++ it("goes back at the next turn when fresh usage released the reset it was waiting on", () => {+ const limited = { instanceId: "codex", model: "gpt-fake-default" };+ const f = fixture();+ f.failovers.record({ botId: "scout", threadId: "t", from: limited, to, resetsAt: NOW + 23 * HOUR, at: NOW });+ expect(f.failovers.restore("scout", "t")).toBe(false);+ f.at(NOW + HOUR);+ expect(f.failovers.recoverHold("codex", NOW + 23 * HOUR + 30_000)).toBe(1);+ expect(f.failovers.restore("scout", "t")).toBe(true);+ expect(f.notes).toEqual(["codex's limit has reset, so this conversation is back on codex."]);+ expect(new LimitFailovers(f.deps).list()).toEqual([]);+ });++ it("leaves another engine's, another reset's, a signed-out and a meter-only failover alone", () => {+ const limited = { instanceId: "codex", model: "gpt-fake-default" };+ const f = fixture();+ f.failovers.record({ botId: "a", threadId: "a", from: limited, to, resetsAt: NOW + 23 * HOUR, at: NOW });+ f.failovers.record({ botId: "b", threadId: "b", from: limited, to, resetsAt: NOW + 2 * HOUR, at: NOW });+ f.failovers.record({ botId: "c", threadId: "c", from: limited, to, resetsAt: null, at: NOW, why: "signed-out" });+ f.failovers.record({ botId: "d", threadId: "d", from: limited, to, resetsAt: NOW + 23 * HOUR, at: NOW, meter: true });+ expect(f.failovers.recoverHold("grok", NOW + 23 * HOUR)).toBe(0);+ expect(f.failovers.recoverHold("codex", NOW + 9 * HOUR)).toBe(0);+ f.at(NOW + HOUR);+ expect(f.failovers.recoverHold("codex", NOW + 23 * HOUR)).toBe(1);+ expect(f.failovers.list().find((row) => row.threadId === "b")?.resetsAt).toBe(NOW + 2 * HOUR);+ expect(f.failovers.list().find((row) => row.threadId === "c")?.resetsAt).toBeNull();+ expect(f.failovers.list().find((row) => row.threadId === "d")?.resetsAt).toBe(NOW + 23 * HOUR);+ });});diff --git a/server/limit-failover.ts b/server/limit-failover.tsindex 8b50ca3094..5e120876c4 100644--- a/server/limit-failover.ts+++ b/server/limit-failover.ts@@ -70,6 +70,8 @@ export interface LimitFailover {/** With no reset time known, a conversation tries its own engine again no sooner than this. */const UNKNOWN_RESET_WAIT_MS = 60 * 60_000;+/** How far a failover's reset and the refusal that caused it can differ and still be the same hold. */+const HOLD_MATCH_MS = 60_000;export interface LimitFailoverDeps {file: string;@@ -136,6 +138,21 @@ export class LimitFailovers {return true;}+ /** Fresh usage showed `engine`'s limit over before the reset it named: the conversations waiting on that same+ * reset go back at their next turn instead. Returns how many rows were shortened. */+ recoverHold(engine: string, heldUntil: number): number {+ const now = this.deps.now?.() ?? Date.now();+ let changed = 0;+ this.rows = this.rows.map((row) => {+ if (row.from.instanceId !== engine || row.why === "signed-out" || row.meter || row.resetsAt === null) return row;+ if (Math.abs(row.resetsAt - heldUntil) > HOLD_MATCH_MS) return row;+ changed++;+ return { ...row, resetsAt: now };+ });+ if (changed) this.save();+ return changed;+ }+forget(threadId: string): false {const kept = this.rows.filter((row) => row.threadId !== threadId);if (kept.length !== this.rows.length) {diff --git a/server/limit-resets.test.ts b/server/limit-resets.test.tsindex 3b7c68fac7..90c2ee714d 100644--- a/server/limit-resets.test.ts+++ b/server/limit-resets.test.ts@@ -725,4 +725,19 @@ describe("LimitResetClock and the turns that follow a refusal", () => {expect(instance.blockedUntil("claude")).toBeNull();expect(instance.report().engines).toEqual([]);});++ it("tells the failovers when fresh usage ends a Codex refusal before its reset", () => {+ const codexAccounts = [{ id: "codex", name: "Codex", driver: "codex" as const, environment: {} }];+ const released: Array<[string, number]> = [];+ const instance = new LimitResetClock({ accounts: () => codexAccounts, now: () => NOW, onHoldReleased: (engine, heldUntil) => released.push([engine, heldUntil]) });+ instance.noteRefusal("codex", NOW + 23 * HOUR);+ instance.noteUsage(report(codex([99, NOW + 2 * HOUR], [99, NOW + 23 * HOUR + 30_000])));+ expect(released, "usage still showing the window that refused keeps the hold").toEqual([]);+ instance.noteUsage({ fetchedAt: iso(NOW - 30_000), providers: [codex([3, NOW + 4 * HOUR], [8, NOW + 5 * 24 * HOUR])] });+ expect(released, "a read from before the refusal says nothing").toEqual([]);+ instance.noteUsage(report(codex([3, NOW + 4 * HOUR], [8, NOW + 5 * 24 * HOUR])));+ expect(released).toEqual([["codex", NOW + 23 * HOUR]]);+ expect(instance.blockedUntil("codex")).toBeNull();+ instance.stop();+ });});diff --git a/server/limit-resets.ts b/server/limit-resets.tsindex 68fb0d09ff..9d3a6fd543 100644--- a/server/limit-resets.ts+++ b/server/limit-resets.ts@@ -91,6 +91,8 @@ export interface LimitClockOptions {waiting?: () => boolean;/** The known reset times changed. */onChange?: () => void;+ /** Fresh usage showed this engine's refusal is over before the reset it named. */+ onHoldReleased?: (engine: string, heldUntil: number) => void;now?: () => number;/** Where the refusals' holds are kept across restarts; none in tests that need no file. */file?: string;@@ -268,9 +270,11 @@ export class LimitResetClock {next.set(limit.engine, limit);this.readAt.set(limit.engine, this.now());if (meterHoldsEngine(row.driver) && fetchedAt >= (this.heldAt.get(limit.engine) ?? 0) && holdGone(row, limit, this.refusals.get(limit.engine), this.guessed.has(limit.engine))) {+ const heldUntil = this.refusals.get(limit.engine);this.refusals.delete(limit.engine);this.heldAt.delete(limit.engine);released = true;+ if (heldUntil !== undefined) this.options.onHoldReleased?.(limit.engine, heldUntil);}}if (released) this.saveHolds();