Skip to content

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

fix(opencode): scope usage-limit holds to the provider that hit them (#4878)

CI fixture645566fe8eae
diff --git a/docs/opencode-go.md b/docs/opencode-go.md
index 4838e69347..a8ad5bbe54 100644
--- a/docs/opencode-go.md
+++ b/docs/opencode-go.md
@@ -69,9 +69,11 @@ restarts, and logs how many tools each server left out.
Zen's free models have an allowance of their own, apart from any Go
subscription on the same login. A free model that reaches it ("Free usage
limit reached…") holds that login's free models, never the account: new turns
-can still run on its paid models, Go's included. A limit on the account's own
-allowance (a Go limit, or a monthly one) holds the whole account until its
-window resets, as with the other engines.
+can still run on its paid models, Go's included. A limit holds the provider it
+comes from — a Go limit holds the Go subscription's models, a limit on another
+provider's key holds that provider's models — and leaves the instance's other
+providers working until its window resets. Only a refusal that names no
+provider holds the whole account, as with the other engines.
The limit card and the plan panel read Go's rolling, weekly and monthly
windows from `opencode.ai/zen/go/v1/usage` with the key saved under Settings →
diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.ts
index 537cc28f73..fd5f96424d 100644
--- a/server/drivers/acp/core.ts
+++ b/server/drivers/acp/core.ts
@@ -241,7 +241,7 @@ export interface AcpSupport extends AcpDriverHooks {
classifyError?(error: unknown): ProviderErrorCode | undefined;
/** A session/prompt error saying the agent never reached its model; startup recovery then holds the ACK for it. */
promptUnreachedModel?(error: unknown): boolean;
- /** How far a usage limit the engine reports reaches: its whole account, or one allowance its models share (OpenCode's free models), with the models that allowance holds. */ limitFacts?(text: string, model?: string): { limit: "engine" | "model"; limitModels?: string[] };
+ /** How far a usage limit the engine reports reaches: its whole account, or one allowance its models share (OpenCode's free models, its Go subscription, one provider's key), with the models that allowance holds. */ limitFacts?(text: string, model?: string): { limit: "engine" | "model"; limitModels?: string[] };
/** Plain words for an account failure (bad key, no credit, a used-up
* quota, no subscription) in place of the provider's raw RPC text. */
describeAccountError?(code: AccountErrorCode, model?: string): string;
@@ -1381,7 +1381,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
...base(threadId, turnId), type: "runtime.error",
...acpRuntimeFailure(e, support.displayName, accountError ? { message: support.describeAccountError?.(code, cliTurn.model), text: support.accountErrorText?.(code) } : undefined),
...(needsAuth ? { setup: true } : {}), ...((e as any)?.acpPromptStall === true ? { stalled: true } : {}),
- ...((e as any)?.acpUsageLimit === true || (code === "quota_or_region_restriction" && LIMIT_WORDS.test(message)) ? modelControls.usageLimit((model) => support.limitFacts?.(message, model) ?? { limit: "engine" as const }) : {}), // waited out, or the engine gave up: another AI can carry on
+ ...((e as any)?.acpUsageLimit === true || (code === "quota_or_region_restriction" && LIMIT_WORDS.test(message)) ? modelControls.usageLimit((sessionModel) => support.limitFacts?.(message, (e as any)?.acpUsageLimitModel as string | undefined ?? sessionModel) ?? { limit: "engine" as const }) : {}), // waited out, or the engine gave up: another AI can carry on
});
// Never replay an accepted prompt (it may have run tools); evict before listeners start the next turn.
if ((e as any)?.acpSessionBroken === true && session.sessionId) brokenSessions.add(session.sessionId);
diff --git a/server/drivers/acp/opencode-go.test.ts b/server/drivers/acp/opencode-go.test.ts
index 76c8d258ab..013d14b0cd 100644
--- a/server/drivers/acp/opencode-go.test.ts
+++ b/server/drivers/acp/opencode-go.test.ts
@@ -487,6 +487,8 @@ describe("OpenCode catalog", () => {
['AI_APICallError: Free usage limit reached. Free models work in OpenCode (https://opencode.ai); subscribe to OpenCode Go to keep going: https://opencode.ai/go', "model"],
["Internal error: FreeUsageLimitError: free models are limited today", "model"],
['OpenCode reached a usage limit (“Free usage limit reached. Free models work in OpenCode”) and is waiting it out without replying, so this turn was stopped.', "model"],
+ // A limit that names no provider reaches the whole account; a Go refusal does too when no catalog lists its models
+ // (the Go-scoped reads are covered with a catalog below).
["Internal error: Monthly usage limit reached for this key", "engine"],
["Internal error: GoUsageLimitError: the Go allowance is used up", "engine"],
["GoUsageLimitError: usage limit reached", "engine"],
@@ -522,8 +524,34 @@ describe("OpenCode catalog", () => {
expect(facts.limitModels).toEqual(expect.arrayContaining(["opencode-go/minimax-m3", "opencode-go/glm-5.3"]));
expect(facts.limitModels).not.toContain("opencode/deepseek-v4.1-flash-free");
}
- expect(openCodeLimitFacts("OpenCode Go weekly usage limit reached", "opencode/big-pickle", catalog), "a limit met by another model still holds the account")
- .toEqual({ limit: "engine" });
+ // The refusal names Go even when the session's selected model says otherwise (a session-level fallback ran a Go
+ // model): the Go subscription's models are held, and Zen's keep working.
+ const misread = openCodeLimitFacts("OpenCode Go weekly usage limit reached", "opencode/big-pickle", catalog);
+ expect(misread).toEqual({ limit: "model", limitModels: expect.arrayContaining(["opencode-go/glm-5.3", "opencode-go/minimax-m3"]) });
+ expect(misread.limitModels).not.toContain("opencode/big-pickle");
+ // A Go refusal seen with no model selected still holds just the Go models the catalog lists.
+ expect(openCodeLimitFacts("Internal error: GoUsageLimitError: the Go allowance is used up", undefined, catalog))
+ .toEqual({ limit: "model", limitModels: ["opencode-go/glm-5.3", "opencode-go/minimax-m3"] });
+ });
+
+ // A usage limit on one provider's key holds that provider's models: Zen, OpenRouter and the other providers the
+ // instance serves share nothing with it.
+ it("holds a limit on one provider's key to that provider's models", () => {
+ const catalog = parseOpenCodeModelsOutput([
+ "opencode/big-pickle", JSON.stringify({ cost: { input: 1, output: 2 } }),
+ "openrouter/anthropic/claude-sonnet-5", JSON.stringify({ cost: { input: 1, output: 2 } }),
+ "openrouter/openai/gpt-6", JSON.stringify({ cost: { input: 1, output: 2 } }),
+ "opencode-go/minimax-m3", JSON.stringify({ cost: { input: 1, output: 2 } }),
+ "ollama_cloud/qwen3-coder", JSON.stringify({}),
+ ].join("\n"))!;
+ const facts = openCodeLimitFacts("Internal error: Monthly usage limit reached for this key", "openrouter/openai/gpt-6", catalog);
+ expect(facts.limit).toBe("model");
+ expect(facts.limitModels).toEqual(expect.arrayContaining(["openrouter/openai/gpt-6", "openrouter/anthropic/claude-sonnet-5"]));
+ expect(facts.limitModels).not.toContain("opencode/big-pickle");
+ expect(facts.limitModels).not.toContain("opencode-go/minimax-m3");
+ // A limit met on a model of an unknown provider still holds just that model, never the account.
+ expect(openCodeLimitFacts("Internal error: Monthly usage limit reached for this key", "unlisted/one-off", catalog))
+ .toEqual({ limit: "model", limitModels: ["unlisted/one-off"] });
});
it("classifies OpenCode 2's authentication refusal and leaves real internal errors alone", () => {
@@ -1029,7 +1057,8 @@ describe("OpenCode turns without a sign-in gate", () => {
try {
const { done, events } = await f.run("t-go-limit", "opencode/big-pickle");
expect(done).toMatchObject({ ok: false, stopReason: "quota" });
- expect(events.find((event) => event.type === "runtime.error")).toMatchObject({ limit: "engine", message: expect.stringMatching(/usage limit/i) });
+ // The failed call's log row names opencode-go/kimi-k3, so the hold is that provider's, not the account's.
+ expect(events.find((event) => event.type === "runtime.error")).toMatchObject({ limit: "model", message: expect.stringMatching(/usage limit/i) });
} finally {
vi.unstubAllEnvs();
vi.restoreAllMocks();
@@ -1058,14 +1087,14 @@ describe("OpenCode turns without a sign-in gate", () => {
}
});
- it("marks OpenCode's own usage-limit refusal as the account's limit, so another AI can carry on", async () => {
+ it("marks OpenCode's own usage-limit refusal as its provider's models, so another AI can carry on", async () => {
const f = await open("opencode-gave-up", (scratch) => ({ FAKE_ACP_MODELS: "opencode/big-pickle", FAKE_ACP_RPC_FAILURE_FILE: join(scratch, "failure.json") }));
writeFileSync(join(f.scratch, "failure.json"), JSON.stringify({
code: -32603, message: "Internal error: Monthly usage limit reached for this key", data: { service: "session", errorName: "APIError" },
}));
const { done, events } = await f.run("t-gave-up", "opencode/big-pickle");
expect(done).toMatchObject({ ok: false });
- expect(events.find((event) => event.type === "runtime.error")).toMatchObject({ limit: "engine" });
+ expect(events.find((event) => event.type === "runtime.error")).toMatchObject({ limit: "model", limitModels: ["opencode/big-pickle"] });
});
it("stops an engine with no open request, no CPU use and nothing logged after a few minutes, not the full silence guard", async () => {
diff --git a/server/drivers/acp/opencode-go.ts b/server/drivers/acp/opencode-go.ts
index 6668f7f774..4d7b143861 100644
--- a/server/drivers/acp/opencode-go.ts
+++ b/server/drivers/acp/opencode-go.ts
@@ -15,7 +15,7 @@ import { createAcpDriver, type AccountErrorCode, type AcpConfig, type AcpSupport
import { offeredModels } from "./config-options.ts";
import type { AcpRequestSteer } from "./steer.ts";
import { declareTypedOpenCodeModel } from "./opencode-typed-model.ts";
-import { OPENCODE_GO_MODEL_PREFIX } from "../../../shared/opencode-model-id.ts";
+import { OPENCODE_GO_MODEL_PREFIX, typedOpenCodeModel } from "../../../shared/opencode-model-id.ts";
import {
declareLiveOpenCodeModels,
keepOpenCodeModelsFresh,
@@ -777,20 +777,32 @@ 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;
-/** 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. */
+/** A usage limit the error names as the Go subscription's, by its error name or its wording ("OpenCode Go weekly usage
+ * limit reached"), whatever model the session had selected. */
+const GO_NAMED_LIMIT = /\bGoUsageLimitError\b|\b(?:OpenCode\s+)?Go\b.{0,60}\b(?:usage|weekly|monthly|5-hour|daily|hourly)\s+limit/iu;
+
+/** How far a usage limit OpenCode reported reaches: one provider's models — the Go subscription's when the refusal or
+ * the failing model names Go, else the failing model's provider's — or one provider's shared free allowance (with the
+ * free models that allowance holds). A limit that names no provider, or names one this instance lists no models of,
+ * reaches the whole account: there is nothing smaller known to hold. */
export function openCodeLimitFacts(text: string, model?: string, catalog?: ModelCatalog): { limit: "engine" | "model"; limitModels?: string[] } {
+ const failing = model ? (typedOpenCodeModel(model) ?? model) : undefined;
if (!FREE_MODEL_LIMIT.test(text)) {
- if (!model?.startsWith(OPENCODE_GO_MODEL_PREFIX)) return { limit: "engine" };
+ const provider = GO_NAMED_LIMIT.test(text) || failing?.startsWith(OPENCODE_GO_MODEL_PREFIX) ? "opencode-go"
+ : failing?.includes("/") ? failing.slice(0, failing.indexOf("/")) : "";
+ if (!provider) return { limit: "engine" };
+ const prefix = `${provider}/`;
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(OPENCODE_GO_MODEL_PREFIX)))] };
+ const paid = provider === "opencode-go" ? ((catalog && catalogPrices.get(catalog)?.paid) ?? []) : [];
+ const models = [...new Set([failing ?? "", ...paid, ...listed].filter((id) => id.startsWith(prefix)))];
+ // No model of the named provider is known to hold: the account is held rather than a wrong model guessed.
+ return models.length ? { limit: "model", limitModels: models } : { limit: "engine" };
}
- const provider = model?.includes("/") ? model.slice(0, model.indexOf("/")) : "";
+ const provider = failing?.includes("/") ? failing.slice(0, failing.indexOf("/")) : "";
const offered = new Set(catalog?.options.map((option) => option.id));
const free = catalog && catalogPrices.get(catalog)?.free;
const shared = provider ? (free ?? []).filter((id) => offered.has(id) && id.startsWith(`${provider}/`)) : [];
- const models = [...new Set(model ? [model, ...shared] : shared)];
+ const models = [...new Set(failing ? [failing, ...shared] : shared)];
return models.length > 1 ? { limit: "model", limitModels: models } : { limit: "model" };
}
diff --git a/server/drivers/acp/quiet-status.test.ts b/server/drivers/acp/quiet-status.test.ts
index c806a98ef8..646b38b288 100644
--- a/server/drivers/acp/quiet-status.test.ts
+++ b/server/drivers/acp/quiet-status.test.ts
@@ -71,7 +71,7 @@ describe("parseOpenCodeLogLine", () => {
it("reads only this session's main-request errors", () => {
const limit = 'error.error="AI_APICallError: Rate limit exceeded. Please try again later."';
expect(parseOpenCodeLogLine(openCodeRow(`session.id=ses_a small=false agent=build mode=primary ${limit}`), "ses_a"))
- .toEqual({ kind: "provider-error", message: "Rate limit exceeded. Please try again later." });
+ .toEqual({ kind: "provider-error", message: "Rate limit exceeded. Please try again later.", model: "opencode/mimo-v2.6-flash-free" });
expect(parseOpenCodeLogLine(openCodeRow(`session.id=ses_b small=false ${limit}`), "ses_a")).toBeNull();
expect(parseOpenCodeLogLine(openCodeRow(`session.id=ses_ab small=false ${limit}`), "ses_a")).toBeNull();
expect(parseOpenCodeLogLine(openCodeRow(`session.id=ses_a small=true agent=title ${limit}`), "ses_a")).toBeNull();
@@ -79,6 +79,17 @@ describe("parseOpenCodeLogLine", () => {
expect(parseOpenCodeLogLine(openCodeRow("session.id=ses_a small=false"), "ses_a")).toBeNull();
});
+ it("names the provider and model that failed, which the refusal text may not", () => {
+ const row = (fields: string) =>
+ `timestamp=2026-10-01T00:00:03.000Z level=ERROR run=fixture_run message="stream error" ${fields}`;
+ const limit = 'error.error="AI_APICallError: Usage limit reached"';
+ expect(parseOpenCodeLogLine(row(`providerID=opencode-go modelID=kimi-k3 session.id=ses_a small=false ${limit}`), "ses_a"))
+ .toEqual({ kind: "provider-error", message: "Usage limit reached", model: "opencode-go/kimi-k3" });
+ // A model id with its own separator survives (OpenRouter): only the first separator names the provider.
+ expect(parseOpenCodeLogLine(row(`providerID=openrouter modelID=anthropic/claude-sonnet-5 session.id=ses_a small=false ${limit}`), "ses_a"))
+ .toEqual({ kind: "provider-error", message: "Usage limit reached", model: "openrouter/anthropic/claude-sonnet-5" });
+ });
+
it("never repeats a key the provider echoed", () => {
const signal = parseOpenCodeLogLine(openCodeRow('session.id=ses_a error.error="AI_APICallError: Incorrect API key provided: sk-proj-abcdefghijklmnopqrstuvwxyz123456"'), "ses_a");
expect(signal).toMatchObject({ kind: "provider-error", message: expect.stringContaining("Incorrect API key provided") });
@@ -87,7 +98,7 @@ describe("parseOpenCodeLogLine", () => {
it("keeps an escaped quote inside the error", () => {
expect(parseOpenCodeLogLine(openCodeRow('session.id=ses_a error.error="Model \\"x\\" is overloaded" next=1'), "ses_a"))
- .toEqual({ kind: "provider-error", message: 'Model \\"x\\" is overloaded' });
+ .toEqual({ kind: "provider-error", message: 'Model \\"x\\" is overloaded', model: "opencode/mimo-v2.6-flash-free" });
});
});
diff --git a/server/drivers/acp/quiet-status.ts b/server/drivers/acp/quiet-status.ts
index 9437d4a977..f77ca928c0 100644
--- a/server/drivers/acp/quiet-status.ts
+++ b/server/drivers/acp/quiet-status.ts
@@ -40,7 +40,7 @@ export type LogSignal =
| { kind: "retry"; status: number | null; delayMs: number | null; attempt: number | null }
| { kind: "compressing" }
| { kind: "context"; tokens: number; threshold: number }
- | { kind: "provider-error"; message: string };
+ | { kind: "provider-error"; message: string; model?: string };
export type QuietState =
| { kind: "retrying"; status: number | null; delayMs: number | null; attempt: number | null }
@@ -85,13 +85,18 @@ export function parseQwenLogLine(line: string): LogSignal | null {
}
/** OpenCode 1.18's shared log, one logfmt row per failed model call of any session or process, like
- * `level=ERROR … message="stream error" … session.id=ses_… small=false … error.error="AI_APICallError: Rate limit exceeded."`.
- * `small=true` is the session's title request, not the turn. */
+ * `level=ERROR … message="stream error" … providerID=opencode-go modelID=kimi-k3 session.id=ses_… small=false … error.error="AI_APICallError: Rate limit exceeded."`.
+ * `small=true` is the session's title request, not the turn. `model` names the provider and model that failed, which
+ * the refusal text itself may not. */
export function parseOpenCodeLogLine(line: string, sessionId: string): LogSignal | null {
const fields = line.split(" ");
if (!fields.includes("level=ERROR") || !fields.includes(`session.id=${sessionId}`) || fields.includes("small=true")) return null;
const error = /\berror\.error="((?:[^"\\]|\\.)*)"/.exec(line)?.[1];
- return error ? { kind: "provider-error", message: redactSecretsInText(error.replace(/^AI_APICallError:\s*/, "")).slice(0, 200) } : null;
+ if (!error) return null;
+ const provider = /\bproviderID=(\S+)/.exec(line)?.[1];
+ const modelId = /\bmodelID=(\S+)/.exec(line)?.[1];
+ const model = provider && modelId ? `${provider}/${modelId}` : undefined;
+ return { kind: "provider-error", message: redactSecretsInText(error.replace(/^AI_APICallError:\s*/, "")).slice(0, 200), ...(model ? { model } : {}) };
}
export class LogTail {
@@ -348,7 +353,8 @@ export function quietVerdict(input: {
const limited = input.logged && waitingOutLimit(input.logged.signal) && input.now - input.logged.at >= limitQuietMs() ? input.logged.signal : null;
if (limited) {
const said = limited.kind === "provider-error" ? ` (“${limited.message}”)` : "";
- return { next, noSignsSince, stop: Object.assign(new RuntimeNoticeError(`${input.name} reached a usage limit${said} and is waiting it out without replying, so this turn was stopped.`, "chat.notice.acpQuietUsageLimit", { name: input.name, said }), { acpUsageLimit: true }) };
+ return { next, noSignsSince, stop: Object.assign(new RuntimeNoticeError(`${input.name} reached a usage limit${said} and is waiting it out without replying, so this turn was stopped.`, "chat.notice.acpQuietUsageLimit", { name: input.name, said }),
+ { acpUsageLimit: true, ...(limited.kind === "provider-error" && limited.model ? { acpUsageLimitModel: limited.model } : {}) }) };
}
if (noSignsSince !== null && input.now - noSignsSince >= noSignsStopMs()) {
return { next, noSignsSince, stop: Object.assign(new RuntimeNoticeError(`${input.name} sent nothing for ${formatQuietLimit(input.quietMs)} with no tool running, no open request to its model and no CPU use, so the turn was stopped as stuck. Send the message again to retry.`, "chat.notice.acpQuietStuck", { name: input.name, quiet: formatQuietLimit(input.quietMs) }), { acpPromptStall: true }) };
diff --git a/server/drivers/runtime-notice-error.test.ts b/server/drivers/runtime-notice-error.test.ts
index a8aa1f9230..e3c9b1bec0 100644
--- a/server/drivers/runtime-notice-error.test.ts
+++ b/server/drivers/runtime-notice-error.test.ts
@@ -57,6 +57,9 @@ describe("runtime notice provenance", () => {
const text = runtimeErrorText(verdict.stop)!;
expect(text.key).toBe("chat.notice.acpQuietUsageLimit");
expect(chatNotice("chat.notice.acpQuietUsageLimit", text.params)).toBe(verdict.stop?.message);
+ // The failed call's log row names the provider and model that hit the limit, so the hold can be scoped to it.
+ const named = quietVerdict({ name: "Custom ACP", next: { kind: "provider-error", message: "HTTP 429" }, logged: { signal: { kind: "provider-error", message: "HTTP 429", model: "opencode-go/kimi-k3" }, at: 0 }, now: 600_000, quietMs: 600_000, noSignsSince: null, stuckAfterMs: 600_000 });
+ expect(named.stop).toMatchObject({ acpUsageLimit: true, acpUsageLimitModel: "opencode-go/kimi-k3" });
const stuck = quietVerdict({ name: "Custom ACP", next: { kind: "no-signs" }, logged: null, now: 600_000, quietMs: 600_000, noSignsSince: 0, stuckAfterMs: 100_000 });
expect(stuck.stop).toMatchObject({ acpPromptStall: true });
expect(runtimeErrorText(stuck.stop)?.key).toBe("chat.notice.acpQuietStuck");
diff --git a/server/host/limit-takeover.test.ts b/server/host/limit-takeover.test.ts
index a41c1e79f5..0e773a56a4 100644
--- a/server/host/limit-takeover.test.ts
+++ b/server/host/limit-takeover.test.ts
@@ -107,15 +107,28 @@ describe("which AI carries on while one is limited", () => {
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, model) => clock.resetAt(id, model),
- chosen: () => [on("claude", "claude-opus-5-5")] });
+ holdScope: (id, model) => clock.holdScope(id, model), chosen: () => [on("claude", "claude-opus-5-5")] });
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 });
+ // The Go subscription's meter holds the Go models only: model scope, so the instance's other providers still serve.
+ expect(instance.heldAtStart(KAI, on("opencode", "opencode-go/kimi-k2"))).toEqual({ scope: "model", 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"));
clock.noteRefusal("opencode", NOW + HOUR / 2);
const free = instance.heldAtStart(KAI, on("opencode", "opencode/big-pickle"));
expect(free?.resetsAt, "a refused free model waits for the refusal's reset, not the Go meter's later one").toBe(clock.blockedUntil("opencode", "opencode/big-pickle"));
expect(free?.resetsAt).toBeLessThan(NOW + HOUR);
+ expect(instance.heldAtStart(KAI, on("opencode", "opencode-go/kimi-k2"))?.scope, "an engine-wide refusal still holds the account").toBe("engine");
+ });
+
+ it("carries a full Go meter over to a Zen model of the same OpenCode instance", () => {
+ 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 taken = takeover({ engines: () => [openCode, CLAUDE, CODEX], blockedUntil: (id, model) => clock.blockedUntil(id, model), resetAt: (id, model) => clock.resetAt(id, model),
+ holdScope: (id, model) => clock.holdScope(id, model), chosen: () => [] }).instance
+ .takeoverAtStart(KAI, on("opencode", "opencode-go/kimi-k2"), [on("opencode", "opencode/big-pickle")]);
+ expect(taken).toEqual({ to: on("opencode", "opencode/big-pickle"), scope: "model", resetsAt: NOW + HOUR });
});
it("carries on only with a backup the person chose, one that bills each use included", () => {
diff --git a/server/host/limit-takeover.ts b/server/host/limit-takeover.ts
index 440ceeabf2..35869d50b8 100644
--- a/server/host/limit-takeover.ts
+++ b/server/host/limit-takeover.ts
@@ -57,6 +57,9 @@ export interface LimitTakeoverDeps {
context: DefaultSelectionContext;
/** Until when this engine refuses work, or null. */
blockedUntil(instanceId: string, model?: string): number | null;
+ /** What holds this engine for a model now: the account ("engine"), only some of its models ("model", OpenCode's Go
+ * subscription's meter), or null. Asked whenever `blockedUntil` holds one, to decide who may carry on. */
+ holdScope?(instanceId: string, model?: string): "engine" | "model" | 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. */
@@ -275,9 +278,12 @@ export function createLimitTakeover(deps: LimitTakeoverDeps) {
function holdOn(selection: ModelSelection): { scope: TakeoverScope; resetsAt?: number } | null {
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;
+ const scope: TakeoverScope | null = engineUntil !== null ? deps.holdScope?.(selection.instanceId, selection.model) ?? "engine"
+ : model ? model.scope : signedOutHeld(selection.instanceId) ? "signed-out" : null;
if (!scope) return null;
- const resetsAt = scope === "engine" ? deps.resetAt?.(selection.instanceId, selection.model) ?? undefined : model?.resetsAt;
+ const resetsAt = scope === "signed-out" ? undefined
+ : scope === "engine" || !model ? deps.resetAt?.(selection.instanceId, selection.model) ?? undefined
+ : model.resetsAt;
return { scope, ...(resetsAt && resetsAt > now() ? { resetsAt } : {}) };
}
diff --git a/server/index.ts b/server/index.ts
index 1dfb5fbf7e..59dc892486 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -8632,7 +8632,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), 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) => 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")) }); 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-resets.test.ts b/server/limit-resets.test.ts
index 16f5089b92..3b7c68fac7 100644
--- a/server/limit-resets.test.ts
+++ b/server/limit-resets.test.ts
@@ -679,8 +679,11 @@ describe("LimitResetClock and the turns that follow a refusal", () => {
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();
+ expect(instance.holdScope("opencodeGo", "opencode-go/kimi-k2"), "a meter that covers some models holds them as model scope").toBe("model");
+ expect(instance.holdScope("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();
+ expect(instance.holdScope("opencodeGo", "opencode-go/kimi-k2"), "a refusal of the whole account is engine scope").toBe("engine");
expect(instance.resetAt("opencodeGo", "opencode/big-pickle"), "a free model resets with the refusal, not the Go meter").toBeLessThan(NOW + 4 * HOUR);
expect(instance.resetAt("opencodeGo", "opencode-go/kimi-k2")).toBe(NOW + 4 * HOUR);
});
@@ -689,6 +692,7 @@ describe("LimitResetClock and the turns that follow a refusal", () => {
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);
+ expect(instance.holdScope("claude", "claude-sonnet-5"), "a meter that covers the whole account is engine scope").toBe("engine");
});
it("ends a hold at once on Try again now, saved across a restart, and a new refusal holds it again", () => {
diff --git a/server/limit-resets.ts b/server/limit-resets.ts
index 0d5dac0b36..68fb0d09ff 100644
--- a/server/limit-resets.ts
+++ b/server/limit-resets.ts
@@ -160,6 +160,18 @@ export class LimitResetClock {
return this.refusal(engine) === null && this.blockedUntil(engine, model) !== null;
}
+ /** What holds this engine for `model` now, as far as is known: `"engine"` when a refusal holds it or its usage meter
+ * covers every model of the account, `"model"` when only a meter that covers some models does (OpenCode's meter is the
+ * Go subscription's, so at its limit the account's other providers still run), null when nothing does. */
+ holdScope(engine: string, model?: string): "engine" | "model" | null {
+ const now = this.now();
+ const refused = this.refusal(engine);
+ const usage = this.meterFor(engine, model);
+ const until = Math.max(refused ?? 0, usage?.blocked && usage.resetsAt !== null ? usage.resetsAt : 0);
+ if (until <= now) return null;
+ return refused === null && usage?.driver === "opencode" && model !== undefined ? "model" : "engine";
+ }
+
/** 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. */
private meterFor(engine: string, model?: string): EngineLimit | undefined {