Open History to see the last commit
1import type { ServerProviderUsageWindow } from "@t3tools/contracts";
2import * as DateTime from "effect/DateTime";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Option from "effect/Option";
6import * as Path from "effect/Path";
7import * as Schema from "effect/Schema";
8import * as HttpClient from "effect/http/HttpClient";
9import * as HttpClientRequest from "effect/http/HttpClientRequest";
10import * as HttpClientResponse from "effect/http/HttpClientResponse";
11import {
12 clampPercent,
13 makeUnavailableUsageLimits,
14 makeUsageLimits,
15} from "@t3tools/provider-core/server/usageLimits";
16import * as HostProcess from "@t3tools/shared/HostProcess";
17
18const GrokCredentials = Schema.Record(
19 Schema.String,
20 Schema.Struct({
21 key: Schema.optional(Schema.String),
22 auth_mode: Schema.optional(Schema.String),
23 email: Schema.optional(Schema.String),
24 }),
25);
26const decodeCredentials = Schema.decodeEffect(Schema.fromJsonString(GrokCredentials));
27export const GROK_USAGE_URL = "https://cli-chat-proxy.grok.com/v1/billing?format=credits";
28export const GrokUsageResponse = Schema.Struct({
29 config: Schema.optional(
30 Schema.Struct({
31 creditUsagePercent: Schema.optional(Schema.Number),
32 currentPeriod: Schema.optional(
33 Schema.Struct({
34 type: Schema.optional(Schema.String),
35 start: Schema.optional(Schema.Unknown),
36 end: Schema.optional(Schema.String),
37 }),
38 ),
39 }),
40 ),
41});
42const GrokErrorResponse = Schema.Struct({ error: Schema.String });
43
44function parsePeriodBoundary(value: string | undefined) {
45 if (
46 !value ||
47 value !== value.trim() ||
48 !/^(?:\d{4}|[+-]\d{6})-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?|24:00(?::00(?:\.0+)?)?)(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/.test(
49 value,
50 )
51 ) {
52 return Number.NaN;
53 }
54 // Date parsing can normalize impossible calendar dates instead of rejecting them.
55 const datePart = value.slice(0, value.indexOf("T"));
56 const date = DateTime.make(`${datePart}T00:00:00.000Z`);
57 if (Option.isNone(date)) return Number.NaN;
58 const parts = DateTime.toPartsUtc(date.value);
59 if (parts.month !== Number(datePart.slice(-5, -3)) || parts.day !== Number(datePart.slice(-2))) {
60 return Number.NaN;
61 }
62 return Date.parse(value);
63}
64
65export function grokUsageResponseToLimits(
66 response: typeof GrokUsageResponse.Type,
67 checkedAt: string,
68) {
69 const period = response.config?.currentPeriod;
70 const periodType = period?.type?.replace(/^USAGE_PERIOD_TYPE_/, "");
71 const kind = periodType === "WEEKLY" ? "weekly" : periodType === "MONTHLY" ? "monthly" : "other";
72 let usedPercent = response.config?.creditUsagePercent;
73 if (
74 usedPercent === undefined &&
75 (kind === "weekly" || kind === "monthly") &&
76 typeof period?.start === "string" &&
77 parsePeriodBoundary(period?.start) < parsePeriodBoundary(period?.end)
78 ) {
79 // Grok omits a zero percentage while retaining the complete subscription period.
80 usedPercent = 0;
81 }
82 if (usedPercent === undefined || !Number.isFinite(usedPercent)) {
83 return makeUsageLimits({ checkedAt, windows: [] });
84 }
85 const reset = period?.end ? DateTime.make(period.end) : Option.none();
86 const window: ServerProviderUsageWindow = {
87 id: "subscription",
88 kind,
89 label: kind === "weekly" ? "Weekly" : kind === "monthly" ? "Monthly" : "Subscription",
90 usedPercent: clampPercent(usedPercent),
91 ...(Option.isSome(reset) ? { resetsAt: DateTime.formatIso(reset.value) } : {}),
92 };
93 return makeUsageLimits({ checkedAt, windows: [window] });
94}
95
96const readGrokCredential = Effect.fn("readGrokCredential")(function* (
97 environment: NodeJS.ProcessEnv,
98) {
99 // T3's ACP adapter explicitly selects API-key auth when this variable is set.
100 if (environment.XAI_API_KEY?.trim()) return undefined;
101 // Alternate auth deployments can select another scope or account from the same file.
102 if (
103 [
104 "GROK_OIDC_ISSUER",
105 "GROK_OIDC_CLIENT_ID",
106 "GROK_OAUTH2_ISSUER",
107 "GROK_OAUTH2_CLIENT_ID",
108 "GROK_OAUTH2_PRINCIPAL_TYPE",
109 "GROK_OAUTH2_PRINCIPAL_ID",
110 "GROK_AUTH_PROVIDER_COMMAND",
111 "GROK_LOCAL_AUTH",
112 "GROK_CLI_CHAT_PROXY_BASE_URL",
113 "GROK_MODELS_BASE_URL",
114 "GROK_CONFIG",
115 "GROK_CONFIG_PATH",
116 ].some((name) => environment[name]?.trim())
117 ) {
118 return undefined;
119 }
120 const fs = yield* FileSystem.FileSystem;
121 const path = yield* Path.Path;
122 const home =
123 environment.GROK_HOME?.trim() ||
124 path.join(
125 environment.HOME || environment.USERPROFILE || (yield* HostProcess.HomeDirectory),
126 ".grok",
127 );
128 for (const configPath of [
129 path.join(home, "config.toml"),
130 path.join(home, "managed_config.toml"),
131 path.join(home, "requirements.toml"),
132 "/etc/grok/managed_config.toml",
133 "/etc/grok/requirements.toml",
134 ]) {
135 const config = yield* fs.readFileString(configPath).pipe(
136 Effect.catchTags({
137 PlatformError: (error) =>
138 error.reason._tag === "NotFound" ? Effect.succeed("") : Effect.fail(error),
139 }),
140 );
141 // These sections can change the selected account or endpoint. Leave custom deployments to the CLI.
142 if (/^\s*(?:\[\[?\s*)?["']?(?:auth|grok_com_config|endpoints)["']?\s*[.\]=]/m.test(config)) {
143 return undefined;
144 }
145 }
146 const contents =
147 environment.GROK_AUTH?.trim() ||
148 (yield* fs.readFileString(path.join(home, "auth.json")).pipe(
149 Effect.catchTags({
150 PlatformError: (error) =>
151 error.reason._tag === "NotFound" ? Effect.succeed("{}") : Effect.fail(error),
152 }),
153 ));
154 const credentials = yield* decodeCredentials(contents);
155 // Never pick an arbitrary account from other deployments stored in the same file.
156 const credential =
157 credentials["https://auth.x.ai::b1a00492-073a-47ea-816f-4c329264a828"] ??
158 credentials["https://accounts.x.ai/sign-in"];
159 return credential?.auth_mode === "api_key" ? undefined : credential;
160});
161
162export const readGrokAccount = Effect.fn("readGrokAccount")(function* (
163 environment: NodeJS.ProcessEnv = process.env,
164) {
165 const checkedAt = DateTime.formatIso(yield* DateTime.now);
166 const probeFailed = makeUnavailableUsageLimits({
167 checkedAt,
168 reason: "probeFailed",
169 message: "Grok could not read usage limits.",
170 });
171 const credential = yield* Effect.option(
172 readGrokCredential(environment).pipe(Effect.timeout("10 seconds")),
173 );
174 if (Option.isNone(credential)) return { email: undefined, usageLimits: probeFailed };
175 const email = credential.value?.email?.trim() || undefined;
176 const token = credential.value?.key?.trim();
177 if (!token) {
178 return { email, usageLimits: makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" }) };
179 }
180 const usageLimits = yield* Effect.gen(function* () {
181 const client = yield* HttpClient.HttpClient;
182 const response = yield* client.execute(
183 HttpClientRequest.get(GROK_USAGE_URL).pipe(HttpClientRequest.bearerToken(token)),
184 );
185 if (response.status === 403) {
186 const { error } = yield* HttpClientResponse.schemaBodyJson(GrokErrorResponse)(response);
187 // xAI refuses Grok Build while the account's privacy setting is a legacy mode.
188 if (error.includes("WKE=privacy-mode:")) {
189 return makeUnavailableUsageLimits({
190 checkedAt,
191 reason: "probeFailed",
192 message: "Switch your xAI account to Privacy Mode to show Grok usage limits.",
193 });
194 }
195 }
196 const body = yield* HttpClientResponse.schemaBodyJson(GrokUsageResponse)(
197 yield* HttpClientResponse.filterStatusOk(response),
198 );
199 return grokUsageResponseToLimits(body, checkedAt);
200 }).pipe(
201 Effect.timeout("10 seconds"),
202 Effect.orElseSucceed(() => probeFailed),
203 );
204 return { email, usageLimits };
205});