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

usageLimits.ts

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