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