@devries-cameron20 / t3code Mirror · read-only / commits / f04546609a
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 23:15 UTC

fix(server): restore OpenCode Go limits for Console API keys (#21007)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

Ben committed Oct 20, 2026 at 06:05 UTC f04546609a0600bd6b878baca0dae75b191f7d35
3 files changed +197 -9
docs/user/usage.md
+4 -3
@@ -113,9 +113,10 @@ anything. The command is offered only for providers that appear under **Usage
113
114 OpenCode Go reports its session, weekly, and monthly allowance when OpenCode runs locally in
115 the environment. T3 cannot report limits for external OpenCode servers because their credentials
116 -belong to the remote server. Limits need an OpenCode Go API key. A Console sign-in alone
117 -does not report them. Add your Go API key as `OPENCODE_API_KEY` in the OpenCode instance's
118 -**Environment variables**, then refresh provider status. Cursor reports
116 +belong to the remote server. Limits need an OpenCode Go API key, or an OpenCode Console connected
117 +in OpenCode with an API key. A Console browser sign-in alone does not report them. You can also add
118 +your Go API key as `OPENCODE_API_KEY` in the OpenCode instance's **Environment variables**, then
119 +refresh provider status. Cursor reports
120 its monthly allowance, including separate Auto and API usage, using the CLI login or
121 `CURSOR_AUTH_TOKEN`. On macOS, this includes the default Keychain login after you enable Cursor
122 usage. Keychain login is used for limits only with Cursor's default API endpoint. If you configure
packages/provider-opencode/src/server/status.test.ts
+132
@@ -1,4 +1,5 @@
1 import * as NodeAssert from "node:assert/strict";
2 +import * as NodeSqlite from "node:sqlite";
3
4 import * as NodeServices from "@effect/platform-node/NodeServices";
5 import { it } from "@effect/vitest";
@@ -98,6 +99,137 @@ it.effect("reads Go limits with the instance's XDG credentials and preserves res
99 }),
100 );
101
102 +it.effect(
103 + "uses the selected public Console key for Go limits, falling back only on auth rejection",
104 + () =>
105 + Effect.gen(function* () {
106 + const fs = yield* FileSystem.FileSystem;
107 + const dataHome = yield* fs.makeTempDirectoryScoped();
108 + yield* fs.makeDirectory(`${dataHome}/opencode`);
109 + yield* fs.writeFileString(
110 + `${dataHome}/opencode/auth.json`,
111 + JSON.stringify({ "opencode-go": { type: "api", key: "go-key" } }),
112 + );
113 + const database = yield* Effect.acquireRelease(
114 + Effect.sync(() => new NodeSqlite.DatabaseSync(`${dataHome}/opencode/opencode.db`)),
115 + (database) => Effect.sync(() => database.close()),
116 + );
117 + database.exec(
118 + "CREATE TABLE credential (id text PRIMARY KEY, integration_id text, value text, active integer, time_created integer, time_updated integer)",
119 + );
120 + const insert = database.prepare("INSERT INTO credential VALUES (?, ?, ?, ?, ?, ?)");
121 + const window = { percent: 1, resetsAt: "2026-09-17T12:00:00.000Z" };
122 + const consoleKey = { type: "key", key: "console-key" };
123 + const fingerprints = new Map([
124 + ["console-key", "3e45cfde9158185930d4cc7020a4e390895574fd54bd8f9631d23a336bbf94f0"],
125 + ["go-key", "d0e590e93fc9bd9353f2b993c0c287391cae505da2a78cb698b75418d2f5367e"],
126 + ["inline-key", "85649de18e63305548b6407e185f708483727ee6189cc4bc9512ddb17e23e776"],
127 + ]);
128 + for (const {
129 + consoleRow = consoleKey,
130 + active = 1,
131 + consoleStatus = 200,
132 + inline = false,
133 + databaseFile,
134 + requested,
135 + } of [
136 + {
137 + consoleRow: { ...consoleKey, metadata: { server: "https://opencode.ai/console" } },
138 + requested: ["console-key"],
139 + },
140 + { consoleStatus: 401, requested: ["console-key", "go-key"] },
141 + { consoleStatus: 403, requested: ["console-key", "go-key"] },
142 + { consoleStatus: 500, requested: ["console-key"] },
143 + { active: 0, requested: ["go-key"] },
144 + {
145 + consoleRow: {
146 + type: "oauth",
147 + methodID: "device",
148 + access: "token",
149 + refresh: "refresh",
150 + expires: 0,
151 + },
152 + requested: ["go-key"],
153 + },
154 + {
155 + consoleRow: { ...consoleKey, metadata: { server: "https://console.example" } },
156 + requested: ["go-key"],
157 + },
158 + { inline: true, requested: ["inline-key"] },
159 + { databaseFile: "selected.db", requested: ["console-key"] },
160 + { databaseFile: ":memory:", requested: ["go-key"] },
161 + { active: null, requested: ["console-key"] },
162 + ]) {
163 + database.exec("DELETE FROM credential");
164 + insert.run("cred_selected", "opencode", JSON.stringify(consoleRow), active, 2, 2);
165 + // Legacy selections follow creation order, even when an older key was updated later.
166 + insert.run(
167 + "cred_older",
168 + "opencode",
169 + JSON.stringify({ type: "key", key: "old-key" }),
170 + active === null ? null : 0,
171 + 1,
172 + 9,
173 + );
174 + insert.run("cred_other", "other", JSON.stringify(consoleKey), 1, 10, 10);
175 + if (databaseFile === "selected.db") {
176 + yield* fs.writeFile(
177 + `${dataHome}/opencode/selected.db`,
178 + yield* fs.readFile(`${dataHome}/opencode/opencode.db`),
179 + );
180 + database
181 + .prepare("UPDATE credential SET value = ? WHERE id = 'cred_selected'")
182 + .run(JSON.stringify({ type: "key", key: "old-key" }));
183 + }
184 + const before = yield* fs.readFile(`${dataHome}/opencode/opencode.db`);
185 + const authorizations: string[] = [];
186 + const limits = yield* readOpenCodeGoUsageLimits({
187 + enabled: true,
188 + serverUrl: "",
189 + environment: {
190 + XDG_DATA_HOME: dataHome,
191 + ...(databaseFile !== undefined ? { OPENCODE_DB: databaseFile } : {}),
192 + ...(inline
193 + ? { OPENCODE_AUTH_CONTENT: '{"opencode-go":{"type":"api","key":"inline-key"}}' }
194 + : {}),
195 + },
196 + }).pipe(
197 + Effect.provideService(
198 + HttpClient.HttpClient,
199 + HttpClient.make((request) => {
200 + NodeAssert.equal(request.url, "https://opencode.ai/zen/go/v1/usage");
201 + const key = (request.headers.authorization ?? "").replace("Bearer ", "");
202 + authorizations.push(key);
203 + // The legacy key is expired in the regression; it only works in fallback scenarios.
204 + const status =
205 + key === "console-key" ? consoleStatus : requested.includes(key) ? 200 : 401;
206 + return Effect.succeed(
207 + HttpClientResponse.fromWeb(
208 + request,
209 + Response.json(
210 + { usage: { rolling: window, weekly: window, monthly: window } },
211 + { status },
212 + ),
213 + ),
214 + );
215 + }),
216 + ),
217 + );
218 + NodeAssert.deepEqual(authorizations, requested);
219 + NodeAssert.deepEqual(yield* fs.readFile(`${dataHome}/opencode/opencode.db`), before);
220 + NodeAssert.equal(
221 + limits.unavailable?.reason,
222 + consoleStatus === 500 ? "probeFailed" : undefined,
223 + );
224 + NodeAssert.equal(limits.windows.length, consoleStatus === 500 ? 0 : 3);
225 + NodeAssert.equal(
226 + limits.credentialFingerprint,
227 + consoleStatus === 500 ? undefined : fingerprints.get(requested.at(-1)!),
228 + );
229 + }
230 + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
231 +);
232 +
233 it.effect("does not read local credentials for external or disabled OpenCode instances", () =>
234 Effect.gen(function* () {
235 for (const settings of [
packages/provider-opencode/src/server/usageLimits.ts
+61 -6
@@ -1,3 +1,5 @@
1 +import * as NodeSqlite from "node:sqlite";
2 +
3 import type { ServerProviderUsageWindow } from "@t3tools/contracts";
4 import * as Crypto from "effect/Crypto";
5 import * as DateTime from "effect/DateTime";
@@ -22,6 +24,15 @@ const AuthFile = Schema.Struct({ "opencode-go": Schema.optionalKey(Schema.Unknow
24 const ApiAuth = Schema.Struct({ type: Schema.Literal("api"), key: Schema.String });
25 const decodeAuthFile = Schema.decodeEffect(Schema.fromJsonString(AuthFile));
26 const decodeApiAuth = Schema.decodeUnknownOption(ApiAuth);
27 +// OpenCode 2's database tags a stored key "key"; auth.json tags it "api".
28 +const StoredKey = Schema.Struct({
29 + type: Schema.Literal("key"),
30 + key: Schema.String,
31 + metadata: Schema.optionalKey(
32 + Schema.NullOr(Schema.Struct({ server: Schema.optionalKey(Schema.Unknown) })),
33 + ),
34 +});
35 +const decodeStoredKey = Schema.decodeOption(Schema.fromJsonString(StoredKey));
36 const UsageWindow = Schema.Struct({
37 percent: Schema.Finite,
38 resetsAt: Schema.DateTimeUtcFromString,
@@ -30,6 +41,36 @@ const UsageResponse = Schema.Struct({
41 usage: Schema.Struct({ rolling: UsageWindow, weekly: UsageWindow, monthly: UsageWindow }),
42 });
43
44 +// Select before decoding so an OAuth or self-hosted connection cannot fall
45 +// through to another stored account. NULL-active rows predate the selection flag.
46 +const readConsoleApiKey = (databasePath: string) =>
47 + Effect.try(() => {
48 + const database = new NodeSqlite.DatabaseSync(databasePath, { readOnly: true });
49 + try {
50 + database.exec("PRAGMA busy_timeout = 100");
51 + const row = database
52 + .prepare(
53 + `SELECT value FROM credential
54 + WHERE integration_id = 'opencode' AND active IS NOT 0
55 + ORDER BY active DESC, time_created DESC, id DESC LIMIT 1`,
56 + )
57 + .get();
58 + const stored =
59 + typeof row?.value === "string"
60 + ? Option.getOrUndefined(decodeStoredKey(row.value))
61 + : undefined;
62 + const server = stored?.metadata?.server;
63 + if (typeof server === "string") {
64 + const url = new URL(server);
65 + if (`${url.origin}${url.pathname.replace(/\/+$/, "")}` !== "https://opencode.ai/console")
66 + return undefined;
67 + }
68 + return stored?.key.trim();
69 + } finally {
70 + database.close();
71 + }
72 + }).pipe(Effect.orElseSucceed(() => undefined));
73 +
74 /** External OpenCode servers own their credentials; never read the host's account for them. */
75 export const readOpenCodeGoUsageLimits = Effect.fn("readOpenCodeGoUsageLimits")(function* (input: {
76 readonly enabled: boolean;
@@ -63,15 +104,29 @@ export const readOpenCodeGoUsageLimits = Effect.fn("readOpenCodeGoUsageLimits")(
104 const auth = yield* decodeAuthFile(contents);
105 const apiAuth = decodeApiAuth(auth["opencode-go"]);
106 // OpenCode overlays stored API credentials after environment credentials.
66 - const apiKey = (Option.isSome(apiAuth) ? apiAuth.value.key : env.OPENCODE_API_KEY)?.trim();
107 + const goKey = (Option.isSome(apiAuth) ? apiAuth.value.key : env.OPENCODE_API_KEY)?.trim();
108 + // Console supplies Go credentials in OpenCode 2. Inline auth explicitly
109 + // overrides local credentials, including the Console connection.
110 + const databaseFile = env.OPENCODE_DB ?? "opencode.db";
111 + const consoleKey =
112 + env.OPENCODE_AUTH_CONTENT || databaseFile === ":memory:"
113 + ? undefined
114 + : yield* readConsoleApiKey(path.resolve(dataHome, "opencode", databaseFile));
115 + let apiKey = consoleKey || goKey;
116 if (!apiKey) return unsupported;
117
118 const client = yield* HttpClient.HttpClient;
70 - const response = yield* client.execute(
71 - HttpClientRequest.get("https://opencode.ai/zen/go/v1/usage").pipe(
72 - HttpClientRequest.bearerToken(apiKey),
73 - ),
74 - );
119 + const readUsage = (key: string) =>
120 + client.execute(
121 + HttpClientRequest.get("https://opencode.ai/zen/go/v1/usage").pipe(
122 + HttpClientRequest.bearerToken(key),
123 + ),
124 + );
125 + let response = yield* readUsage(apiKey);
126 + if ((response.status === 401 || response.status === 403) && goKey && goKey !== apiKey) {
127 + apiKey = goKey;
128 + response = yield* readUsage(apiKey);
129 + }
130 // A valid Zen key can exist without a Go subscription.
131 if (response.status === 403) return unsupported;
132 const body = yield* HttpClientResponse.filterStatusOk(response).pipe(