Open History to see the last commit
1import * as NodeOS from "node:os";
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 { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
13
14import {
15 clampPercent,
16 makeUnavailableUsageLimits,
17 makeUsageLimits,
18} from "./providerUsageLimits.ts";
19
20const AuthFile = Schema.Struct({ "opencode-go": Schema.optionalKey(Schema.Unknown) });
21const ApiAuth = Schema.Struct({ type: Schema.Literal("api"), key: Schema.String });
22const decodeAuthFile = Schema.decodeEffect(Schema.fromJsonString(AuthFile));
23const decodeApiAuth = Schema.decodeUnknownOption(ApiAuth);
24const UsageWindow = Schema.Struct({
25 percent: Schema.Finite,
26 resetsAt: Schema.DateTimeUtcFromString,
27});
28const UsageResponse = Schema.Struct({
29 usage: Schema.Struct({ rolling: UsageWindow, weekly: UsageWindow, monthly: UsageWindow }),
30});
31
32/** External OpenCode servers own their credentials; never read the host's account for them. */
33export const readOpenCodeGoUsageLimits = Effect.fn("readOpenCodeGoUsageLimits")(function* (input: {
34 readonly enabled: boolean;
35 readonly serverUrl: string;
36 readonly environment: NodeJS.ProcessEnv;
37}) {
38 const checkedAt = DateTime.formatIso(yield* DateTime.now);
39 const unsupported = makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" });
40 if (!input.enabled || input.serverUrl.trim()) return unsupported;
41
42 return yield* Effect.gen(function* () {
43 const fs = yield* FileSystem.FileSystem;
44 const path = yield* Path.Path;
45 const env = input.environment;
46 const dataHome =
47 env.XDG_DATA_HOME ||
48 path.join(env.HOME || env.USERPROFILE || NodeOS.homedir(), ".local", "share");
49 const authPath = path.join(dataHome, "opencode", "auth.json");
50 const contents =
51 env.OPENCODE_AUTH_CONTENT ||
52 (yield* fs.readFileString(authPath).pipe(
53 Effect.catchTags({
54 PlatformError: (error) =>
55 error.reason._tag === "NotFound" ? Effect.succeed("{}") : Effect.fail(error),
56 }),
57 ));
58 const auth = yield* decodeAuthFile(contents);
59 const apiAuth = decodeApiAuth(auth["opencode-go"]);
60 // OpenCode overlays stored API credentials after environment credentials.
61 const apiKey = (Option.isSome(apiAuth) ? apiAuth.value.key : env.OPENCODE_API_KEY)?.trim();
62 if (!apiKey) return unsupported;
63
64 const client = yield* HttpClient.HttpClient;
65 const response = yield* client.execute(
66 HttpClientRequest.get("https://opencode.ai/zen/go/v1/usage").pipe(
67 HttpClientRequest.bearerToken(apiKey),
68 ),
69 );
70 // A valid Zen key can exist without a Go subscription.
71 if (response.status === 403) return unsupported;
72 const body = yield* HttpClientResponse.filterStatusOk(response).pipe(
73 Effect.flatMap(HttpClientResponse.schemaBodyJson(UsageResponse)),
74 );
75 const windows: ServerProviderUsageWindow[] = [
76 {
77 id: "go_rolling",
78 kind: "session",
79 label: "Go · Session",
80 windowDurationMins: 5 * 60,
81 usedPercent: clampPercent(body.usage.rolling.percent),
82 resetsAt: DateTime.formatIso(body.usage.rolling.resetsAt),
83 },
84 {
85 id: "go_weekly",
86 kind: "weekly",
87 label: "Go · Weekly",
88 windowDurationMins: 7 * 24 * 60,
89 usedPercent: clampPercent(body.usage.weekly.percent),
90 resetsAt: DateTime.formatIso(body.usage.weekly.resetsAt),
91 },
92 {
93 id: "go_monthly",
94 kind: "monthly",
95 label: "Go · Monthly",
96 usedPercent: clampPercent(body.usage.monthly.percent),
97 resetsAt: DateTime.formatIso(body.usage.monthly.resetsAt),
98 },
99 ];
100 const crypto = yield* Crypto.Crypto;
101 // Go's usage response has no account ID. An unkeyed hash matches across
102 // environments without a shared secret. It permits offline guesses, but
103 // Go keys are randomly generated.
104 const credentialFingerprint = yield* crypto
105 .digest("SHA-256", new TextEncoder().encode(`opencode-go\0${apiKey}`))
106 .pipe(Effect.map(Hex.encode), Effect.orDie);
107 return {
108 ...makeUsageLimits({ checkedAt, windows }),
109 credentialFingerprint,
110 };
111 }).pipe(
112 Effect.timeout("5 seconds"),
113 Effect.orElseSucceed(() =>
114 makeUnavailableUsageLimits({
115 checkedAt,
116 reason: "probeFailed",
117 message: "OpenCode Go could not read usage.",
118 }),
119 ),
120 );
121});