Skip to content

Commit f045466

Browse files
fix(server): restore OpenCode Go limits for Console API keys (pingdotgg#21007)
Co-authored-by: Julius Marminge <[email protected]>
1 parent 45bcde1 commit f045466

3 files changed

Lines changed: 197 additions & 9 deletions

File tree

‎docs/user/usage.md‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -113,9 +113,10 @@ anything. The command is offered only for providers that appear under **Usage
113113

114114
OpenCode Go reports its session, weekly, and monthly allowance when OpenCode runs locally in
115115
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
119120
its monthly allowance, including separate Auto and API usage, using the CLI login or
120121
`CURSOR_AUTH_TOKEN`. On macOS, this includes the default Keychain login after you enable Cursor
121122
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‎

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import * as NodeAssert from "node:assert/strict";
2+
import * as NodeSqlite from "node:sqlite";
23

34
import * as NodeServices from "@effect/platform-node/NodeServices";
45
import { it } from "@effect/vitest";
@@ -98,6 +99,137 @@ it.effect("reads Go limits with the instance's XDG credentials and preserves res
9899
}),
99100
);
100101

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+
101233
it.effect("does not read local credentials for external or disabled OpenCode instances", () =>
102234
Effect.gen(function* () {
103235
for (const settings of [

‎packages/provider-opencode/src/server/usageLimits.ts‎

Lines changed: 61 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import * as NodeSqlite from "node:sqlite";
2+
13
import type { ServerProviderUsageWindow } from "@t3tools/contracts";
24
import * as Crypto from "effect/Crypto";
35
import * as DateTime from "effect/DateTime";
@@ -22,6 +24,15 @@ const AuthFile = Schema.Struct({ "opencode-go": Schema.optionalKey(Schema.Unknow
2224
const ApiAuth = Schema.Struct({ type: Schema.Literal("api"), key: Schema.String });
2325
const decodeAuthFile = Schema.decodeEffect(Schema.fromJsonString(AuthFile));
2426
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));
2536
const UsageWindow = Schema.Struct({
2637
percent: Schema.Finite,
2738
resetsAt: Schema.DateTimeUtcFromString,
@@ -30,6 +41,36 @@ const UsageResponse = Schema.Struct({
3041
usage: Schema.Struct({ rolling: UsageWindow, weekly: UsageWindow, monthly: UsageWindow }),
3142
});
3243

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+
3374
/** External OpenCode servers own their credentials; never read the host's account for them. */
3475
export const readOpenCodeGoUsageLimits = Effect.fn("readOpenCodeGoUsageLimits")(function* (input: {
3576
readonly enabled: boolean;
@@ -63,15 +104,29 @@ export const readOpenCodeGoUsageLimits = Effect.fn("readOpenCodeGoUsageLimits")(
63104
const auth = yield* decodeAuthFile(contents);
64105
const apiAuth = decodeApiAuth(auth["opencode-go"]);
65106
// 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;
67116
if (!apiKey) return unsupported;
68117

69118
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+
}
75130
// A valid Zen key can exist without a Go subscription.
76131
if (response.status === 403) return unsupported;
77132
const body = yield* HttpClientResponse.filterStatusOk(response).pipe(

0 commit comments

Comments
 (0)