Skip to content

Commit 7513255

Browse files
JustMarkDevclaude
andcommitted
fix(server): read OpenCode Go limits key from OpenCode 2's credential database
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
1 parent f4f148e commit 7513255

3 files changed

Lines changed: 72 additions & 2 deletions

File tree

‎apps/server/src/provider/OpenCodeProvider.test.ts‎

Lines changed: 42 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,47 @@ it.effect("reads Go limits with the instance's XDG credentials and preserves res
9899
}),
99100
);
100101

102+
it.effect("reads a Go API key from OpenCode 2's credential database", () =>
103+
Effect.gen(function* () {
104+
const fs = yield* FileSystem.FileSystem;
105+
const dataHome = yield* fs.makeTempDirectoryScoped();
106+
yield* fs.makeDirectory(`${dataHome}/opencode`);
107+
const database = new NodeSqlite.DatabaseSync(`${dataHome}/opencode/opencode.db`);
108+
database.exec(
109+
"CREATE TABLE credential (integration_id text, value text, active integer, time_updated integer)",
110+
);
111+
const insert = database.prepare("INSERT INTO credential VALUES (?, ?, ?, ?)");
112+
// A Console login and an inactive Go key must lose to the active Go key.
113+
insert.run("opencode", JSON.stringify({ type: "oauth", access: "console-token" }), 1, 3);
114+
insert.run("opencode-go", JSON.stringify({ type: "api", key: "old-key" }), 0, 2);
115+
insert.run("opencode-go", JSON.stringify({ type: "api", key: "db-key" }), 1, 1);
116+
database.close();
117+
118+
const resetsAt = "2026-09-17T12:00:00.000Z";
119+
const window = { percent: 1, resetsAt };
120+
const limits = yield* readOpenCodeGoUsageLimits({
121+
enabled: true,
122+
serverUrl: "",
123+
environment: { XDG_DATA_HOME: dataHome, OPENCODE_API_KEY: "env-key" },
124+
}).pipe(
125+
Effect.provideService(
126+
HttpClient.HttpClient,
127+
HttpClient.make((request) => {
128+
NodeAssert.equal(request.headers.authorization, "Bearer db-key");
129+
return Effect.succeed(
130+
HttpClientResponse.fromWeb(
131+
request,
132+
Response.json({ usage: { rolling: window, weekly: window, monthly: window } }),
133+
),
134+
);
135+
}),
136+
),
137+
);
138+
NodeAssert.equal(limits.unavailable, undefined);
139+
NodeAssert.equal(limits.windows.length, 3);
140+
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
141+
);
142+
101143
it.effect("does not read local credentials for external or disabled OpenCode instances", () =>
102144
Effect.gen(function* () {
103145
for (const settings of [

‎apps/server/src/provider/openCodeUsageLimits.ts‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import * as NodeOS from "node:os";
2+
import * as NodeSqlite from "node:sqlite";
23

34
import type { ServerProviderUsageWindow } from "@t3tools/contracts";
45
import * as Crypto from "effect/Crypto";
@@ -29,6 +30,29 @@ const UsageResponse = Schema.Struct({
2930
usage: Schema.Struct({ rolling: UsageWindow, weekly: UsageWindow, monthly: UsageWindow }),
3031
});
3132

33+
/**
34+
* OpenCode 2 stores credentials in its SQLite database instead of auth.json. A
35+
* Console login is a separate OAuth row under another integration, so only a
36+
* Go API key row is usable here.
37+
*/
38+
const readStoredGoApiKey = (databasePath: string) =>
39+
Effect.try(() => {
40+
const database = new NodeSqlite.DatabaseSync(databasePath, { readOnly: true });
41+
try {
42+
database.exec("PRAGMA busy_timeout = 100");
43+
const row = database
44+
.prepare(
45+
"SELECT value FROM credential WHERE integration_id = 'opencode-go' ORDER BY active DESC, time_updated DESC LIMIT 1",
46+
)
47+
.get();
48+
return typeof row?.value === "string"
49+
? decodeApiAuth(JSON.parse(row.value) as unknown)
50+
: Option.none();
51+
} finally {
52+
database.close();
53+
}
54+
}).pipe(Effect.orElseSucceed(() => Option.none<typeof ApiAuth.Type>()));
55+
3256
/** External OpenCode servers own their credentials; never read the host's account for them. */
3357
export const readOpenCodeGoUsageLimits = Effect.fn("readOpenCodeGoUsageLimits")(function* (input: {
3458
readonly enabled: boolean;
@@ -56,7 +80,10 @@ export const readOpenCodeGoUsageLimits = Effect.fn("readOpenCodeGoUsageLimits")(
5680
}),
5781
));
5882
const auth = yield* decodeAuthFile(contents);
59-
const apiAuth = decodeApiAuth(auth["opencode-go"]);
83+
const fileAuth = decodeApiAuth(auth["opencode-go"]);
84+
const apiAuth = Option.isSome(fileAuth)
85+
? fileAuth
86+
: yield* readStoredGoApiKey(path.join(dataHome, "opencode", "opencode.db"));
6087
// OpenCode overlays stored API credentials after environment credentials.
6188
const apiKey = (Option.isSome(apiAuth) ? apiAuth.value.key : env.OPENCODE_API_KEY)?.trim();
6289
if (!apiKey) return unsupported;

‎docs/user/usage.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,8 @@ closes when you dismiss it or send your next message. It uses the same snapshot
100100
anything. The command is offered only for providers that appear under **Usage → Limits**.
101101

102102
OpenCode Go reports its session, weekly, and monthly allowance when OpenCode runs locally in
103-
the environment. T3 cannot report limits for external OpenCode servers because their credentials
103+
the environment and has a Go API key, either saved in OpenCode or set as `OPENCODE_API_KEY`.
104+
Signing in with the OpenCode Console alone is not enough. T3 cannot report limits for external OpenCode servers because their credentials
104105
belong to the remote server. Cursor reports
105106
its monthly allowance, including separate Auto and API usage, using the CLI login or
106107
`CURSOR_AUTH_TOKEN`. On macOS, this includes the default Keychain login after you enable Cursor

0 commit comments

Comments
 (0)