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

usageLimits.ts

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