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

usageLimits.ts

237 lines9.3 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 StoredMetadata = Schema.Struct({
28 server: Schema.optionalKey(Schema.Unknown),
29 orgID: Schema.optionalKey(Schema.Unknown),
30});
31// OpenCode 2's database tags a stored key "key"; auth.json tags it "api".
32const StoredKey = Schema.Struct({
33 type: Schema.Literal("key"),
34 key: Schema.String,
35 metadata: Schema.optionalKey(Schema.NullOr(StoredMetadata)),
36});
37const StoredOAuth = Schema.Struct({
38 type: Schema.Literal("oauth"),
39 access: Schema.String,
40 metadata: Schema.optionalKey(Schema.NullOr(StoredMetadata)),
41});
42const decodeStoredCredential = Schema.decodeOption(
43 Schema.fromJsonString(Schema.Union([StoredKey, StoredOAuth])),
44);
45const UsageWindow = Schema.Struct({
46 percent: Schema.Finite,
47 resetsAt: Schema.DateTimeUtcFromString,
48});
49const UsageResponse = Schema.Struct({
50 usage: Schema.Struct({ rolling: UsageWindow, weekly: UsageWindow, monthly: UsageWindow }),
51});
52​
53// Select before decoding so an unsupported or self-hosted connection cannot fall
54// through to another stored account. NULL-active rows predate the selection flag.
55class OpenCodeCredentialReadError extends Schema.TaggedError<OpenCodeCredentialReadError>()(
56 "OpenCodeCredentialReadError",
57 { databasePath: Schema.String, cause: Schema.Defect() },
58) {
59 override get message(): string {
60 return `Could not read OpenCode credentials from ${this.databasePath}.`;
61 }
63​
64type StoredCredential = {
65 readonly token: string;
66 readonly workspaceID?: string;
67 readonly oauth?: true;
68};
69​
70const readStoredCredential = (databasePath: string, integrationId: "opencode" | "opencode-go") =>
71 Effect.try({
72 try: (): StoredCredential | undefined => {
73 const database = new NodeSqlite.DatabaseSync(databasePath, { readOnly: true });
74 try {
75 database.exec("PRAGMA busy_timeout = 100");
76 const row = database
77 .prepare(
78 `SELECT value FROM credential
79 WHERE integration_id = ? AND active IS NOT 0
80 ORDER BY active DESC, time_created DESC, id DESC LIMIT 1`,
81 )
82 .get(integrationId);
83 const stored =
84 typeof row?.value === "string"
85 ? Option.getOrUndefined(decodeStoredCredential(row.value))
86 : undefined;
87 const server = stored?.metadata?.server;
88 if (typeof server === "string") {
89 const url = new URL(server);
90 if (`${url.origin}${url.pathname.replace(/\/+$/, "")}` !== "https://opencode.ai/console")
91 return undefined;
92 }
93 const token = (stored?.type === "oauth" ? stored.access : stored?.key)?.trim();
94 if (!token) return undefined;
95 const orgID = stored?.metadata?.orgID;
96 return {
97 token,
98 ...(typeof orgID === "string" ? { workspaceID: orgID } : {}),
99 ...(stored?.type === "oauth" ? { oauth: true as const } : {}),
100 };
101 } finally {
102 database.close();
103 }
104 },
105 catch: (cause) => new OpenCodeCredentialReadError({ databasePath, cause }),
106 }).pipe(Effect.orElseSucceed(() => undefined));
107​
108/** External OpenCode servers own their credentials; never read the host's account for them. */
109export const readOpenCodeGoUsageLimits = Effect.fn("readOpenCodeGoUsageLimits")(function* (input: {
110 readonly enabled: boolean;
111 readonly serverUrl: string;
112 readonly environment: NodeJS.ProcessEnv;
113}) {
114 const checkedAt = DateTime.formatIso(yield* DateTime.now);
115 const unsupported = makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" });
116 if (!input.enabled || input.serverUrl.trim()) return unsupported;
117​
118 return yield* Effect.gen(function* () {
119 const fs = yield* FileSystem.FileSystem;
120 const path = yield* Path.Path;
121 const env = input.environment;
122 const dataHome =
123 env.XDG_DATA_HOME ||
124 path.join(
125 env.HOME || env.USERPROFILE || (yield* HostProcess.HomeDirectory),
126 ".local",
127 "share",
128 );
129 const authPath = path.join(dataHome, "opencode", "auth.json");
130 const contents =
131 env.OPENCODE_AUTH_CONTENT ||
132 (yield* fs.readFileString(authPath).pipe(
133 Effect.catchTags({
134 PlatformError: (error) =>
135 error.reason._tag === "NotFound" ? Effect.succeed("{}") : Effect.fail(error),
136 }),
137 ));
138 const auth = yield* decodeAuthFile(contents);
139 const apiAuth = decodeApiAuth(auth["opencode-go"]);
140 // OpenCode overlays stored API credentials after environment credentials.
141 const goKey = (Option.isSome(apiAuth) ? apiAuth.value.key : env.OPENCODE_API_KEY)?.trim();
142 // Console supplies Go credentials in OpenCode 2. Inline auth explicitly
143 // overrides local credentials, including the Console connection.
144 const databaseFile = env.OPENCODE_DB ?? "opencode.db";
145 const databasePath = path.resolve(dataHome, "opencode", databaseFile);
146 const storedCredentials =
147 env.OPENCODE_AUTH_CONTENT || databaseFile === ":memory:"
148 ? []
149 : [
150 yield* readStoredCredential(databasePath, "opencode"),
151 // OpenCode 2 imports auth.json once, so a replaced Go key only exists here.
152 yield* readStoredCredential(databasePath, "opencode-go"),
153 ];
154 // The first source of a token wins, so a duplicate auth.json key keeps its workspace.
155 const credentials = [storedCredentials, goKey ? [{ token: goKey }] : []]
156 .flat()
157 .filter(
158 (credential, index, all): credential is StoredCredential =>
159 credential !== undefined &&
160 all.findIndex((other) => other?.token === credential.token) === index,
161 );
162 let credential = credentials[0];
163 if (!credential) return unsupported;
164​
165 const client = yield* HttpClient.HttpClient;
166 const readUsage = (selected: StoredCredential) => {
167 let request = HttpClientRequest.get("https://opencode.ai/zen/go/v1/usage").pipe(
168 HttpClientRequest.bearerToken(selected.token),
169 );
170 if (selected.workspaceID) {
171 request = request.pipe(
172 HttpClientRequest.setHeader("x-opencode-org-id", selected.workspaceID),
173 );
174 }
175 return client.execute(request);
176 };
177 let response = yield* readUsage(credential);
178 for (const next of credentials.slice(1)) {
179 if (response.status !== 401 && response.status !== 403) break;
180 credential = next;
181 response = yield* readUsage(credential);
182 }
183 // A valid Zen key can exist without a Go subscription.
184 if (response.status === 403) return unsupported;
185 const body = yield* HttpClientResponse.filterStatusOk(response).pipe(
186 Effect.flatMap(HttpClientResponse.schemaBodyJson(UsageResponse)),
187 );
188 const windows: ServerProviderUsageWindow[] = [
189 {
190 id: "go_rolling",
191 kind: "session",
192 label: "Go · Session",
193 windowDurationMins: 5 * 60,
194 usedPercent: clampPercent(body.usage.rolling.percent),
195 resetsAt: DateTime.formatIso(body.usage.rolling.resetsAt),
196 },
197 {
198 id: "go_weekly",
199 kind: "weekly",
200 label: "Go · Weekly",
201 windowDurationMins: 7 * 24 * 60,
202 usedPercent: clampPercent(body.usage.weekly.percent),
203 resetsAt: DateTime.formatIso(body.usage.weekly.resetsAt),
204 },
205 {
206 id: "go_monthly",
207 kind: "monthly",
208 label: "Go · Monthly",
209 usedPercent: clampPercent(body.usage.monthly.percent),
210 resetsAt: DateTime.formatIso(body.usage.monthly.resetsAt),
211 },
212 ];
213 const digest = yield* Digest.Digest;
214 // Unkeyed hashes match across environments; random Go keys resist offline guessing.
215 // Console OAuth tokens rotate on refresh, so their usage is keyed by workspace instead.
216 const fingerprintSource =
217 credential.oauth && credential.workspaceID
218 ? `opencode-console\0${credential.workspaceID}`
219 : `opencode-go\0${credential.token}`;
220 const credentialFingerprint = yield* digest
221 .digest(Digest.sha256, new TextEncoder().encode(fingerprintSource))
222 .pipe(Effect.map(Hex.encode), Effect.orDie);
223 return {
224 ...makeUsageLimits({ checkedAt, windows }),
225 credentialFingerprint,
226 };
227 }).pipe(
228 Effect.timeout("5 seconds"),
229 Effect.orElseSucceed(() =>
230 makeUnavailableUsageLimits({
231 checkedAt,
232 reason: "probeFailed",
233 message: "OpenCode Go could not read usage.",
234 }),
235 ),
236 );
237});