Skip to content

Commit b11b757

Browse files
onlydoleclaude
andcommitted
fix(opencode): Go limits use the OpenCode Console sign-in
Usage → Limits read only a Go API key or a Console API key. An OpenCode 2 Console sign-in (`opencode auth login`) is stored as an OAuth row, so the probe skipped it and fell back to the separate Go key, which is often an expired key imported from auth.json. Limits then showed nothing or "could not read usage" while OpenCode itself worked. The probe now sends the active Console sign-in's access token to the same Go usage endpoint, falls back to the Go key on 401/403, and still ignores self-hosted Consoles. Both public Console addresses count as public. The fingerprint for a sign-in hashes the account and organization IDs, so one account signed in on several devices merges into one Limits row. T3 never refreshes the token; OpenCode owns renewal. Fixes #14983 Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 3b95e78 commit b11b757

3 files changed

Lines changed: 103 additions & 30 deletions

File tree

‎docs/user/usage.md‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -113,10 +113,11 @@ 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, 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
116+
belong to the remote server. Limits use the OpenCode Console account you signed in to with
117+
`opencode auth login`, or an OpenCode Go API key. OpenCode renews the sign-in while it runs; if
118+
limits stop appearing, sign in again. You can also add your Go API key as
119+
`OPENCODE_API_KEY` in the OpenCode instance's **Environment variables**, then refresh provider
120+
status. Cursor reports
120121
its monthly allowance, including separate Auto and API usage, using the CLI login or
121122
`CURSOR_AUTH_TOKEN`. On macOS, this includes the default Keychain login after you enable Cursor
122123
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: 46 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -114,15 +114,34 @@ it.effect(
114114
const insert = database.prepare("INSERT INTO credential VALUES (?, ?, ?, ?, ?, ?)");
115115
const window = { percent: 1, resetsAt: "2026-09-17T12:00:00.000Z" };
116116
const consoleKey = { type: "key", key: "console-key" };
117+
const consoleLogin = {
118+
type: "oauth",
119+
methodID: "device",
120+
access: "console-token",
121+
refresh: "refresh",
122+
expires: 0,
123+
metadata: {
124+
server: "https://opencode.ai/console",
125+
accountID: "acc_1",
126+
127+
orgID: "org_1",
128+
orgName: "Org",
129+
},
130+
};
131+
const consoleAccount = "4c1ad3b022b414b769bf373c1fa50a36e1704129d036b9d1a9fe4cde9999e87e";
117132
const fingerprints = new Map([
118133
["console-key", "3e45cfde9158185930d4cc7020a4e390895574fd54bd8f9631d23a336bbf94f0"],
119134
["go-key", "d0e590e93fc9bd9353f2b993c0c287391cae505da2a78cb698b75418d2f5367e"],
120135
["inline-key", "85649de18e63305548b6407e185f708483727ee6189cc4bc9512ddb17e23e776"],
136+
// Each device signs in separately, so one account must not split by token.
137+
["console-token", consoleAccount],
138+
["other-device-token", consoleAccount],
121139
]);
122140
for (const {
123141
consoleRow = consoleKey,
124142
active = 1,
125143
consoleStatus = 200,
144+
rejected,
126145
inline = false,
127146
databaseFile,
128147
requested,
@@ -135,13 +154,28 @@ it.effect(
135154
{ consoleStatus: 403, requested: ["console-key", "go-key"] },
136155
{ consoleStatus: 500, requested: ["console-key"] },
137156
{ active: 0, requested: ["go-key"] },
157+
{ consoleRow: consoleLogin, requested: ["console-token"] },
158+
{
159+
consoleRow: { ...consoleLogin, access: "other-device-token" },
160+
requested: ["other-device-token"],
161+
},
162+
{
163+
// Earlier OpenCode 2 releases signed in through this address.
164+
consoleRow: {
165+
...consoleLogin,
166+
metadata: { ...consoleLogin.metadata, server: "https://console.opencode.ai/" },
167+
},
168+
requested: ["console-token"],
169+
},
170+
{
171+
consoleRow: consoleLogin,
172+
rejected: "console-token",
173+
requested: ["console-token", "go-key"],
174+
},
138175
{
139176
consoleRow: {
140-
type: "oauth",
141-
methodID: "device",
142-
access: "token",
143-
refresh: "refresh",
144-
expires: 0,
177+
...consoleLogin,
178+
metadata: { ...consoleLogin.metadata, server: "https://console.example" },
145179
},
146180
requested: ["go-key"],
147181
},
@@ -196,7 +230,13 @@ it.effect(
196230
authorizations.push(key);
197231
// The legacy key is expired in the regression; it only works in fallback scenarios.
198232
const status =
199-
key === "console-key" ? consoleStatus : requested.includes(key) ? 200 : 401;
233+
key === rejected
234+
? 401
235+
: key === "console-key"
236+
? consoleStatus
237+
: requested.includes(key)
238+
? 200
239+
: 401;
200240
return Effect.succeed(
201241
HttpClientResponse.fromWeb(
202242
request,

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

Lines changed: 52 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -24,15 +24,30 @@ const AuthFile = Schema.Struct({ "opencode-go": Schema.optionalKey(Schema.Unknow
2424
const ApiAuth = Schema.Struct({ type: Schema.Literal("api"), key: Schema.String });
2525
const decodeAuthFile = Schema.decodeEffect(Schema.fromJsonString(AuthFile));
2626
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) })),
27+
const ConsoleMetadata = Schema.optionalKey(
28+
Schema.NullOr(
29+
Schema.Struct({
30+
server: Schema.optionalKey(Schema.Unknown),
31+
accountID: Schema.optionalKey(Schema.Unknown),
32+
orgID: Schema.optionalKey(Schema.Unknown),
33+
}),
3334
),
34-
});
35-
const decodeStoredKey = Schema.decodeOption(Schema.fromJsonString(StoredKey));
35+
);
36+
// OpenCode 2's database tags a stored key "key"; auth.json tags it "api".
37+
const ConsoleCredential = Schema.Union([
38+
Schema.Struct({ type: Schema.Literal("key"), key: Schema.String, metadata: ConsoleMetadata }),
39+
Schema.Struct({
40+
type: Schema.Literal("oauth"),
41+
access: Schema.String,
42+
metadata: ConsoleMetadata,
43+
}),
44+
]);
45+
const decodeConsoleCredential = Schema.decodeOption(Schema.fromJsonString(ConsoleCredential));
46+
// OpenCode 2 releases have signed in through both public Console addresses.
47+
const PUBLIC_CONSOLE_SERVERS = new Set([
48+
"https://opencode.ai/console",
49+
"https://console.opencode.ai",
50+
]);
3651
const UsageWindow = Schema.Struct({
3752
percent: Schema.Finite,
3853
resetsAt: Schema.DateTimeUtcFromString,
@@ -41,9 +56,10 @@ const UsageResponse = Schema.Struct({
4156
usage: Schema.Struct({ rolling: UsageWindow, weekly: UsageWindow, monthly: UsageWindow }),
4257
});
4358

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) =>
59+
// Select before decoding so a self-hosted connection cannot fall through to
60+
// another stored account. NULL-active rows predate the selection flag. T3 never
61+
// refreshes a sign-in: Console rotates refresh tokens, and OpenCode owns renewal.
62+
const readConsoleCredential = (databasePath: string) =>
4763
Effect.try(() => {
4864
const database = new NodeSqlite.DatabaseSync(databasePath, { readOnly: true });
4965
try {
@@ -57,15 +73,24 @@ const readConsoleApiKey = (databasePath: string) =>
5773
.get();
5874
const stored =
5975
typeof row?.value === "string"
60-
? Option.getOrUndefined(decodeStoredKey(row.value))
76+
? Option.getOrUndefined(decodeConsoleCredential(row.value))
6177
: undefined;
62-
const server = stored?.metadata?.server;
78+
if (!stored) return undefined;
79+
const { server, accountID, orgID } = stored.metadata ?? {};
6380
if (typeof server === "string") {
6481
const url = new URL(server);
65-
if (`${url.origin}${url.pathname.replace(/\/+$/, "")}` !== "https://opencode.ai/console")
82+
if (!PUBLIC_CONSOLE_SERVERS.has(`${url.origin}${url.pathname.replace(/\/+$/, "")}`))
6683
return undefined;
6784
}
68-
return stored?.key.trim();
85+
if (stored.type === "key") return { token: stored.key.trim() };
86+
return {
87+
token: stored.access.trim(),
88+
// Each device signs in with its own token, so only the account matches across environments.
89+
account:
90+
typeof accountID === "string"
91+
? `${accountID}\0${typeof orgID === "string" ? orgID : ""}`
92+
: undefined,
93+
};
6994
} finally {
7095
database.close();
7196
}
@@ -108,11 +133,11 @@ export const readOpenCodeGoUsageLimits = Effect.fn("readOpenCodeGoUsageLimits")(
108133
// Console supplies Go credentials in OpenCode 2. Inline auth explicitly
109134
// overrides local credentials, including the Console connection.
110135
const databaseFile = env.OPENCODE_DB ?? "opencode.db";
111-
const consoleKey =
136+
const consoleCredential =
112137
env.OPENCODE_AUTH_CONTENT || databaseFile === ":memory:"
113138
? undefined
114-
: yield* readConsoleApiKey(path.resolve(dataHome, "opencode", databaseFile));
115-
let apiKey = consoleKey || goKey;
139+
: yield* readConsoleCredential(path.resolve(dataHome, "opencode", databaseFile));
140+
let apiKey = consoleCredential?.token || goKey;
116141
if (!apiKey) return unsupported;
117142

118143
const client = yield* HttpClient.HttpClient;
@@ -159,9 +184,16 @@ export const readOpenCodeGoUsageLimits = Effect.fn("readOpenCodeGoUsageLimits")(
159184
];
160185
const crypto = yield* Crypto.Crypto;
161186
// An unkeyed hash matches across environments without a shared secret. It
162-
// permits offline guesses, but Go keys are randomly generated.
187+
// permits offline guesses, but Go keys are randomly generated, and a Console
188+
// sign-in hashes only account IDs, never its token.
189+
const account = apiKey === consoleCredential?.token ? consoleCredential.account : undefined;
163190
const credentialFingerprint = yield* crypto
164-
.digest("SHA-256", new TextEncoder().encode(`opencode-go\0${apiKey}`))
191+
.digest(
192+
"SHA-256",
193+
new TextEncoder().encode(
194+
account ? `opencode-go\0console\0${account}` : `opencode-go\0${apiKey}`,
195+
),
196+
)
165197
.pipe(Effect.map(Hex.encode), Effect.orDie);
166198
return {
167199
...makeUsageLimits({ checkedAt, windows }),

0 commit comments

Comments
 (0)