Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Plan usage reads OpenCode Go's allowance
BunBnnuye7f61b0a634a
diff --git a/scripts/testing/file-size-ratchet.test.ts b/scripts/testing/file-size-ratchet.test.tsindex 073341e2ed..624451a932 100644--- a/scripts/testing/file-size-ratchet.test.ts+++ b/scripts/testing/file-size-ratchet.test.ts@@ -39,6 +39,7 @@ const LINES: Record<string, number> = {"scripts/mcp-server.ts": 1414,"server/boat.ts": 1258,"server/drivers/pi.ts": 1036,+ "server/plan-usage.ts": 1050,"server/container-computer.ts": 1225,"src/components/ModelPicker.tsx": 1046,"src/components/PhoneSetupFlow.tsx": 1146,diff --git a/server/plan-usage.test.ts b/server/plan-usage.test.tsindex ddd8d1e0fe..d1c0a40e68 100644--- a/server/plan-usage.test.ts+++ b/server/plan-usage.test.ts@@ -10,6 +10,7 @@ import {parseClaudeUsage,parseCodexUsage,parseGrokUsage,+ parseOpenCodeUsage,planAccountsFromInstances,type PlanAccount,type PlanFetch,@@ -32,9 +33,10 @@ function jsonResponse(body: unknown, status = 200): PlanResponse {}function account(driver: PlanAccount["driver"], extras: Partial<PlanAccount> = {}): PlanAccount {+ const name = driver === "claude" ? "Claude" : driver === "codex" ? "Codex" : driver === "opencode" ? "OpenCode" : "Grok";return {id: driver,- name: driver === "claude" ? "Claude" : driver === "codex" ? "Codex" : "Grok",+ name,driver,environment: {},...extras,@@ -241,6 +243,30 @@ describe("plan usage parsers", () => {});});+describe("an OpenCode Go allowance", () => {+ const body = {+ usage: {+ rolling: { status: "ok", percent: 5, resetsAt: "2026-11-04T22:20:18.000Z" },+ weekly: { status: "rate-limited", percent: 100, resetsAt: "2026-11-09T00:00:00.000Z" },+ monthly: { status: "ok", percent: 17, resetsAt: "2026-11-24T21:32:14.000Z" },+ },+ };++ it("reads the running window, the week and the month", () => {+ const parsed = parseOpenCodeUsage(body);+ expect(parsed.plan).toBe("Go");+ expect(parsed.fiveHour).toEqual({ available: true, usedPercent: 5, remainingPercent: 95, resetsAt: "2026-11-04T22:20:18.000Z" });+ expect(parsed.weekly).toMatchObject({ usedPercent: 100, remainingPercent: 0 });+ expect(parsed.extra).toEqual([{ label: "Monthly", usedPercent: 17, remainingPercent: 83, resetsAt: "2026-11-24T21:32:14.000Z" }]);+ });++ it("says nothing it was not given", () => {+ expect(parseOpenCodeUsage({}).plan).toBeNull();+ expect(parseOpenCodeUsage({ usage: {} }).fiveHour.available).toBe(false);+ expect(parseOpenCodeUsage({ usage: { rolling: { status: "ok", percent: "5" } } }).fiveHour.available).toBe(false);+ });+});+describe("plan usage fetcher", () => {it("does not call fetch when the Claude token is expired", async () => {const fetchImpl = vi.fn<PlanFetch>();@@ -473,6 +499,73 @@ describe("plan usage fetcher", () => {]);});+ it("lists an OpenCode instance under the key its environment carries", () => {+ expect(planAccountsFromInstances({+ open: { driver: "opencodeGo", environment: { OPENCODE_API_KEY: SECRET } },+ })).toEqual([{ id: "open", name: "OpenCode", driver: "opencode", environment: { OPENCODE_API_KEY: SECRET } }]);+ });++ it("reads OpenCode Go's allowance with the key saved on the instance", async () => {+ const fetchImpl = vi.fn<PlanFetch>(async () => jsonResponse({+ usage: {+ rolling: { status: "ok", percent: 5, resetsAt: "2026-11-04T22:20:18.000Z" },+ weekly: { status: "ok", percent: 15, resetsAt: "2026-11-09T00:00:00.000Z" },+ monthly: { status: "ok", percent: 17, resetsAt: "2026-11-24T21:32:14.000Z" },+ },+ }));+ const report = await fetchPlanUsage([account("opencode", { environment: { OPENCODE_API_KEY: SECRET } })], {+ fetch: fetchImpl,+ now: () => NOW,+ credentials: fileCredentialReader({ now: () => NOW, env: {}, readText: () => null }),+ });+ expect(fetchImpl.mock.calls[0]?.[0]).toBe("https://opencode.ai/zen/go/v1/usage");+ expect(fetchImpl.mock.calls[0]?.[1].headers.Authorization).toBe(`Bearer ${SECRET}`);+ expect(report.providers[0]).toMatchObject({+ driver: "opencode",+ ok: true,+ error: null,+ plan: "Go",+ fiveHour: { available: true, usedPercent: 5, remainingPercent: 95 },+ weekly: { available: true, usedPercent: 15 },+ });+ expect(report.providers[0]?.extra[0]).toMatchObject({ label: "Monthly", usedPercent: 17 });+ expect(JSON.stringify(report)).not.toContain(SECRET);+ });++ it("takes the CLI's OpenCode Go login when no key is saved, before the Zen one", async () => {+ const goLogin = "opencode-go-fixture-login";+ const zenLogin = "opencode-zen-fixture-login";+ const fetchImpl = vi.fn<PlanFetch>(async () => jsonResponse({ usage: { rolling: { status: "ok", percent: 4, resetsAt: null } } }));+ const auth = (entries: Record<string, unknown>) => ({ OPENCODE_AUTH_CONTENT: JSON.stringify(entries) });+ await fetchPlanUsage([+ account("opencode", { id: "go", environment: auth({ opencode: { type: "key", key: zenLogin }, "opencode-go": { type: "oauth", access: goLogin, expires: NOW + 600_000 } }) }),+ account("opencode", { id: "zen", environment: auth({ opencode: { type: "key", key: zenLogin } }) }),+ ], {+ fetch: fetchImpl,+ now: () => NOW,+ credentials: fileCredentialReader({ now: () => NOW, env: {}, readText: () => null }),+ });+ expect(fetchImpl.mock.calls.map((call) => call[1].headers.Authorization)).toEqual([`Bearer ${goLogin}`, `Bearer ${zenLogin}`]);+ });++ it("keeps the OpenCode row when there is no Go plan, and names a refused key", async () => {+ const credentials = fileCredentialReader({ now: () => NOW, env: {}, readText: () => null });+ const instances = [account("opencode", { environment: { OPENCODE_API_KEY: SECRET } })];+ const noGo = await fetchPlanUsage(instances, {+ fetch: async () => jsonResponse({ _tag: "Forbidden" }, 403),+ now: () => NOW,+ credentials,+ });+ expect(noGo.providers[0]).toMatchObject({ ok: true, error: null, plan: null, fiveHour: { available: false }, extra: [] });++ const refused = await fetchPlanUsage(instances, {+ fetch: async () => jsonResponse({ error: "unauthorized" }, 401),+ now: () => NOW,+ credentials,+ });+ expect(refused.providers[0]).toMatchObject({ ok: false, error: "OpenCode refused the saved credentials" });+ });+it("reads no usage for a ChatGPT-plan provider, whose sign-in is not the shared Codex login", async () => {// Reading ~/.codex/auth.json for it reported (and held) the default Codex account's limit on a different account.const accounts = planAccountsFromInstances({diff --git a/server/plan-usage.ts b/server/plan-usage.tsindex 977ae18064..8636d6848b 100644--- a/server/plan-usage.ts+++ b/server/plan-usage.ts@@ -2,13 +2,14 @@import { execFile } from "node:child_process";import { createHash } from "node:crypto";import { readFileSync, statSync } from "node:fs";+import { homedir } from "node:os";import { join } from "node:path";import type { InstanceConfigMap } from "./contracts.ts";import { resolveClaudeConfigDir } from "./drivers/claude.ts";import { codexHome } from "./drivers/codex-identity.ts";import { harnessHome, sealedFixture } from "./env-path.ts";-export type PlanDriver = "claude" | "codex" | "grok";+export type PlanDriver = "claude" | "codex" | "grok" | "opencode";export interface PlanWindow {available: boolean;@@ -125,6 +126,8 @@ const CODEX_USAGE_URL = "https://chatgpt.com/backend-api/wham/usage";const GROK_CREDITS_URL = "https://cli-chat-proxy.grok.com/v1/billing?format=credits";const GROK_BILLING_URL = "https://cli-chat-proxy.grok.com/v1/billing";const GROK_SETTINGS_URL = "https://cli-chat-proxy.grok.com/v1/settings";+// OpenCode Go's own allowance: the rolling window, the weekly one and the month's, as the CLI reads them.+const OPENCODE_GO_USAGE_URL = "https://opencode.ai/zen/go/v1/usage";const FIVE_HOUR_MIN_SECONDS = 3 * 3600;const FIVE_HOUR_MAX_SECONDS = 8 * 3600;@@ -137,12 +140,14 @@ const DRIVER_OF: Record<string, PlanDriver> = {claudeAgent: "claude",codex: "codex",grokAgent: "grok",+ opencodeGo: "opencode",};const PRODUCT_NAME: Record<PlanDriver, string> = {claude: "Claude",codex: "Codex",grok: "Grok",+ opencode: "OpenCode",};export function planAccountsFromInstances(instances: InstanceConfigMap): PlanAccount[] {@@ -235,6 +240,27 @@ export function parseGrokUsage(credits: unknown, billing?: unknown, settings?: ureturn { plan: grokPlan(settings), fiveHour, weekly, extra, models };}+/** OpenCode Go answers with a meter per window: the running one, the week's and the month's. */+export function parseOpenCodeUsage(body: unknown): PlanWindows {+ const usage = asRecord(asRecord(body)?.usage);+ const [rolling, weekly, monthly] = [usage?.rolling, usage?.weekly, usage?.monthly].map(openCodeMeter);+ return {+ plan: rolling || weekly || monthly ? "Go" : null,+ fiveHour: rolling ?? closedWindow(),+ weekly: weekly ?? closedWindow(),+ extra: monthly ? [extraLine("Monthly", monthly)] : [],+ models: [],+ };+}++/** One meter of Go's allowance: `percent` is what it has used, and `resetsAt` comes as an ISO stamp. */+function openCodeMeter(value: unknown): PlanWindow | null {+ const record = asRecord(value);+ const used = finiteNumber(record?.percent);+ if (used == null) return null;+ return openWindow(used, isoOrNull(record?.resetsAt));+}+export function fileCredentialReader(source: CredentialSource): CredentialReader {const env = source.env ?? process.env;const now = source.now ?? Date.now;@@ -244,6 +270,7 @@ export function fileCredentialReader(source: CredentialSource): CredentialReaderconst at = now();if (account.driver === "claude") return readClaudeCredential(account, merged, source, at);if (account.driver === "codex") return readCodexCredential(merged, source.readText, at);+ if (account.driver === "opencode") return readOpenCodeCredential(merged, source.readText, at);return readGrokCredential(merged, source.readText, at);},};@@ -828,6 +855,40 @@ function readGrokCredential(return sawExpired ? expiredCredential() : missingCredential();}+/** The key saved in Settings, or the login `opencode auth login` keeps in the CLI's data folder. */+function readOpenCodeCredential(+ env: NodeJS.ProcessEnv,+ readText: (path: string) => string | null,+ now: number,+): PlanCredential {+ const key = secretString(env.OPENCODE_API_KEY);+ if (key) return { token: key, accountId: null, expired: false };+ const raw = env.OPENCODE_AUTH_CONTENT ?? openCodeAuthText(env, readText);+ const stored = asRecord(parseJson(raw));+ // A Go login lives under "opencode-go", a Zen one under "opencode"; the CLI lists Go first too.+ const entry = [stored?.["opencode-go"], stored?.opencode].map((value) => asRecord(value))+ .find((record) => secretString(record?.access) ?? secretString(record?.key));+ const token = secretString(entry?.access) ?? secretString(entry?.key);+ if (!token) return missingCredential();+ const expiry = timeMs(entry?.expires ?? entry?.expires_at ?? entry?.expiresAt);+ if (expiry != null && expiry <= now) return expiredCredential();+ return { token, accountId: null, expired: false };+}++/** The CLI is xdg-flavoured on every platform, so the xdg data folder comes first. */+function openCodeAuthText(env: NodeJS.ProcessEnv, readText: (path: string) => string | null): string | null {+ const home = env.HOME || env.USERPROFILE || homedir();+ const roots = [+ env.XDG_DATA_HOME || join(home, ".local", "share"),+ process.platform === "darwin" ? join(home, "Library", "Application Support") : "",+ process.platform === "win32" ? env.LOCALAPPDATA || join(home, "AppData", "Local") : "",+ ].filter(Boolean);+ for (const root of roots) {+ const text = readText(join(root, "opencode", "auth.json"));+ if (text) return text;+ }+ return null;+}function errorRow(account: PlanAccount, error: string): PlanProviderRow {return {id: account.id,@@ -869,6 +930,7 @@ async function fetchProvider(account: PlanAccount, deps: PlanUsageDeps): Promisetry {if (account.driver === "claude") return await fetchClaude(account, credential.token, deps);if (account.driver === "codex") return await fetchCodex(account, credential.token, credential.accountId, deps);+ if (account.driver === "opencode") return await fetchOpenCode(account, credential.token, deps);return await fetchGrok(account, credential.token, deps);} catch {return errorRow(account, couldNotReach(account.driver));@@ -970,3 +1032,18 @@ async function fetchGrok(account: PlanAccount, token: string, deps: PlanUsageDepconst windows = parseGrokUsage(creditsBody, billingBody ?? undefined, settings.ok ? settings.body : undefined);return okRow(account, windows);}++/** Go's allowance, read with the account's own key or login. A key without a Go subscription answers 403. */+async function fetchOpenCode(account: PlanAccount, token: string, deps: PlanUsageDeps): Promise<PlanProviderRow> {+ const result = await fetchJson(deps.fetch, OPENCODE_GO_USAGE_URL, {+ Authorization: `Bearer ${token}`,+ Accept: "application/json",+ }, deps.timeoutMs ?? PROVIDER_TIMEOUT_MS);+ // 403 is Go's own answer for a key without a Go subscription: the account works and has no allowance to report.+ if (result.status === 403) return okRow(account, { plan: null, fiveHour: closedWindow(), weekly: closedWindow(), extra: [], models: [] });+ if (authRejected(result.status)) return errorRow(account, "OpenCode refused the saved credentials");+ if (!result.ok || result.body === null || typeof result.body !== "object") {+ return errorRow(account, result.status === 0 || result.status >= 500 ? couldNotReach("opencode") : unexpectedUsage("opencode"));+ }+ return okRow(account, parseOpenCodeUsage(result.body));+}diff --git a/shared/limit-reset.ts b/shared/limit-reset.tsindex 92412cdd24..ec02ef24c2 100644--- a/shared/limit-reset.ts+++ b/shared/limit-reset.ts@@ -30,7 +30,7 @@ export interface EngineLimit {engine: string;/** The engine's display name ("Claude", "Codex", or the instance's own name). */name: string;- driver: "claude" | "codex" | "grok";+ driver: "claude" | "codex" | "grok" | "opencode";/** The window that decides the reset: the fullest, or the one refusing work. */window: LimitWindowName | null;/** 0–100, or null when the engine reported no window. */