Skip to content

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

Keep OpenCode Zen's free models running when the Go meter is full

Bugfixer 2d3de428c04f8
diff --git a/server/drivers/acp/opencode-go.ts b/server/drivers/acp/opencode-go.ts
index 8a9237ab8c..db15383400 100644
--- a/server/drivers/acp/opencode-go.ts
+++ b/server/drivers/acp/opencode-go.ts
@@ -13,6 +13,7 @@ import { OPENCODE_STANDALONE } from "./opencode-release.ts";
import { createAcpDriver, type AccountErrorCode, type AcpConfig, type AcpSupport } from "./core.ts";
import { offeredModels } from "./config-options.ts";
import { declareTypedOpenCodeModel } from "./opencode-typed-model.ts";
+import { OPENCODE_GO_MODEL_PREFIX } from "../../../shared/opencode-model-id.ts";
import {
declareLiveOpenCodeModels,
keepOpenCodeModelsFresh,
@@ -761,18 +762,14 @@ const ACCOUNT_ERROR_TEXT: ReadonlyArray<readonly [RegExp, AccountErrorCode]> = [
* refusal holds that login's free models and leaves the account available. */
const FREE_MODEL_LIMIT = /\bfree(?:UsageLimitError|\s+usage\s+limit)\b/iu;
-/** OpenCode Go's subscription models: its weekly or monthly allowance holds them all, never Zen's free models on the same
- * login, which have an allowance of their own. */
-const GO_PROVIDER = "opencode-go/";
-
/** How far a usage limit OpenCode reported reaches: one provider's shared free allowance (with the free models that
* allowance holds), the Go subscription's models, or the whole account. */
export function openCodeLimitFacts(text: string, model?: string, catalog?: ModelCatalog): { limit: "engine" | "model"; limitModels?: string[] } {
if (!FREE_MODEL_LIMIT.test(text)) {
- if (!model?.startsWith(GO_PROVIDER)) return { limit: "engine" };
+ if (!model?.startsWith(OPENCODE_GO_MODEL_PREFIX)) return { limit: "engine" };
const listed = [...lastSuccessfulCatalog.values(), ...(catalog ? [catalog] : [])].flatMap((known) => known.options.map((option) => option.id));
const paid = (catalog && catalogPrices.get(catalog)?.paid) ?? [];
- return { limit: "model", limitModels: [...new Set([model, ...paid, ...listed].filter((id) => id.startsWith(GO_PROVIDER)))] };
+ return { limit: "model", limitModels: [...new Set([model, ...paid, ...listed].filter((id) => id.startsWith(OPENCODE_GO_MODEL_PREFIX)))] };
}
const provider = model?.includes("/") ? model.slice(0, model.indexOf("/")) : "";
const offered = new Set(catalog?.options.map((option) => option.id));
diff --git a/server/host/limit-takeover.test.ts b/server/host/limit-takeover.test.ts
index 436067568b..ad61a4e609 100644
--- a/server/host/limit-takeover.test.ts
+++ b/server/host/limit-takeover.test.ts
@@ -7,6 +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 { 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");
@@ -62,6 +63,18 @@ function takeover(overrides: Partial<LimitTakeoverDeps> = {}, dir = freshDir())
}
describe("which AI carries on while one is limited", () => {
+ it("keeps a bot on OpenCode Zen's free models while only the Go subscription's meter is full", () => {
+ const openCode = engine("opencode", "opencode", ["opencode-go/kimi-k2", "opencode/big-pickle"]);
+ const clock = new LimitResetClock({ accounts: () => [{ id: "opencode", name: "OpenCode", driver: "opencode", environment: {} }], now: () => NOW });
+ clock.noteUsage({ fetchedAt: new Date(NOW).toISOString(), providers: [{ id: "opencode", name: "OpenCode", driver: "opencode", ok: true, error: null,
+ ...parseOpenCodeUsage({ usage: { rolling: { percent: 100, resetsAt: new Date(NOW + HOUR).toISOString() }, weekly: { percent: 50, resetsAt: new Date(NOW + 48 * HOUR).toISOString() } } }) }] });
+ const { instance } = takeover({ engines: () => [openCode, CLAUDE, CODEX], blockedUntil: (id, model) => clock.blockedUntil(id, model), resetAt: (id) => clock.resetAt(id) });
+ expect(instance.heldAtStart(KAI, on("opencode", "opencode/big-pickle")), "a free model has its own allowance").toBeNull();
+ expect(instance.heldAtStart(KAI, on("opencode", "opencode-go/kimi-k2"))).toEqual({ scope: "engine", resetsAt: NOW + HOUR });
+ const chosen = takeover({ engines: () => [openCode, CLAUDE, CODEX], blockedUntil: (id, model) => clock.blockedUntil(id, model), chosen: () => [on("opencode", "opencode/big-pickle")] }).instance;
+ expect(chosen.backups("kai", on("claude", "claude-opus-5-5"))[0], "a free model the person chose still carries on for another AI").toEqual(on("opencode", "opencode/big-pickle"));
+ });
+
it("never picks an AI that bills each use by itself, only as a backup the person chose", () => {
const apiClaude = engine("claude-api", "claudeAgent", ["claude-opus-5-5"], { access: "api" });
const keyedClaude = engine("claude-key", "claudeAgent", ["claude-opus-5-5"]);
diff --git a/server/host/limit-takeover.ts b/server/host/limit-takeover.ts
index d71b120dc7..e63c1328b5 100644
--- a/server/host/limit-takeover.ts
+++ b/server/host/limit-takeover.ts
@@ -51,7 +51,7 @@ export interface LimitTakeoverDeps {
configs(): InstanceConfigMap;
context: DefaultSelectionContext;
/** Until when this engine refuses work, or null. */
- blockedUntil(instanceId: string): number | null;
+ blockedUntil(instanceId: string, model?: string): number | null;
/** When this engine's limit resets, when that is known. */
resetAt?(instanceId: string): number | null;
/** The backups the person chose for this bot, or for every bot. */
@@ -162,7 +162,7 @@ export function createLimitTakeover(deps: LimitTakeoverDeps) {
const usable = (engines: TakeoverEngine[], current: TakeoverEngine, selection: ModelSelection, scope: TakeoverScope, approval?: ApprovalMode): boolean => {
const engine = engines.find((candidate) => candidate.instanceId === selection.instanceId);
- if (!engine || !readyToRun(engine, deps.context) || deps.blockedUntil(engine.instanceId) !== null || modelHeld(selection) !== null) return false;
+ if (!engine || !readyToRun(engine, deps.context) || deps.blockedUntil(engine.instanceId, selection.model) !== null || modelHeld(selection) !== null) return false;
if (engine.instanceId !== current.instanceId) {
if (signedOutHeld(engine.instanceId)) return false;
// Another sign-in to the same plan never carries a limit (that rotates accounts); it may stand in for one signed out.
@@ -253,7 +253,7 @@ export function createLimitTakeover(deps: LimitTakeoverDeps) {
* with no refused turn first. Null when nothing holds it, or when nothing could carry on and the AI is tried as
* usual. `recovering`: Automatic recovery has backups of its own for a limit. */
heldAtStart(bot: ThreadBot, selection: ModelSelection, recovering = false): { scope: TakeoverScope; resetsAt?: number } | null {
- const engineUntil = deps.blockedUntil(selection.instanceId);
+ const engineUntil = deps.blockedUntil(selection.instanceId, selection.model);
const model = engineUntil === null ? modelHeld(selection) : null;
const scope: TakeoverScope | null = engineUntil !== null ? "engine" : model ? model.scope : signedOutHeld(selection.instanceId) ? "signed-out" : null;
if (!scope) return null;
diff --git a/server/index.ts b/server/index.ts
index 4f50331c10..b28a9e58c0 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -8776,8 +8776,8 @@ 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) => 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); 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) => limitClock.blockedUntil(engine), signedOut: (engine) => limitTakeover.stillSignedOut(engine), engineName,
+ 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) => 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); 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 } : {}) } }),
switchBack: ({ botId, threadId, from, to }) => {
diff --git a/server/limit-failover.ts b/server/limit-failover.ts
index 191a274286..2fc956e8e4 100644
--- a/server/limit-failover.ts
+++ b/server/limit-failover.ts
@@ -73,7 +73,7 @@ export interface LimitFailoverDeps {
file: string;
now?: () => number;
/** Until when this engine refuses work; null when it should be working. */
- blockedUntil: (engine: string) => number | null;
+ blockedUntil: (engine: string, model?: string) => number | null;
/** This engine refused a turn because it is signed out, and has not been signed in again since. */
signedOut?: (engine: string) => boolean;
/** The thread's model now, or null when the thread is gone. */
@@ -125,7 +125,7 @@ export class LimitFailovers {
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) !== null) return false;
+ if (waitUntil > now || this.deps.blockedUntil(row.from.instanceId, row.from.model) !== null) 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.test.ts b/server/limit-resets.test.ts
index 41bcbf34e5..f7dcec962d 100644
--- a/server/limit-resets.test.ts
+++ b/server/limit-resets.test.ts
@@ -516,6 +516,27 @@ describe("LimitResetClock and the turns that follow a refusal", () => {
expect(instance.blockedUntil("opencodeGo")).toBeNull();
});
+ it("holds only OpenCode Go's own models at a full Go meter, so Zen's free models on the same login keep working", () => {
+ const goAccounts = [{ id: "opencodeGo", name: "OpenCode", driver: "opencode" as const, environment: {} }];
+ const instance = new LimitResetClock({ accounts: () => goAccounts, now: () => NOW });
+ instance.noteUsage(report(row("opencodeGo", "opencode", parseOpenCodeUsage({ usage: {
+ rolling: { percent: 100, resetsAt: iso(NOW + 4 * HOUR) },
+ weekly: { percent: 60, resetsAt: iso(NOW + 5 * 24 * HOUR) },
+ } }))));
+ expect(instance.blockedUntil("opencodeGo", "opencode-go/kimi-k2")).toBe(NOW + 4 * HOUR);
+ expect(instance.blockedUntil("opencodeGo", "typed::opencode-go/new-model"), "a Go model typed by hand").toBe(NOW + 4 * HOUR);
+ expect(instance.blockedUntil("opencodeGo"), "no model named: the whole engine, as before").toBe(NOW + 4 * HOUR);
+ expect(instance.blockedUntil("opencodeGo", "opencode/big-pickle")).toBeNull();
+ instance.noteRefusal("opencodeGo", NOW + 2 * HOUR);
+ expect(instance.blockedUntil("opencodeGo", "opencode/big-pickle"), "a refusal of the whole account still holds every model").not.toBeNull();
+ });
+
+ it("still holds every model of an engine other than OpenCode at a full window", () => {
+ const instance = new LimitResetClock({ accounts: () => accounts, now: () => NOW });
+ instance.noteUsage(report(claude([100, NOW + 2 * HOUR], [40, NOW + 3 * 24 * HOUR])));
+ expect(instance.blockedUntil("claude", "claude-sonnet-5")).toBe(NOW + 2 * HOUR);
+ });
+
it("ends a hold at once on Try again now, saved across a restart, and a new refusal holds it again", () => {
const dir = mkdtempSync(join(tmpdir(), "limit-release-"));
try {
diff --git a/server/limit-resets.ts b/server/limit-resets.ts
index c9bf08703e..3c552b5186 100644
--- a/server/limit-resets.ts
+++ b/server/limit-resets.ts
@@ -8,6 +8,7 @@ import { writeFileAtomic } from "./atomic.ts";
import { LIMIT_POLL_MS, limitReadDue } from "./limit-poll.ts";
import { claudeHasExtraUsageRoom, loadPlanUsage, type PlanAccount, type PlanProviderRow, type PlanUsageReport, type PlanWindow } from "./plan-usage.ts";
import type { RuntimeEvent } from "../shared/runtime-events.ts";
+import { OPENCODE_GO_MODEL_PREFIX, typedOpenCodeModel } from "../shared/opencode-model-id.ts";
export { LIMIT_POLL_MS };
/** A refusal's reset is kept a little past its time, so a run due right then still finds it. */
@@ -137,12 +138,14 @@ export class LimitResetClock {
return usage?.blocked && usage.resetsAt !== null && usage.resetsAt > refused ? usage.resetsAt : refused;
}
- /** Until when this engine refuses work, as far as is known; null when it should be working. */
- blockedUntil(engine: string): number | null {
+ /** Until when this engine refuses work, as far as is known; null when it should be working. With `model`, for that
+ * model: OpenCode's usage meter is the Go subscription's, so at its limit Zen's free models still run. */
+ blockedUntil(engine: string, model?: string): number | null {
const now = this.now();
const refused = this.refusal(engine);
const usage = this.reading(engine);
- const until = Math.max(refused ?? 0, usage?.blocked && usage.resetsAt !== null ? usage.resetsAt : 0);
+ const meterHolds = usage?.driver !== "opencode" || !model || (typedOpenCodeModel(model) ?? model).startsWith(OPENCODE_GO_MODEL_PREFIX);
+ const until = Math.max(refused ?? 0, meterHolds && usage?.blocked && usage.resetsAt !== null ? usage.resetsAt : 0);
return until > now ? until : null;
}
diff --git a/shared/opencode-model-id.ts b/shared/opencode-model-id.ts
index d12ec73bfa..547715d28e 100644
--- a/shared/opencode-model-id.ts
+++ b/shared/opencode-model-id.ts
@@ -29,3 +29,7 @@ export function openCodeRunsTypedModel(model: string, listed: ReadonlyArray<{ id
const provider = model.slice(0, model.indexOf("/") + 1);
return provider.length > 1 && listed.some((option) => option.id.startsWith(provider) && !option.id.startsWith(TYPED_PREFIX));
}
+
+/** OpenCode Go's subscription models: its usage meter and its weekly or monthly allowance hold them all, never Zen's free
+ * models on the same login, which have an allowance of their own. */
+export const OPENCODE_GO_MODEL_PREFIX = "opencode-go/";