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

usageLimits.ts

167 lines6.2 KB

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