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