Open History to see the last commit
1import * as NodeOS from "node:os";
2import type { ServerProviderUsageWindow } from "@t3tools/contracts";
3import * as DateTime from "effect/DateTime";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Option from "effect/Option";
7import * as Path from "effect/Path";
8import * as Schema from "effect/Schema";
9import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
10import {
11 clampPercent,
12 makeUnavailableUsageLimits,
13 makeUsageLimits,
14} from "../providerUsageLimits.ts";
15
16const GrokCredentials = Schema.Record(
17 Schema.String,
18 Schema.Struct({
19 key: Schema.optional(Schema.String),
20 auth_mode: Schema.optional(Schema.String),
21 }),
22);
23const decodeCredentials = Schema.decodeEffect(Schema.fromJsonString(GrokCredentials));
24const GrokUsageResponse = Schema.Struct({
25 config: Schema.optional(
26 Schema.Struct({
27 creditUsagePercent: Schema.optional(Schema.Number),
28 currentPeriod: Schema.optional(
29 Schema.Struct({
30 type: Schema.optional(Schema.String),
31 end: Schema.optional(Schema.String),
32 }),
33 ),
34 }),
35 ),
36});
37
38export function grokUsageResponseToLimits(
39 response: typeof GrokUsageResponse.Type,
40 checkedAt: string,
41) {
42 const usedPercent = response.config?.creditUsagePercent;
43 if (usedPercent === undefined || !Number.isFinite(usedPercent)) {
44 return makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" });
45 }
46 const period = response.config?.currentPeriod;
47 const periodType = period?.type?.replace(/^USAGE_PERIOD_TYPE_/, "");
48 const kind = periodType === "WEEKLY" ? "weekly" : periodType === "MONTHLY" ? "monthly" : "other";
49 const reset = period?.end ? DateTime.make(period.end) : Option.none();
50 const window: ServerProviderUsageWindow = {
51 id: "subscription",
52 kind,
53 label: kind === "weekly" ? "Weekly" : kind === "monthly" ? "Monthly" : "Subscription",
54 usedPercent: clampPercent(usedPercent),
55 ...(Option.isSome(reset) ? { resetsAt: DateTime.formatIso(reset.value) } : {}),
56 };
57 return makeUsageLimits({ checkedAt, windows: [window] });
58}
59
60export const readGrokUsageLimits = Effect.fn("readGrokUsageLimits")(function* (
61 environment: NodeJS.ProcessEnv = process.env,
62) {
63 const checkedAt = DateTime.formatIso(yield* DateTime.now);
64 return yield* Effect.gen(function* () {
65 // T3's ACP adapter explicitly selects API-key auth when this variable is set.
66 if (environment.XAI_API_KEY?.trim()) {
67 return makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" });
68 }
69 // Alternate auth deployments can select another scope or account from the same file.
70 if (
71 [
72 "GROK_OIDC_ISSUER",
73 "GROK_OIDC_CLIENT_ID",
74 "GROK_OAUTH2_ISSUER",
75 "GROK_OAUTH2_CLIENT_ID",
76 "GROK_OAUTH2_PRINCIPAL_TYPE",
77 "GROK_OAUTH2_PRINCIPAL_ID",
78 "GROK_AUTH_PROVIDER_COMMAND",
79 "GROK_LOCAL_AUTH",
80 "GROK_CLI_CHAT_PROXY_BASE_URL",
81 "GROK_MODELS_BASE_URL",
82 "GROK_CONFIG",
83 "GROK_CONFIG_PATH",
84 ].some((name) => environment[name]?.trim())
85 ) {
86 return makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" });
87 }
88 const fs = yield* FileSystem.FileSystem;
89 const path = yield* Path.Path;
90 const home =
91 environment.GROK_HOME?.trim() ||
92 path.join(environment.HOME || environment.USERPROFILE || NodeOS.homedir(), ".grok");
93 for (const configPath of [
94 path.join(home, "config.toml"),
95 path.join(home, "managed_config.toml"),
96 path.join(home, "requirements.toml"),
97 "/etc/grok/managed_config.toml",
98 "/etc/grok/requirements.toml",
99 ]) {
100 const config = yield* fs.readFileString(configPath).pipe(
101 Effect.catchTags({
102 PlatformError: (error) =>
103 error.reason._tag === "NotFound" ? Effect.succeed("") : Effect.fail(error),
104 }),
105 );
106 // These sections can change the selected account or endpoint. Leave custom deployments to the CLI.
107 if (/^\s*(?:\[\[?\s*)?["']?(?:auth|grok_com_config|endpoints)["']?\s*[.\]=]/m.test(config)) {
108 return makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" });
109 }
110 }
111 const contents =
112 environment.GROK_AUTH?.trim() ||
113 (yield* fs.readFileString(path.join(home, "auth.json")).pipe(
114 Effect.catchTags({
115 PlatformError: (error) =>
116 error.reason._tag === "NotFound" ? Effect.succeed("{}") : Effect.fail(error),
117 }),
118 ));
119 const credentials = yield* decodeCredentials(contents);
120 // Never pick an arbitrary account from other deployments stored in the same file.
121 const credential =
122 credentials["https://auth.x.ai::b1a00492-073a-47ea-816f-4c329264a828"] ??
123 credentials["https://accounts.x.ai/sign-in"];
124 const token = credential?.auth_mode === "api_key" ? undefined : credential?.key?.trim();
125 if (!token) return makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" });
126 const client = yield* HttpClient.HttpClient;
127 const response = yield* client.execute(
128 HttpClientRequest.get("https://cli-chat-proxy.grok.com/v1/billing?format=credits").pipe(
129 HttpClientRequest.bearerToken(token),
130 ),
131 );
132 const body = yield* HttpClientResponse.schemaBodyJson(GrokUsageResponse)(
133 yield* HttpClientResponse.filterStatusOk(response),
134 );
135 return grokUsageResponseToLimits(body, checkedAt);
136 }).pipe(
137 Effect.timeout("10 seconds"),
138 Effect.catch(() =>
139 Effect.succeed(
140 makeUnavailableUsageLimits({
141 checkedAt,
142 reason: "probeFailed",
143 message: "Grok could not read usage limits.",
144 }),
145 ),
146 ),
147 );
148});