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

grokUsageLimits.ts

175 lines6.7 KB

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/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 email: Schema.optional(Schema.String),
22 }),
23);
24const decodeCredentials = Schema.decodeEffect(Schema.fromJsonString(GrokCredentials));
25const GrokUsageResponse = Schema.Struct({
26 config: Schema.optional(
27 Schema.Struct({
28 creditUsagePercent: Schema.optional(Schema.Number),
29 currentPeriod: Schema.optional(
30 Schema.Struct({
31 type: Schema.optional(Schema.String),
32 end: Schema.optional(Schema.String),
33 }),
34 ),
35 }),
36 ),
37});
38​
39export function grokUsageResponseToLimits(
40 response: typeof GrokUsageResponse.Type,
41 checkedAt: string,
42) {
43 const usedPercent = response.config?.creditUsagePercent;
44 if (usedPercent === undefined || !Number.isFinite(usedPercent)) {
45 // A billing read that succeeded but carries no percentage is an account
46 // with nothing metered yet, not one that can never report: xAI omits the
47 // field entirely (rather than sending 0) until usage registers, then fills
48 // it in. Calling that `unsupported` would strand the account — the Limits
49 // view drops unsupported entries and deliberately mutes their notice, so a
50 // freshly signed-in Grok account would vanish with no explanation until it
51 // happened to be used, and `applyUsageLimitsUpdate` would refuse the
52 // mid-turn windows that could have recovered it.
53 return makeUsageLimits({ checkedAt, windows: [] });
54 }
55 const period = response.config?.currentPeriod;
56 const periodType = period?.type?.replace(/^USAGE_PERIOD_TYPE_/, "");
57 const kind = periodType === "WEEKLY" ? "weekly" : periodType === "MONTHLY" ? "monthly" : "other";
58 const reset = period?.end ? DateTime.make(period.end) : Option.none();
59 const window: ServerProviderUsageWindow = {
60 id: "subscription",
61 kind,
62 label: kind === "weekly" ? "Weekly" : kind === "monthly" ? "Monthly" : "Subscription",
63 usedPercent: clampPercent(usedPercent),
64 ...(Option.isSome(reset) ? { resetsAt: DateTime.formatIso(reset.value) } : {}),
65 };
66 return makeUsageLimits({ checkedAt, windows: [window] });
68​
69/**
70 * The grok.com login the CLI uses by default, or undefined when the CLI is
71 * configured to pick another account, endpoint, or an API key.
72 */
73const readGrokCredential = Effect.fn("readGrokCredential")(function* (
74 environment: NodeJS.ProcessEnv,
75) {
76 // T3's ACP adapter explicitly selects API-key auth when this variable is set.
77 if (environment.XAI_API_KEY?.trim()) return undefined;
78 // Alternate auth deployments can select another scope or account from the same file.
79 if (
80 [
81 "GROK_OIDC_ISSUER",
82 "GROK_OIDC_CLIENT_ID",
83 "GROK_OAUTH2_ISSUER",
84 "GROK_OAUTH2_CLIENT_ID",
85 "GROK_OAUTH2_PRINCIPAL_TYPE",
86 "GROK_OAUTH2_PRINCIPAL_ID",
87 "GROK_AUTH_PROVIDER_COMMAND",
88 "GROK_LOCAL_AUTH",
89 "GROK_CLI_CHAT_PROXY_BASE_URL",
90 "GROK_MODELS_BASE_URL",
91 "GROK_CONFIG",
92 "GROK_CONFIG_PATH",
93 ].some((name) => environment[name]?.trim())
94 ) {
95 return undefined;
96 }
97 const fs = yield* FileSystem.FileSystem;
98 const path = yield* Path.Path;
99 const home =
100 environment.GROK_HOME?.trim() ||
101 path.join(environment.HOME || environment.USERPROFILE || NodeOS.homedir(), ".grok");
102 for (const configPath of [
103 path.join(home, "config.toml"),
104 path.join(home, "managed_config.toml"),
105 path.join(home, "requirements.toml"),
106 "/etc/grok/managed_config.toml",
107 "/etc/grok/requirements.toml",
108 ]) {
109 const config = yield* fs.readFileString(configPath).pipe(
110 Effect.catchTags({
111 PlatformError: (error) =>
112 error.reason._tag === "NotFound" ? Effect.succeed("") : Effect.fail(error),
113 }),
114 );
115 // These sections can change the selected account or endpoint. Leave custom deployments to the CLI.
116 if (/^\s*(?:\[\[?\s*)?["']?(?:auth|grok_com_config|endpoints)["']?\s*[.\]=]/m.test(config)) {
117 return undefined;
118 }
119 }
120 const contents =
121 environment.GROK_AUTH?.trim() ||
122 (yield* fs.readFileString(path.join(home, "auth.json")).pipe(
123 Effect.catchTags({
124 PlatformError: (error) =>
125 error.reason._tag === "NotFound" ? Effect.succeed("{}") : Effect.fail(error),
126 }),
127 ));
128 const credentials = yield* decodeCredentials(contents);
129 // Never pick an arbitrary account from other deployments stored in the same file.
130 const credential =
131 credentials["https://auth.x.ai::b1a00492-073a-47ea-816f-4c329264a828"] ??
132 credentials["https://accounts.x.ai/sign-in"];
133 return credential?.auth_mode === "api_key" ? undefined : credential;
134});
135​
136/**
137 * Reads the default grok.com login once and reports its usage limits along with
138 * its email, so the email always names the account whose quota was read.
139 */
140export const readGrokAccount = Effect.fn("readGrokAccount")(function* (
141 environment: NodeJS.ProcessEnv = process.env,
142) {
143 const checkedAt = DateTime.formatIso(yield* DateTime.now);
144 const probeFailed = makeUnavailableUsageLimits({
145 checkedAt,
146 reason: "probeFailed",
147 message: "Grok could not read usage limits.",
148 });
149 const credential = yield* Effect.option(
150 readGrokCredential(environment).pipe(Effect.timeout("10 seconds")),
151 );
152 if (Option.isNone(credential)) return { email: undefined, usageLimits: probeFailed };
153 const email = credential.value?.email?.trim() || undefined;
154 const token = credential.value?.key?.trim();
155 if (!token) {
156 return { email, usageLimits: makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" }) };
157 }
158 // A failed quota request still knows which account it asked about.
159 const usageLimits = yield* Effect.gen(function* () {
160 const client = yield* HttpClient.HttpClient;
161 const response = yield* client.execute(
162 HttpClientRequest.get("https://cli-chat-proxy.grok.com/v1/billing?format=credits").pipe(
163 HttpClientRequest.bearerToken(token),
164 ),
165 );
166 const body = yield* HttpClientResponse.schemaBodyJson(GrokUsageResponse)(
167 yield* HttpClientResponse.filterStatusOk(response),
168 );
169 return grokUsageResponseToLimits(body, checkedAt);
170 }).pipe(
171 Effect.timeout("10 seconds"),
172 Effect.orElseSucceed(() => probeFailed),
173 );
174 return { email, usageLimits };
175});