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

usageLimits.ts

179 lines6.9 KB

1import * as NodeSqlite from "node:sqlite";
2​
3import type { ServerProviderUsageWindow } from "@t3tools/contracts";
4import * as Crypto from "effect/Crypto";
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 readConsoleApiKey = (databasePath: string) =>
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 = 'opencode' AND active IS NOT 0
55 ORDER BY active DESC, time_created DESC, id DESC LIMIT 1`,
56 )
57 .get();
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 consoleKey =
112 env.OPENCODE_AUTH_CONTENT || databaseFile === ":memory:"
113 ? undefined
114 : yield* readConsoleApiKey(path.resolve(dataHome, "opencode", databaseFile));
115 let apiKey = consoleKey || goKey;
116 if (!apiKey) return unsupported;
117​
118 const client = yield* HttpClient.HttpClient;
119 const readUsage = (key: string) =>
120 client.execute(
121 HttpClientRequest.get("https://opencode.ai/zen/go/v1/usage").pipe(
122 HttpClientRequest.bearerToken(key),
123 ),
124 );
125 let response = yield* readUsage(apiKey);
126 if ((response.status === 401 || response.status === 403) && goKey && goKey !== apiKey) {
127 apiKey = goKey;
128 response = yield* readUsage(apiKey);
129 }
130 // A valid Zen key can exist without a Go subscription.
131 if (response.status === 403) return unsupported;
132 const body = yield* HttpClientResponse.filterStatusOk(response).pipe(
133 Effect.flatMap(HttpClientResponse.schemaBodyJson(UsageResponse)),
134 );
135 const windows: ServerProviderUsageWindow[] = [
136 {
137 id: "go_rolling",
138 kind: "session",
139 label: "Go · Session",
140 windowDurationMins: 5 * 60,
141 usedPercent: clampPercent(body.usage.rolling.percent),
142 resetsAt: DateTime.formatIso(body.usage.rolling.resetsAt),
143 },
144 {
145 id: "go_weekly",
146 kind: "weekly",
147 label: "Go · Weekly",
148 windowDurationMins: 7 * 24 * 60,
149 usedPercent: clampPercent(body.usage.weekly.percent),
150 resetsAt: DateTime.formatIso(body.usage.weekly.resetsAt),
151 },
152 {
153 id: "go_monthly",
154 kind: "monthly",
155 label: "Go · Monthly",
156 usedPercent: clampPercent(body.usage.monthly.percent),
157 resetsAt: DateTime.formatIso(body.usage.monthly.resetsAt),
158 },
159 ];
160 const crypto = yield* Crypto.Crypto;
161 // Unkeyed hashes match across environments; random Go keys resist offline guessing.
162 const credentialFingerprint = yield* crypto
163 .digest("SHA-256", new TextEncoder().encode(`opencode-go\0${apiKey}`))
164 .pipe(Effect.map(Hex.encode), Effect.orDie);
165 return {
166 ...makeUsageLimits({ checkedAt, windows }),
167 credentialFingerprint,
168 };
169 }).pipe(
170 Effect.timeout("5 seconds"),
171 Effect.orElseSucceed(() =>
172 makeUnavailableUsageLimits({
173 checkedAt,
174 reason: "probeFailed",
175 message: "OpenCode Go could not read usage.",
176 }),
177 ),
178 );
179});