Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix: a free model's usage limit holds that model, not the OpenCode account
quang.tranminh69097960bb28
diff --git a/docs/opencode-go.md b/docs/opencode-go.mdindex 2cece5fd54..5d61565c54 100644--- a/docs/opencode-go.md+++ b/docs/opencode-go.md@@ -64,6 +64,21 @@ OpenMausBot retries it once with each MCP server listing only its share ofwhat OpenCode's own tools leave, keeps doing so for that model until itrestarts, and logs how many tools each server left out.+## Usage limits++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+allowance (a Go limit, or a monthly one) holds the whole account until its+window resets, 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 →+API keys, or the login `opencode auth login` keeps in `auth.json`. An OpenCode+2 install keeps its logins in its own database instead, so saving the key in+OpenMausBot is what makes those windows readable there.+## TestingNormal unit and ACP protocol tests do not require a subscription. Live testsdiff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.tsindex 9be470eafe..8471d95676 100644--- a/server/drivers/acp/core.ts+++ b/server/drivers/acp/core.ts@@ -221,6 +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";/** 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;@@ -1485,8 +1486,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>// opencode 1.18.18 reports usage at the result root; grok and gemini under _meta.const usage = result?.usage ?? result?._meta ?? {};if (typeof usage.inputTokens === "number" || typeof usage.outputTokens === "number") {- // opencode 1.18.25 keeps only the uncached share in inputTokens and reports cache reads- // beside it (omitted when 0); other agents count them inside. Absent is not zero.+ // opencode 1.18.25 keeps only the uncached share in inputTokens and reports cache reads beside it (omitted when 0); other agents count them inside. Absent is not zero.const input = usage.inputTokens ?? 0;const output = usage.outputTokens ?? 0;const cachedRead = typeof usage.cachedReadTokens === "number" && usage.cachedReadTokens > 0@@ -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: "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)) ? { limit: support.limitScope?.(message) ?? "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 === truediff --git a/server/drivers/acp/opencode-go.test.ts b/server/drivers/acp/opencode-go.test.tsindex 2ef3ca5991..0766072b77 100644--- a/server/drivers/acp/opencode-go.test.ts+++ b/server/drivers/acp/opencode-go.test.ts@@ -17,6 +17,7 @@ import {describeOpenCodeAccountError,discoverOpenCodeModels,openCodeFreeFallback,+ openCodeLimitScope,openCodeOwnedDirectories,OpenCodeDriver,openCodeProviderKeysAllowed,@@ -324,6 +325,19 @@ describe("OpenCode catalog", () => {expect(classifyOpenCodeError(apiError(message))).toBeUndefined();});+ // A Go subscriber can still run out of Zen's free models: the paid Go and Zen models on the same login keep working,+ // so that refusal holds only the free model, never the whole OpenCode account.+ it.each([+ ['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"],+ ["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"],+ ] as const)("reads how far the usage limit reaches: %s", (message, expected) => {+ expect(openCodeLimitScope(message)).toBe(expected);+ });+it("classifies OpenCode 2's authentication refusal and leaves real internal errors alone", () => {expect(classifyOpenCodeError({ code: -32000, message: "Authentication required: provider authentication required", data: {} })).toBe("invalid_credentials");@@ -834,6 +848,28 @@ describe("OpenCode turns without a sign-in gate", () => {}});+ // Recorded from opencode 1.18.27 with a `-free` model on an account that still has Go allowance: the refusal is Zen's+ // free-tier limit, so it holds that model alone and the account stays usable on a Go model.+ it("holds only the free model a Go account's free allowance limited, not the account", async () => {+ vi.spyOn(quietStatus, "sampleProcessTree").mockResolvedValue({ cpuMs: 0, connections: 0 });+ vi.stubEnv("OMB_ACP_QUIET_NOTICE_MS", "300");+ vi.stubEnv("OMB_ACP_QUIET_TICK_MS", "50");+ vi.stubEnv("OMB_ACP_LIMIT_QUIET_MS", "400");+ const row = `timestamp=2026-11-07T10:13:43.366Z level=ERROR run=fixture_run message="stream error" providerID=opencode modelID=deepseek-v4.1-flash-free session.id={session} small=false agent=build mode=primary error.error="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 f = await open("opencode-go-free-limit", () => ({+ FAKE_ACP_MODE: "quiet-then-answer", FAKE_ACP_QUIET_MS: "30000", FAKE_ACP_MODELS: "opencode/deepseek-v4.1-flash-free",+ FAKE_ACP_OPENCODE_LOG: JSON.stringify([row]),+ }));+ try {+ const { done, events } = await f.run("t-go-free-limit", "opencode/deepseek-v4.1-flash-free");+ expect(done).toMatchObject({ ok: false, stopReason: "quota" });+ expect(events.find((event) => event.type === "runtime.error")).toMatchObject({ limit: "model", message: expect.stringMatching(/usage limit/i) });+ } finally {+ vi.unstubAllEnvs();+ vi.restoreAllMocks();+ }+ });+it("marks OpenCode's own usage-limit refusal as the account's limit, 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({diff --git a/server/drivers/acp/opencode-go.ts b/server/drivers/acp/opencode-go.tsindex 59de0a63c8..715a68f5e2 100644--- a/server/drivers/acp/opencode-go.ts+++ b/server/drivers/acp/opencode-go.ts@@ -912,6 +912,7 @@ const support = (|| await canRunOpenCode(env, config.cli, loadCatalog);},classifyError: classifyOpenCodeError,+ limitScope: openCodeLimitScope,describeAccountError: describeOpenCodeAccountError,resolveModels: async (environment, config, instanceId, fresh) => {if (fresh) markOpenCodeCatalogRefreshed(instanceId, (sources.now ?? Date.now)());@@ -933,6 +934,15 @@ const ACCOUNT_ERROR_TEXT: ReadonlyArray<readonly [RegExp, AccountErrorCode]> = [[/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. */+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";+}+export function classifyOpenCodeError(error: unknown): ProviderErrorCode | undefined {const value = error && typeof error === "object" ? error as Record<string, unknown> : {};const code = value.code;