Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

usageLimits.ts

242 lines9.2 KB

1import * as NodeSqlite from "node:sqlite";
2​
3import type { ServerProviderUsageWindow } from "@t3tools/contracts";
4import * as Digest from "effect/crypto/Digest";
5import * as DateTime from "effect/DateTime";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Option from "effect/Option";
9import * as Path from "effect/Path";
10import * as Schema from "effect/Schema";
11import * as Hex from "effect/encoding/Hex";
12import * as HttpClient from "effect/http/HttpClient";
13import * as HttpClientRequest from "effect/http/HttpClientRequest";
14import * as HttpClientResponse from "effect/http/HttpClientResponse";
15​
16import {
17 clampPercent,
18 makeUnavailableUsageLimits,
19 makeUsageLimits,
20} from "@t3tools/provider-core/server/usageLimits";
21import * as HostProcess from "@t3tools/shared/HostProcess";
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);
27const 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 }),
34 ),
35);
36// OpenCode 2's database tags a stored key "key"; auth.json tags it "api".
37const 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]);
45const decodeConsoleCredential = Schema.decodeOption(Schema.fromJsonString(ConsoleCredential));
46// OpenCode 2 releases have signed in through both public Console addresses.
47const PUBLIC_CONSOLE_SERVERS = new Set([
48 "https://opencode.ai/console",
49 "https://console.opencode.ai",
50]);
51const UsageWindow = Schema.Struct({
52 percent: Schema.Finite,
53 resetsAt: Schema.DateTimeUtcFromString,
54});
55const UsageResponse = Schema.Struct({
56 usage: Schema.Struct({ rolling: UsageWindow, weekly: UsageWindow, monthly: UsageWindow }),
57});
58​
59class OpenCodeCredentialReadError extends Schema.TaggedError<OpenCodeCredentialReadError>()(
60 "OpenCodeCredentialReadError",
61 { databasePath: Schema.String, cause: Schema.Defect() },
62) {
63 override get message(): string {
64 return `Could not read OpenCode credentials from ${this.databasePath}.`;
65 }
67​
68// Select before decoding so a self-hosted connection cannot fall through to
69// another stored account. NULL-active rows predate the selection flag. T3 never
70// refreshes a sign-in: Console rotates refresh tokens, and OpenCode owns renewal.
71const readStoredCredential = (database: NodeSqlite.DatabaseSync, integrationId: string) => {
72 const row = database
73 .prepare(
74 `SELECT value FROM credential
75 WHERE integration_id = ? AND active IS NOT 0
76 ORDER BY active DESC, time_created DESC, id DESC LIMIT 1`,
77 )
78 .get(integrationId);
79 const stored =
80 typeof row?.value === "string"
81 ? Option.getOrUndefined(decodeConsoleCredential(row.value))
82 : undefined;
83 if (!stored) return undefined;
84 const { server, accountID, orgID } = stored.metadata ?? {};
85 // OpenCode sends a credential without a server string to the public Console,
86 // and service-account keys never store one.
87 if (typeof server === "string") {
88 const url = URL.parse(server);
89 if (!url || !PUBLIC_CONSOLE_SERVERS.has(`${url.origin}${url.pathname.replace(/\/+$/, "")}`))
90 return undefined;
91 }
92 if (stored.type === "key") return { token: stored.key.trim() };
93 return {
94 token: stored.access.trim(),
95 // Each device signs in with its own token, so only the account matches across environments.
96 account:
97 typeof accountID === "string" && typeof orgID === "string"
98 ? `${accountID}\0${orgID}`
99 : undefined,
100 };
101};
102​
103// OpenCode 2 keeps a standalone Go key in its database under "opencode-go";
104// auth.json only seeded that row once, so its copy can be stale.
105const readStoredCredentials = (databasePath: string) =>
106 Effect.try({
107 try: () => {
108 const database = new NodeSqlite.DatabaseSync(databasePath, { readOnly: true });
109 try {
110 database.exec("PRAGMA busy_timeout = 100");
111 return {
112 console: readStoredCredential(database, "opencode"),
113 go: readStoredCredential(database, "opencode-go"),
114 };
115 } finally {
116 database.close();
117 }
118 },
119 catch: (cause) => new OpenCodeCredentialReadError({ databasePath, cause }),
120 }).pipe(Effect.orElseSucceed(() => undefined));
121​
122/** External OpenCode servers own their credentials; never read the host's account for them. */
123export const readOpenCodeGoUsageLimits = Effect.fn("readOpenCodeGoUsageLimits")(function* (input: {
124 readonly enabled: boolean;
125 readonly serverUrl: string;
126 readonly environment: NodeJS.ProcessEnv;
127}) {
128 const checkedAt = DateTime.formatIso(yield* DateTime.now);
129 const unsupported = makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" });
130 if (!input.enabled || input.serverUrl.trim()) return unsupported;
131​
132 return yield* Effect.gen(function* () {
133 const fs = yield* FileSystem.FileSystem;
134 const path = yield* Path.Path;
135 const env = input.environment;
136 const dataHome =
137 env.XDG_DATA_HOME ||
138 path.join(
139 env.HOME || env.USERPROFILE || (yield* HostProcess.HomeDirectory),
140 ".local",
141 "share",
142 );
143 const authPath = path.join(dataHome, "opencode", "auth.json");
144 const contents =
145 env.OPENCODE_AUTH_CONTENT ||
146 (yield* fs.readFileString(authPath).pipe(
147 Effect.catchTags({
148 PlatformError: (error) =>
149 error.reason._tag === "NotFound" ? Effect.succeed("{}") : Effect.fail(error),
150 }),
151 ));
152 const auth = yield* decodeAuthFile(contents);
153 const apiAuth = decodeApiAuth(auth["opencode-go"]);
154 // OpenCode overlays stored API credentials after environment credentials.
155 const goKey = (Option.isSome(apiAuth) ? apiAuth.value.key : env.OPENCODE_API_KEY)?.trim();
156 // Console supplies Go credentials in OpenCode 2. Inline auth explicitly
157 // overrides local credentials, including the Console connection.
158 const databaseFile = env.OPENCODE_DB ?? "opencode.db";
159 const stored =
160 env.OPENCODE_AUTH_CONTENT || databaseFile === ":memory:"
161 ? undefined
162 : yield* readStoredCredentials(path.resolve(dataHome, "opencode", databaseFile));
163 const consoleCredential = stored?.console;
164 const candidates = [
165 ...new Set(
166 [consoleCredential?.token, stored?.go?.token, goKey].filter((key): key is string => !!key),
167 ),
168 ];
169 let apiKey = candidates.shift();
170 if (!apiKey) return unsupported;
171​
172 const client = yield* HttpClient.HttpClient;
173 const readUsage = (key: string) =>
174 client.execute(
175 HttpClientRequest.get("https://opencode.ai/zen/go/v1/usage").pipe(
176 HttpClientRequest.bearerToken(key),
177 ),
178 );
179 let response = yield* readUsage(apiKey);
180 // Try the next stored credential only when this one is rejected.
181 for (const key of candidates) {
182 if (response.status !== 401 && response.status !== 403) break;
183 apiKey = key;
184 response = yield* readUsage(apiKey);
185 }
186 // A valid Zen key can exist without a Go subscription.
187 if (response.status === 403) return unsupported;
188 const body = yield* HttpClientResponse.filterStatusOk(response).pipe(
189 Effect.flatMap(HttpClientResponse.schemaBodyJson(UsageResponse)),
190 );
191 const windows: ServerProviderUsageWindow[] = [
192 {
193 id: "go_rolling",
194 kind: "session",
195 label: "Go · Session",
196 windowDurationMins: 5 * 60,
197 usedPercent: clampPercent(body.usage.rolling.percent),
198 resetsAt: DateTime.formatIso(body.usage.rolling.resetsAt),
199 },
200 {
201 id: "go_weekly",
202 kind: "weekly",
203 label: "Go · Weekly",
204 windowDurationMins: 7 * 24 * 60,
205 usedPercent: clampPercent(body.usage.weekly.percent),
206 resetsAt: DateTime.formatIso(body.usage.weekly.resetsAt),
207 },
208 {
209 id: "go_monthly",
210 kind: "monthly",
211 label: "Go · Monthly",
212 usedPercent: clampPercent(body.usage.monthly.percent),
213 resetsAt: DateTime.formatIso(body.usage.monthly.resetsAt),
214 },
215 ];
216 const digest = yield* Digest.Digest;
217 // Unkeyed hashes match across environments; random Go keys resist offline guessing,
218 // and a Console sign-in hashes only account IDs, never its token.
219 const account = apiKey === consoleCredential?.token ? consoleCredential.account : undefined;
220 const credentialFingerprint = yield* digest
221 .digest(
222 Digest.sha256,
223 new TextEncoder().encode(
224 account ? `opencode-go\0console\0${account}` : `opencode-go\0${apiKey}`,
225 ),
226 )
227 .pipe(Effect.map(Hex.encode), Effect.orDie);
228 return {
229 ...makeUsageLimits({ checkedAt, windows }),
230 credentialFingerprint,
231 };
232 }).pipe(
233 Effect.timeout("5 seconds"),
234 Effect.orElseSucceed(() =>
235 makeUnavailableUsageLimits({
236 checkedAt,
237 reason: "probeFailed",
238 message: "OpenCode Go could not read usage.",
239 }),
240 ),
241 );
242});