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

openCodeUsageLimits.ts

109 lines4.1 KB

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