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