Skip to content

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

Merge pull request #5200 from leonongoing/leon/fix-opencode-price-holds-4877

milind-soni9d6e16e4ba0a
diff --cc server/drivers/acp/opencode-go.test.ts
index 850bdea725,9c70b98531..2c5c64578e
--- a/server/drivers/acp/opencode-go.test.ts
+++ b/server/drivers/acp/opencode-go.test.ts
@@@ -384,24 -375,6 +384,24 @@@ describe("OpenCode catalog", () =>
expect(openCodeLimitFacts(said), "a refusal that names no model holds just the model scope").toEqual({ limit: "model" });
});
+ // OpenCode Go's weekly allowance is the Go subscription's alone: Zen's free models on the same login keep working, so a
+ // free model there is still a backup when a Go model runs out.
+ it("holds only the Go models when a Go model meets the Go allowance, never Zen's free models", () => {
- parseOpenCodeModelsOutput([
++ const catalog = parseOpenCodeModelsOutput([
+ "opencode/deepseek-v4.1-flash-free", JSON.stringify({ cost: { input: 0, output: 0 } }),
+ "opencode-go/glm-5.3", JSON.stringify({ cost: { input: 1, output: 2 } }),
+ "opencode-go/minimax-m3", JSON.stringify({ cost: { input: 1, output: 2 } }),
- ].join("\n"));
++ ].join("\n"))!;
+ for (const said of ["OpenCode Go weekly usage limit reached", "Internal error: GoUsageLimitError: the Go allowance is used up"]) {
- const facts = openCodeLimitFacts(said, "opencode-go/minimax-m3");
++ const facts = openCodeLimitFacts(said, "opencode-go/minimax-m3", catalog);
+ expect(facts.limit, said).toBe("model");
+ 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"), "a limit met by another model still holds the account")
++ 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" });
+ });
+
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");
diff --cc server/drivers/acp/opencode-go.ts
index e29ea1b4d2,8431d5ac93..8a9237ab8c
--- a/server/drivers/acp/opencode-go.ts
+++ b/server/drivers/acp/opencode-go.ts
@@@ -657,81 -651,100 +651,100 @@@ const support =
loadCatalog: OpenCodeCatalogLoader,
ownAccess = new Map<string, boolean>(),
sources: OpenCodeModelSources = {},
- ): AcpSupport => ({
- driverKind: "opencodeGo",
- displayName: "OpenCode",
- models: NO_MODELS,
- defaultCli: "opencode",
- nativeSource: "opencode.acp",
- loginNote: "OpenCode has no usable models. Add an OpenCode key in Settings → API keys.",
- install: {
- command: {
- darwin: "npm install -g @opencode/cli",
- linux: "npm install -g @opencode/cli",
- win32: "npm install -g @opencode/cli",
+ ): AcpSupport => {
+ let priceCatalog: ModelCatalog | undefined;
+ let generation = 0;
+ const discover: OpenCodeCatalogLoader = async (...args) => {
+ const started = generation;
+ const catalog = await loadCatalog(...args);
+ if (started === generation) priceCatalog = catalog;
+ return catalog;
+ };
+ return {
+ driverKind: "opencodeGo",
+ displayName: "OpenCode",
+ models: NO_MODELS,
+ defaultCli: "opencode",
+ nativeSource: "opencode.acp",
+ loginNote: "OpenCode has no usable models. Add an OpenCode key in Settings → API keys.",
+ install: {
+ command: {
+ darwin: "npm install -g @opencode/cli",
+ linux: "npm install -g @opencode/cli",
+ win32: "npm install -g @opencode/cli",
+ },
+ docsUrl: "https://opencode.ai/docs/",
+ signInCommand: "opencode auth login",
+ needsNode: true,
+ standalone: OPENCODE_STANDALONE,
},
- docsUrl: "https://opencode.ai/docs/",
- signInCommand: "opencode auth login",
- needsNode: true,
- standalone: OPENCODE_STANDALONE,
- },
- spawnArgs: () => ["acp"],
- statusLog: { path: openCodeLogPath, parse: parseOpenCodeLogLine, shared: true },
- // A folder outside git files its session under OpenCode's global project, which every non-git folder of the person's
- // shares: a connection check or memory upkeep would show up in their history there.
- oneShotFolder: discoveryDirectory,
- shareProcess: true,
- credentialEnv: ["OPENCODE_API_KEY", ...OPENCODE_PROVIDER_ENV],
- selectModel: { configId: "model" },
- fallbackModel: (sessionConfig, catalogDefault) => {
- const offered = offeredModels(sessionConfig, "model");
- if (catalogDefault && offered.includes(catalogDefault)) return catalogDefault;
- return preferredOpenCodeModel(offered, catalogFromOpenCodeSession(sessionConfig)?.current) || null;
- },
- modelVariants: true,
- ownMcpOverHttp: true,
- // OpenCode 1.18.27's build agent lists 13 tools of its own (bash, read, edit, task, skill…); room for a newer CLI's.
- engineTools: 24,
- resolveTurnModel: (model, env, catalog) => model ? declareTypedOpenCodeModel(env, model, catalog.options) ?? ensureOpenCodeInjectModel(model, env) : model,
- transformEnv: (env, config, instanceId, instanceEnvironment) => {
- withholdProviderKeysWhenManaged(env, config, instanceId, instanceEnvironment);
- declareLiveOpenCodeModels(env, sources.liveLists);
- applyStandaloneSpawnEnv(OPENCODE_STANDALONE, env, config.cli);
- },
- spawnFingerprint: (env, config) => openCodeSpawnFingerprint(env, config.cli),
- applyTurnEnv: (env, { fullAuto, botId, cwd }) => {
- if (openMausOwnsWorkingFolder(cwd)) env.OPENCODE_DISABLE_PROJECT_CONFIG = "1";
- if (!fullAuto) {
- allowOwnedDirectories(env, botId, cwd);
- return;
- }
- // A wildcard alone leaves OpenCode's more-specific external-directory and read rules in place.
- env.OPENCODE_PERMISSION = JSON.stringify(Object.fromEntries([
- "*", "external_directory", "read", "edit", "bash", "glob", "grep",
- "list", "task", "lsp", "skill", "webfetch", "websearch", "codesearch",
- "todoread", "todowrite", "doom_loop",
- ].map((permission) => [permission, "allow"])));
- },
- pickAuthMethod: () => null,
- authFailure: "continue",
- isAuthenticated: async (env, config, instanceId, allowEnv) => {
- ownAccess.set(instanceId, ownOpenCodeAccess(env));
- return Boolean(env.OPENCODE_API_KEY)
- || hasStoredOpenCodeAuth(env)
- || await canRunOpenCode(env, config.cli, loadCatalog, allowEnv);
- },
- classifyError: classifyOpenCodeError,
- promptUnreachedModel: openCodePromptUnreachedModel,
- limitFacts: openCodeLimitFacts,
- describeAccountError: describeOpenCodeAccountError,
- resolveModels: async (environment, config, instanceId, fresh, allowEnv) => {
- if (fresh) markOpenCodeCatalogRefreshed(instanceId, (sources.now ?? Date.now)());
- await refreshLiveModelLists(environment, { lists: sources.liveLists, fetch: sources.fetch, now: sources.now });
- declareLiveOpenCodeModels(environment, sources.liveLists);
- return mergeLocalInject(await loadCatalog(environment, config.cli, { refresh: fresh === true, allowEnv }), environment);
- },
- buildPromptText: (turn) => turn.system ? `${turn.system}\n\n${turn.text}` : turn.text,
- });
+ spawnArgs: () => ["acp"],
+ statusLog: { path: openCodeLogPath, parse: parseOpenCodeLogLine, shared: true },
+ // A folder outside git files its session under OpenCode's global project, which every non-git folder of the person's
+ // shares: a connection check or memory upkeep would show up in their history there.
+ oneShotFolder: discoveryDirectory,
+ shareProcess: true,
+ credentialEnv: ["OPENCODE_API_KEY", ...OPENCODE_PROVIDER_ENV],
+ selectModel: { configId: "model" },
+ fallbackModel: (sessionConfig, catalogDefault) => {
+ const offered = offeredModels(sessionConfig, "model");
+ if (catalogDefault && offered.includes(catalogDefault)) return catalogDefault;
+ return preferredOpenCodeModel(offered, catalogFromOpenCodeSession(sessionConfig)?.current, priceCatalog) || null;
+ },
+ modelVariants: true,
+ ownMcpOverHttp: true,
+ // OpenCode 1.18.27's build agent lists 13 tools of its own (bash, read, edit, task, skill…); room for a newer CLI's.
+ engineTools: 24,
- resolveTurnModel: (model, env) => model ? declareTypedOpenCodeModel(env, model) ?? ensureOpenCodeInjectModel(model, env) : model,
++ resolveTurnModel: (model, env, catalog) => model ? declareTypedOpenCodeModel(env, model, catalog.options) ?? ensureOpenCodeInjectModel(model, env) : model,
+ transformEnv: (env, config, instanceId, instanceEnvironment) => {
+ withholdProviderKeysWhenManaged(env, config, instanceId, instanceEnvironment);
+ declareLiveOpenCodeModels(env, sources.liveLists);
+ applyStandaloneSpawnEnv(OPENCODE_STANDALONE, env, config.cli);
+ },
+ spawnFingerprint: (env, config) => openCodeSpawnFingerprint(env, config.cli),
+ applyTurnEnv: (env, { fullAuto, botId, cwd }) => {
+ if (openMausOwnsWorkingFolder(cwd)) env.OPENCODE_DISABLE_PROJECT_CONFIG = "1";
+ if (!fullAuto) {
+ allowOwnedDirectories(env, botId, cwd);
+ return;
+ }
+ // A wildcard alone leaves OpenCode's more-specific external-directory and read rules in place.
+ env.OPENCODE_PERMISSION = JSON.stringify(Object.fromEntries([
+ "*", "external_directory", "read", "edit", "bash", "glob", "grep",
+ "list", "task", "lsp", "skill", "webfetch", "websearch", "codesearch",
+ "todoread", "todowrite", "doom_loop",
+ ].map((permission) => [permission, "allow"])));
+ },
+ pickAuthMethod: () => null,
+ authFailure: "continue",
+ isAuthenticated: async (env, config, instanceId, allowEnv) => {
+ ownAccess.set(instanceId, ownOpenCodeAccess(env));
+ return Boolean(env.OPENCODE_API_KEY)
+ || hasStoredOpenCodeAuth(env)
+ || await canRunOpenCode(env, config.cli, discover, allowEnv);
+ },
+ classifyError: classifyOpenCodeError,
+ promptUnreachedModel: openCodePromptUnreachedModel,
+ limitFacts: (text, model) => openCodeLimitFacts(text, model, priceCatalog),
+ describeAccountError: describeOpenCodeAccountError,
+ resolveModels: async (environment, config, instanceId, fresh, allowEnv) => {
+ priceCatalog = undefined;
+ generation++;
+ let catalog: ModelCatalog | undefined;
+ try {
+ if (fresh) markOpenCodeCatalogRefreshed(instanceId, (sources.now ?? Date.now)());
+ await refreshLiveModelLists(environment, { lists: sources.liveLists, fetch: sources.fetch, now: sources.now });
+ declareLiveOpenCodeModels(environment, sources.liveLists);
+ catalog = await loadCatalog(environment, config.cli, { refresh: fresh === true, allowEnv });
+ return mergeLocalInject(catalog, environment);
+ } finally {
+ generation++;
+ priceCatalog = catalog;
+ }
+ },
+ buildPromptText: (turn) => turn.system ? `${turn.system}\n\n${turn.text}` : turn.text,
+ };
+ };
/** OpenCode 1.18 reports a provider's account refusal as a JSON-RPC internal error wrapping an APIError:
* `{code: -32603, message: "Internal error: Invalid API key.", data: {service: "session", errorName: "APIError"}}`. */
@@@ -748,20 -761,14 +761,23 @@@ const ACCOUNT_ERROR_TEXT: ReadonlyArray
* 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), or the whole account. */
+ * allowance holds), the Go subscription's models, or the whole account. */
- export function openCodeLimitFacts(text: string, model?: string): { limit: "engine" | "model"; limitModels?: string[] } {
+ export function openCodeLimitFacts(text: string, model?: string, catalog?: ModelCatalog): { limit: "engine" | "model"; limitModels?: string[] } {
- if (!FREE_MODEL_LIMIT.test(text)) return { limit: "engine" };
+ if (!FREE_MODEL_LIMIT.test(text)) {
+ if (!model?.startsWith(GO_PROVIDER)) return { limit: "engine" };
- const listed = [...lastSuccessfulCatalog.values()].flatMap((catalog) => catalog.options.map((option) => option.id));
- return { limit: "model", limitModels: [...new Set([model, ...paidModels, ...listed].filter((id) => id.startsWith(GO_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(GO_PROVIDER)))] };
+ }
const provider = model?.includes("/") ? model.slice(0, model.indexOf("/")) : "";
- const shared = provider ? [...freeModels].filter((id) => id.startsWith(`${provider}/`)) : [];
+ 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)];
return models.length > 1 ? { limit: "model", limitModels: models } : { limit: "model" };
}