Skip to content

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

fix: hold OpenCode's shared free allowance, and recognise FreeUsageLimitError

quang.tranminhd6654d35f69b
diff --git a/docs/opencode-go.md b/docs/opencode-go.md
index 5d61565c54..4838e69347 100644
--- a/docs/opencode-go.md
+++ b/docs/opencode-go.md
@@ -68,8 +68,8 @@ 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 model alone, never the account: new turns can
-still run on its other models, Go's included. A limit on the account's own
+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.
diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.ts
index 8471d95676..24f50231bf 100644
--- a/server/drivers/acp/core.ts
+++ b/server/drivers/acp/core.ts
@@ -221,7 +221,7 @@ export interface AcpSupport {
requireAuthenticationBeforeSpawn?: boolean;
/** Classify provider-native failures without coupling the core to messages. */
classifyError?(error: unknown): ProviderErrorCode | undefined;
- /** How far a usage limit the engine reports reaches: its whole account, or one model's own allowance (OpenCode's free models), which leaves its other models working. */ limitScope?(text: string): "engine" | "model";
+ /** 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[] };
/** 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;
@@ -1563,7 +1563,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)) ? { limit: support.limitScope?.(message) ?? "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)) ? support.limitFacts?.(message, cliTurn.model) ?? { 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 (!needsAuth && !accountError && ((e as any)?.acpPromptStall === true || (e as any)?.acpUsageLimit === true || (e as any)?.acpSessionFailure === true
diff --git a/server/drivers/acp/opencode-go.test.ts b/server/drivers/acp/opencode-go.test.ts
index 0766072b77..5f1943e92c 100644
--- a/server/drivers/acp/opencode-go.test.ts
+++ b/server/drivers/acp/opencode-go.test.ts
@@ -17,7 +17,7 @@ import {
describeOpenCodeAccountError,
discoverOpenCodeModels,
openCodeFreeFallback,
- openCodeLimitScope,
+ openCodeLimitFacts,
openCodeOwnedDirectories,
OpenCodeDriver,
openCodeProviderKeysAllowed,
@@ -313,6 +313,8 @@ describe("OpenCode catalog", () => {
["Internal error: Insufficient account funds.", "insufficient_funds"],
["Internal error: An active OpenCode Go subscription is required", "inactive_subscription"],
["Internal error: Monthly usage limit reached for this key", "quota_or_region_restriction"],
+ ["Internal error: FreeUsageLimitError: free models are limited today", "quota_or_region_restriction"],
+ ["Internal error: GoUsageLimitError: the Go allowance is used up", "quota_or_region_restriction"],
] as const)("classifies the real APIError %s", (message, expected) => {
expect(classifyOpenCodeError(apiError(message))).toBe(expected);
});
@@ -335,7 +337,21 @@ describe("OpenCode catalog", () => {
["Internal error: GoUsageLimitError: the Go allowance is used up", "engine"],
["GoUsageLimitError: usage limit reached", "engine"],
] as const)("reads how far the usage limit reaches: %s", (message, expected) => {
- expect(openCodeLimitScope(message)).toBe(expected);
+ expect(openCodeLimitFacts(message).limit).toBe(expected);
+ });
+
+ it("holds a provider's free models together, never a paid Go model", () => {
+ // The catalog reports Zen's free models at cost 0; a Go model is paid.
+ parseOpenCodeModelsOutput([
+ "opencode/big-pickle", JSON.stringify({ cost: { input: 0, output: 0 } }),
+ "opencode-go/deepseek-v4.1-flash", JSON.stringify({ cost: { input: 1, output: 2 } }),
+ ].join("\n"));
+ const said = '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';
+ const facts = openCodeLimitFacts(said, "opencode/deepseek-v4.1-flash-free");
+ expect(facts.limit).toBe("model");
+ expect(facts.limitModels).toEqual(expect.arrayContaining(["opencode/deepseek-v4.1-flash-free", "opencode/big-pickle"]));
+ expect(facts.limitModels).not.toContain("opencode-go/deepseek-v4.1-flash");
+ expect(openCodeLimitFacts(said), "a refusal that names no model holds just the model scope").toEqual({ limit: "model" });
});
it("classifies OpenCode 2's authentication refusal and leaves real internal errors alone", () => {
diff --git a/server/drivers/acp/opencode-go.ts b/server/drivers/acp/opencode-go.ts
index 715a68f5e2..0e3c371da0 100644
--- a/server/drivers/acp/opencode-go.ts
+++ b/server/drivers/acp/opencode-go.ts
@@ -912,7 +912,7 @@ const support = (
|| await canRunOpenCode(env, config.cli, loadCatalog);
},
classifyError: classifyOpenCodeError,
- limitScope: openCodeLimitScope,
+ limitFacts: openCodeLimitFacts,
describeAccountError: describeOpenCodeAccountError,
resolveModels: async (environment, config, instanceId, fresh) => {
if (fresh) markOpenCodeCatalogRefreshed(instanceId, (sources.now ?? Date.now)());
@@ -928,19 +928,24 @@ const support = (
const ACCOUNT_ERROR_TEXT: ReadonlyArray<readonly [RegExp, AccountErrorCode]> = [
[/insufficient (?:account )?(?:funds|balance|credits?)|out of credits?|no credits? (?:left|remaining)|payment required|\b402\b/iu, "insufficient_funds"],
// Not plain "rate limit exceeded": a transient 429 that OpenCode retries itself.
- [/\bquota\b|usage limit|(?:hourly|daily|weekly|monthly|5-hour) limit/iu, "quota_or_region_restriction"],
+ [/\bquota\b|usage limit|\b(?:Free|Go)UsageLimitError\b|(?:hourly|daily|weekly|monthly|5-hour) limit/iu, "quota_or_region_restriction"],
[/\bsubscription\b/iu, "inactive_subscription"],
// "User not found." is OpenRouter's refusal of an unknown key (opencode 1.18.27).
[/invalid api key|api key (?:is )?(?:invalid|missing|revoked|expired)|incorrect api key|unauthori[sz]ed|\b401\b|authentication (?:failed|required)|(?:^|internal error: )user not found\b/iu, "invalid_credentials"],
];
/** A usage limit that only OpenCode's free models met: the paid Go and Zen models on the same login still work, so the
- * refusal holds that model and leaves the account available. */
+ * 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: a free model's own allowance, or the whole account. */
-export function openCodeLimitScope(text: string): "engine" | "model" {
- return FREE_MODEL_LIMIT.test(text) ? "model" : "engine";
+/** How far a usage limit OpenCode reported reaches: one provider's shared free allowance (with the free models that
+ * allowance holds), or the whole account. */
+export function openCodeLimitFacts(text: string, model?: string): { limit: "engine" | "model"; limitModels?: string[] } {
+ if (!FREE_MODEL_LIMIT.test(text)) return { limit: "engine" };
+ const provider = model?.includes("/") ? model.slice(0, model.indexOf("/")) : "";
+ const shared = provider ? [...freeModels].filter((id) => id.startsWith(`${provider}/`)) : [];
+ const models = [...new Set(model ? [model, ...shared] : shared)];
+ return models.length > 1 ? { limit: "model", limitModels: models } : { limit: "model" };
}
export function classifyOpenCodeError(error: unknown): ProviderErrorCode | undefined {
diff --git a/server/host/limit-takeover.test.ts b/server/host/limit-takeover.test.ts
index 9341244086..69c3b886b9 100644
--- a/server/host/limit-takeover.test.ts
+++ b/server/host/limit-takeover.test.ts
@@ -130,6 +130,16 @@ describe("a model's own limit", () => {
now.at = NOW + UNNAMED_LIMIT_MS + 1;
expect(instance.modelHeld(on("claude", "claude-sonnet-5"))).toBeNull();
});
+
+ it("holds every model one shared allowance covers", () => {
+ const { instance } = takeover();
+ instance.noteRuntimeEvent("kai", on("claude", "claude-opus-5-5"),
+ { ...error("model", NOW + 2 * HOUR), limitModels: ["claude-opus-5-5", "claude-sonnet-5"] } as RuntimeEvent);
+ expect(instance.modelHeld(on("claude", "claude-opus-5-5"))).toEqual({ until: NOW + 2 * HOUR, resetsAt: NOW + 2 * HOUR, scope: "model" });
+ expect(instance.modelHeld(on("claude", "claude-sonnet-5")), "the same allowance holds it too")
+ .toEqual({ until: NOW + 2 * HOUR, resetsAt: NOW + 2 * HOUR, scope: "model" });
+ expect(instance.modelHeld(on("codex", "gpt-6")), "another AI is untouched").toBeNull();
+ });
});
describe("what the person hears", () => {
diff --git a/server/host/limit-takeover.ts b/server/host/limit-takeover.ts
index a741c1ca2f..5988093f7d 100644
--- a/server/host/limit-takeover.ts
+++ b/server/host/limit-takeover.ts
@@ -261,7 +261,9 @@ export function createLimitTakeover(deps: LimitTakeoverDeps) {
const said = event.type === "turn.completed" || event.type === "session.exited" ? setupSaid.get(event.threadId) : undefined;
if (said !== undefined) setupSaid.delete(event.threadId);
if (!selection) return;
- if (event.type === "runtime.error" && (event.limit === "model" || event.limit === "credits")) holdModel(selection, event.limit, event.limitResetsAt);
+ if (event.type === "runtime.error" && (event.limit === "model" || event.limit === "credits")) {
+ for (const model of event.limitModels?.length ? event.limitModels : [selection.model]) holdModel({ ...selection, model }, event.limit, event.limitResetsAt);
+ }
else if (event.type === "turn.completed" && event.ok) worked(botId, selection);
else if (event.type === "turn.completed" && signedOutStop(event.stopReason, said)) noteSignedOut(selection.instanceId);
},
diff --git a/shared/runtime-events.ts b/shared/runtime-events.ts
index 5cd6c866a1..9d988146fa 100644
--- a/shared/runtime-events.ts
+++ b/shared/runtime-events.ts
@@ -195,8 +195,9 @@ export type RuntimeEvent = RuntimeEventBase &
// `limitResetsAt`: epoch ms when the usage limit refusing this account resets, when the engine says.
// `limit`: a usage limit refused this turn: the account's on this engine ("engine"), one model's own window
// ("model"), or that model's extra usage credits ("credits"); the engine's other models still work for the last two.
+ // `limitModels`: the models a "model" limit holds, when one allowance is shared (OpenCode's free models).
| { type: "runtime.error"; message: string; partial?: boolean; setup?: boolean; terminal?: boolean; claudeUpdate?: boolean; trialCredit?: "used_up" | "ended" | "paused" | "too_low";
- stalled?: boolean; limitResetsAt?: number; limit?: "engine" | "model" | "credits";
+ stalled?: boolean; limitResetsAt?: number; limit?: "engine" | "model" | "credits"; limitModels?: string[];
/** `message` as a `chat.notice.*` key and params, when it is one of the server's fixed sentences. */
text?: ServerText }
/** Something the person should know that did not fail the turn — for