Open History to see the last commit
1import type { ServerProviderUsageWindow } from "@t3tools/contracts";
2import * as Crypto from "effect/Crypto";
3import * as DateTime from "effect/DateTime";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Option from "effect/Option";
7import * as Path from "effect/Path";
8import * as Schema from "effect/Schema";
9import * as Hex from "effect/encoding/Hex";
10import * as HttpClient from "effect/http/HttpClient";
11import * as HttpClientRequest from "effect/http/HttpClientRequest";
12import * as HttpClientResponse from "effect/http/HttpClientResponse";
13import * as SqlClient from "effect/sql/SqlClient";
14
15import {
16 clampPercent,
17 makeUnavailableUsageLimits,
18 makeUsageLimits,
19} from "@t3tools/provider-core/server/usageLimits";
20import * as HostProcess from "@t3tools/shared/HostProcess";
21import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
22
23const AuthFile = Schema.Struct({ "opencode-go": Schema.optionalKey(Schema.Unknown) });
24const ApiAuth = Schema.Struct({ type: Schema.Literal("api"), key: Schema.String });
25const decodeAuthFile = Schema.decodeEffect(Schema.fromJsonString(AuthFile));
26const decodeApiAuth = Schema.decodeUnknownOption(ApiAuth);
27// OpenCode 2 tags a stored key "key" where auth.json tagged it "api".
28const StoredKey = Schema.Struct({ type: Schema.Literal("key"), key: Schema.String });
29const decodeStoredKey = Schema.decodeUnknownOption(Schema.fromJsonString(StoredKey));
30const UsageWindow = Schema.Struct({
31 percent: Schema.Finite,
32 resetsAt: Schema.DateTimeUtcFromString,
33});
34const UsageResponse = Schema.Struct({
35 usage: Schema.Struct({ rolling: UsageWindow, weekly: UsageWindow, monthly: UsageWindow }),
36});
37
38/**
39 * OpenCode 2 keeps credentials in its database and selects the connection it
40 * uses by this same order: the active row, else the newest. Only a Go API key
41 * row is usable here; a Console login is an OAuth row under another integration.
42 */
43const readStoredGoApiKey = (databasePath: string) =>
44 Effect.gen(function* () {
45 const sql = yield* SqlClient.SqlClient;
46 // A busy live provider should fail this read promptly rather than stall the probe.
47 yield* sql.unsafe("PRAGMA busy_timeout = 100");
48 const [row] = yield* sql<{ readonly value: unknown }>`
49 SELECT value FROM credential WHERE integration_id = 'opencode-go'
50 ORDER BY active DESC, time_created DESC, id DESC LIMIT 1
51 `;
52 return Option.map(decodeStoredKey(row?.value), (stored) => stored.key);
53 }).pipe(
54 Effect.provide(NodeSqliteClient.layer({ filename: databasePath, readonly: true })),
55 // A missing or pre-OpenCode 2 database holds no stored key.
56 Effect.orElseSucceed(() => Option.none<string>()),
57 );
58
59/** External OpenCode servers own their credentials; never read the host's account for them. */
60export const readOpenCodeGoUsageLimits = Effect.fn("readOpenCodeGoUsageLimits")(function* (input: {
61 readonly enabled: boolean;
62 readonly serverUrl: string;
63 readonly environment: NodeJS.ProcessEnv;
64}) {
65 const checkedAt = DateTime.formatIso(yield* DateTime.now);
66 const unsupported = makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" });
67 if (!input.enabled || input.serverUrl.trim()) return unsupported;
68
69 return yield* Effect.gen(function* () {
70 const fs = yield* FileSystem.FileSystem;
71 const path = yield* Path.Path;
72 const env = input.environment;
73 const dataHome =
74 env.XDG_DATA_HOME ||
75 path.join(
76 env.HOME || env.USERPROFILE || (yield* HostProcess.HomeDirectory),
77 ".local",
78 "share",
79 );
80 const dataDir = path.join(dataHome, "opencode");
81 const fileAuth = Effect.gen(function* () {
82 const contents =
83 env.OPENCODE_AUTH_CONTENT ||
84 (yield* fs.readFileString(path.join(dataDir, "auth.json")).pipe(
85 Effect.catchTags({
86 PlatformError: (error) =>
87 error.reason._tag === "NotFound" ? Effect.succeed("{}") : Effect.fail(error),
88 }),
89 ));
90 const auth = yield* decodeAuthFile(contents);
91 return Option.map(decodeApiAuth(auth["opencode-go"]), (api) => api.key);
92 });
93 // Inline auth content is an explicit override. Otherwise the database wins:
94 // OpenCode 2 no longer writes auth.json, so a key there that disagrees with
95 // it is a stale OpenCode 1 leftover. OpenCode resolves OPENCODE_DB against
96 // its data directory.
97 const storedKey = env.OPENCODE_AUTH_CONTENT
98 ? Option.none<string>()
99 : yield* readStoredGoApiKey(path.resolve(dataDir, env.OPENCODE_DB || "opencode.db"));
100 const savedKey = Option.isSome(storedKey) ? storedKey : yield* fileAuth;
101 // OpenCode overlays stored API credentials after environment credentials.
102 const apiKey = (Option.isSome(savedKey) ? savedKey.value : env.OPENCODE_API_KEY)?.trim();
103 if (!apiKey) return unsupported;
104
105 const client = yield* HttpClient.HttpClient;
106 const response = yield* client.execute(
107 HttpClientRequest.get("https://opencode.ai/zen/go/v1/usage").pipe(
108 HttpClientRequest.bearerToken(apiKey),
109 ),
110 );
111 // A valid Zen key can exist without a Go subscription.
112 if (response.status === 403) return unsupported;
113 const body = yield* HttpClientResponse.filterStatusOk(response).pipe(
114 Effect.flatMap(HttpClientResponse.schemaBodyJson(UsageResponse)),
115 );
116 const windows: ServerProviderUsageWindow[] = [
117 {
118 id: "go_rolling",
119 kind: "session",
120 label: "Go · Session",
121 windowDurationMins: 5 * 60,
122 usedPercent: clampPercent(body.usage.rolling.percent),
123 resetsAt: DateTime.formatIso(body.usage.rolling.resetsAt),
124 },
125 {
126 id: "go_weekly",
127 kind: "weekly",
128 label: "Go · Weekly",
129 windowDurationMins: 7 * 24 * 60,
130 usedPercent: clampPercent(body.usage.weekly.percent),
131 resetsAt: DateTime.formatIso(body.usage.weekly.resetsAt),
132 },
133 {
134 id: "go_monthly",
135 kind: "monthly",
136 label: "Go · Monthly",
137 usedPercent: clampPercent(body.usage.monthly.percent),
138 resetsAt: DateTime.formatIso(body.usage.monthly.resetsAt),
139 },
140 ];
141 const crypto = yield* Crypto.Crypto;
142 // An unkeyed hash matches across environments without a shared secret. It
143 // permits offline guesses, but Go keys are randomly generated.
144 const credentialFingerprint = yield* crypto
145 .digest("SHA-256", new TextEncoder().encode(`opencode-go\0${apiKey}`))
146 .pipe(Effect.map(Hex.encode), Effect.orDie);
147 return {
148 ...makeUsageLimits({ checkedAt, windows }),
149 credentialFingerprint,
150 };
151 }).pipe(
152 Effect.timeout("5 seconds"),
153 Effect.orElseSucceed(() =>
154 makeUnavailableUsageLimits({
155 checkedAt,
156 reason: "probeFailed",
157 message: "OpenCode Go could not read usage.",
158 }),
159 ),
160 );
161});