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

cliproxyApi.ts

566 lines20.5 KB

1import {
2 ProviderDriverKind,
3 UsageLimitSourceError,
4 type ProviderConsumeResetCreditResult,
5 type UsageLimitSourceAccount,
6 type UsageLimitSourceConfig,
7} from "@t3tools/contracts";
8import * as HostProcess from "@t3tools/shared/HostProcess";
9import * as Cause from "effect/Cause";
10import * as Digest from "effect/crypto/Digest";
11import * as DateTime from "effect/DateTime";
12import * as Effect from "effect/Effect";
13import * as Hex from "effect/encoding/Hex";
14import * as Option from "effect/Option";
15import * as Schema from "effect/Schema";
16import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http";
17​
18import {
19 GROK_USAGE_URL,
20 GrokUsageResponse,
21 grokUsageResponseToLimits,
22} from "@t3tools/provider-grok/server";
23import { codexPlanLabel } from "../provider/CodexProvider.ts";
24import { codexRateLimitsToLimits } from "../provider/codexUsageLimits.ts";
25import { claudeUsageResponseToLimits } from "../provider/claudeUsageLimits.ts";
26import {
27 antigravityAccountFingerprint,
28 antigravitySummaryWindows,
29 antigravityUserAgent,
30} from "../provider/antigravityUsageLimits.ts";
31import {
32 makeUnavailableUsageLimits,
33 makeUsageLimits,
34} from "@t3tools/provider-core/server/usageLimits";
35​
36/** A hub with its management key already read from wherever the setting keeps it. */
37export interface CliproxyHub {
38 readonly url: UsageLimitSourceConfig["url"];
39 readonly managementKey: string;
41​
42const AuthFile = Schema.Struct({
43 id: Schema.String,
44 auth_index: Schema.String,
45 provider: Schema.String,
46 email: Schema.optional(Schema.String),
47 disabled: Schema.optional(Schema.Boolean),
48 project_id: Schema.optional(Schema.String),
49 id_token: Schema.optional(
50 Schema.Struct({
51 chatgpt_account_id: Schema.optional(Schema.String),
52 chatgpt_plan_type: Schema.optional(Schema.String),
53 plan_type: Schema.optional(Schema.String),
54 }),
55 ),
56});
57const AuthFiles = Schema.Struct({ files: Schema.Array(AuthFile) });
58const ApiResponse = Schema.Struct({ status_code: Schema.Number, body: Schema.String });
59const CodexWindow = Schema.Struct({
60 used_percent: Schema.Number,
61 reset_at: Schema.optional(Schema.NullOr(Schema.Number)),
62 limit_window_seconds: Schema.optional(Schema.Number),
63});
64const CodexUsage = Schema.Struct({
65 plan_type: Schema.optional(Schema.String),
66 rate_limit: Schema.NullOr(
67 Schema.Struct({
68 primary_window: Schema.optional(Schema.NullOr(CodexWindow)),
69 secondary_window: Schema.optional(Schema.NullOr(CodexWindow)),
70 }),
71 ),
72});
73// The usage endpoint can report a window without a utilization, as the CLI's own schema allows.
74const ClaudeWindow = Schema.Struct({
75 utilization: Schema.NullOr(Schema.Number),
76 resets_at: Schema.NullOr(Schema.String),
77});
78const ClaudeUsage = Schema.Struct({
79 five_hour: Schema.optional(Schema.NullOr(ClaudeWindow)),
80 seven_day: Schema.optional(Schema.NullOr(ClaudeWindow)),
81 spend: Schema.optional(Schema.Unknown),
82 extra_usage: Schema.optional(
83 Schema.NullOr(
84 Schema.Struct({
85 is_enabled: Schema.Boolean,
86 monthly_limit: Schema.NullOr(Schema.Number),
87 used_credits: Schema.NullOr(Schema.Number),
88 utilization: Schema.NullOr(Schema.Number),
89 }),
90 ),
91 ),
92 limits: Schema.optional(
93 Schema.Array(
94 Schema.Struct({
95 kind: Schema.String,
96 percent: Schema.optional(Schema.NullOr(Schema.Number)),
97 resets_at: Schema.optional(Schema.NullOr(Schema.String)),
98 scope: Schema.optional(
99 Schema.NullOr(
100 Schema.Struct({
101 model: Schema.optional(Schema.NullOr(Schema.Struct({ display_name: Schema.String }))),
102 }),
103 ),
104 ),
105 }),
106 ),
107 ),
108});
109const CreditList = Schema.Struct({
110 credits: Schema.Array(
111 Schema.Struct({
112 id: Schema.String,
113 status: Schema.String,
114 reset_type: Schema.String,
115 expires_at: Schema.String,
116 }),
117 ),
118});
119​
120const decodeAuthFiles = Schema.decodeUnknownEffect(AuthFiles);
121const encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
122const decodeApiResponse = Schema.decodeUnknownEffect(ApiResponse);
123const decodeCreditList = Schema.decodeUnknownEffect(Schema.fromJsonString(CreditList));
124const decodeClaudeUsage = Schema.decodeUnknownEffect(Schema.fromJsonString(ClaudeUsage));
125const decodeCodexUsage = Schema.decodeUnknownEffect(Schema.fromJsonString(CodexUsage));
126const decodeGrokUsage = Schema.decodeUnknownEffect(Schema.fromJsonString(GrokUsageResponse));
127const decodeJson = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
128const isUsageLimitSourceError = Schema.is(UsageLimitSourceError);
129​
130// Extra CAs can fix untrusted chains; expiry/hostname failures report codes only.
131const UNTRUSTED_CERTIFICATE_CODES = new Set([
132 "DEPTH_ZERO_SELF_SIGNED_CERT",
133 "SELF_SIGNED_CERT_IN_CHAIN",
134 "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
135 "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
136]);
137​
138// fetch wraps Node error codes in generic TypeErrors.
139const nodeErrorCode = (cause: unknown) => {
140 for (let error = cause, depth = 0; error instanceof Error && depth < 3; depth += 1) {
141 const code = (error as { readonly code?: unknown }).code;
142 if (typeof code === "string" && /^[A-Z0-9_]{1,64}$/.test(code)) return code;
143 error = error.cause;
144 }
145 return undefined;
146};
147​
148// Hub responses can contain credentials; expose only failure kind, HTTP status or Node code.
149const describeManagementFailure = (error: unknown) => {
150 if (Cause.isTimeoutError(error)) return "The hub did not answer within 15 seconds.";
151 if (HttpClientError.isHttpClientError(error)) {
152 const reason = error.reason;
153 if (reason._tag === "StatusCodeError") {
154 return `The hub answered with HTTP ${reason.response.status}.`;
155 }
156 const code = reason._tag === "TransportError" ? nodeErrorCode(reason.cause) : undefined;
157 if (code !== undefined && UNTRUSTED_CERTIFICATE_CODES.has(code)) {
158 return `The hub's TLS certificate is not trusted (${code}). If it comes from a private CA, add that CA to NODE_EXTRA_CA_CERTS.`;
159 }
160 if (code !== undefined) return `The hub request failed (${code}).`;
161 }
162 return "The hub management request failed.";
163};
164const decodeConsumeResponse = Schema.decodeUnknownEffect(
165 Schema.fromJsonString(
166 Schema.Struct({
167 code: Schema.Literals(["reset", "nothing_to_reset", "no_credit", "already_redeemed"]),
168 }),
169 ),
170);
171​
172const CODEX_BASE = "https://chatgpt.com/backend-api/wham";
173const CREDIT_URL = `${CODEX_BASE}/rate-limit-reset-credits`;
174​
175const CREDIT_REDEEM_NAMESPACE = new Uint8Array([
176 0x6f, 0x1c, 0x2a, 0x9e, 0x2d, 0x4b, 0x4c, 0x1e, 0x9a, 0x7f, 0x3b, 0x8d, 0x5e, 0x0c, 0x1a, 0x42,
177]);
178​
179// UUIDv5 per account and credit also deduplicates retries across T3 environments.
180const creditRedeemRequestId = Effect.fn("CliproxyApi.creditRedeemRequestId")(function* (
181 accountId: string,
182 creditId: string,
183) {
184 const digest = yield* Digest.Digest;
185 const name = new TextEncoder().encode(`${accountId}:${creditId}`);
186 const input = new Uint8Array(CREDIT_REDEEM_NAMESPACE.length + name.length);
187 input.set(CREDIT_REDEEM_NAMESPACE);
188 input.set(name, CREDIT_REDEEM_NAMESPACE.length);
189 const bytes = (yield* digest.digest(Digest.sha1, input).pipe(Effect.orDie)).slice(0, 16);
190 bytes[6] = (bytes[6]! & 0x0f) | 0x50;
191 bytes[8] = (bytes[8]! & 0x3f) | 0x80;
192 const hex = Hex.encode(bytes);
193 return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
194});
195​
196type AuthFile = typeof AuthFile.Type;
197/** Sends one upstream request with the account's token, as GET or as a JSON POST of `data`. */
198type HubCall = (
199 url: string,
200 data?: unknown,
201) => Effect.Effect<string, UsageLimitSourceError | Schema.SchemaError>;
202type HubReading = Omit<UsageLimitSourceAccount, "id" | "driver">;
203interface HubProvider {
204 readonly driver: ProviderDriverKind;
205 readonly header: (
206 account: AuthFile,
207 platform: NodeJS.Platform,
208 architecture: NodeJS.Architecture,
209 ) => Record<string, string>;
210 readonly read: (input: {
211 readonly account: AuthFile;
212 readonly call: HubCall;
213 readonly checkedAt: string;
214 }) => Effect.Effect<HubReading, UsageLimitSourceError | Schema.SchemaError, Digest.Digest>;
216​
217const listedIdentity = (account: AuthFile) => ({
218 ...(account.email ? { email: account.email } : {}),
219 ...(account.id_token?.chatgpt_account_id?.trim()
220 ? { workspaceId: account.id_token.chatgpt_account_id.trim() }
221 : {}),
222});
223​
224const credits = Effect.fn("CliproxyApi.credits")(function* (call: HubCall) {
225 const response = yield* decodeCreditList(yield* call(CREDIT_URL));
226 const now = DateTime.toEpochMillis(yield* DateTime.now);
227 return response.credits
228 .filter(
229 (credit) =>
230 credit.reset_type === "codex_rate_limits" &&
231 credit.status === "available" &&
232 Date.parse(credit.expires_at) > now,
233 )
234 .toSorted((a, b) => Date.parse(a.expires_at) - Date.parse(b.expires_at));
235});
236​
237const CODEX_HUB: HubProvider = {
238 driver: ProviderDriverKind.make("codex"),
239 header: (account) => ({
240 Authorization: "Bearer $TOKEN$",
241 "Content-Type": "application/json",
242 "OpenAI-Beta": "codex-1",
243 Originator: "Codex Desktop",
244 ...(account.id_token?.chatgpt_account_id
245 ? { "Chatgpt-Account-Id": account.id_token.chatgpt_account_id }
246 : {}),
247 }),
248 read: Effect.fnUntraced(function* ({ account, call, checkedAt }) {
249 const usage = yield* decodeCodexUsage(yield* call(`${CODEX_BASE}/usage`));
250 const toWindow = (window: typeof CodexWindow.Type | null | undefined) =>
251 window
252 ? {
253 usedPercent: window.used_percent,
254 resetsAt: window.reset_at ?? null,
255 ...(window.limit_window_seconds === undefined
256 ? {}
257 : { windowDurationMins: window.limit_window_seconds / 60 }),
258 }
259 : null;
260 const available = yield* credits(call).pipe(Effect.orElseSucceed(() => undefined));
261 const next = available?.[0];
262 const planType =
263 usage.plan_type ?? account.id_token?.plan_type ?? account.id_token?.chatgpt_plan_type;
264 return {
265 ...listedIdentity(account),
266 plan: codexPlanLabel(planType),
267 usageLimits: {
268 ...codexRateLimitsToLimits({
269 checkedAt,
270 snapshot: {
271 planType: planType ?? null,
272 primary: toWindow(usage.rate_limit?.primary_window),
273 secondary: toWindow(usage.rate_limit?.secondary_window),
274 },
275 }),
276 ...(available
277 ? {
278 resetCredits: {
279 availableCount: available.length,
280 ...(next
281 ? {
282 nextCreditId: next.id,
283 nextExpiresAt: DateTime.formatIso(DateTime.makeUnsafe(next.expires_at)),
284 }
285 : {}),
286 },
287 }
288 : {}),
289 },
290 };
291 }),
292};
293​
294const GROK_CLI_VERSION = "1.0.77";
295const ANTIGRAVITY_SUMMARY_URL =
296 "https://daily-cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary";
297​
298// Keyed by the auth-files `provider`; accounts of any other provider are skipped.
299const HUB_PROVIDERS = new Map<string, HubProvider>([
300 ["codex", CODEX_HUB],
301 [
302 "claude",
303 {
304 driver: ProviderDriverKind.make("claudeAgent"),
305 header: () => ({
306 Authorization: "Bearer $TOKEN$",
307 "anthropic-beta": "oauth-2025-04-20",
308 // The OAuth usage endpoint can return 429 without a Claude Code user agent.
309 "User-Agent": "claude-code/2.1.273",
310 }),
311 read: Effect.fnUntraced(function* ({ account, call, checkedAt }) {
312 const usage = yield* decodeClaudeUsage(
313 yield* call("https://api.anthropic.com/api/oauth/usage"),
314 );
315 const model_scoped = (usage.limits ?? []).flatMap((limit) =>
316 limit.kind === "weekly_scoped" && limit.scope?.model && typeof limit.percent === "number"
317 ? [
318 {
319 display_name: limit.scope.model.display_name,
320 utilization: limit.percent,
321 resets_at: limit.resets_at ?? null,
322 },
323 ]
324 : [],
325 );
326 const rateLimits = {
327 five_hour: usage.five_hour ?? null,
328 seven_day: usage.seven_day ?? null,
329 model_scoped,
330 spend: usage.spend,
331 extra_usage: usage.extra_usage ?? null,
332 };
333 return {
334 ...listedIdentity(account),
335 plan: "Claude Subscription",
336 usageLimits: claudeUsageResponseToLimits({
337 checkedAt,
338 response: { rate_limits_available: true, rate_limits: rateLimits },
339 }).limits,
340 };
341 }),
342 },
343 ],
344 [
345 "xai",
346 {
347 driver: ProviderDriverKind.make("grok"),
348 header: () => ({
349 Authorization: "Bearer $TOKEN$",
350 "x-xai-token-auth": "xai-grok-cli",
351 "x-grok-client-version": GROK_CLI_VERSION,
352 "User-Agent": `grok-cli/${GROK_CLI_VERSION}`,
353 }),
354 read: Effect.fnUntraced(function* ({ account, call, checkedAt }) {
355 const usage = yield* decodeGrokUsage(yield* call(GROK_USAGE_URL));
356 return {
357 ...listedIdentity(account),
358 usageLimits: grokUsageResponseToLimits(usage, checkedAt),
359 };
360 }),
361 },
362 ],
363 [
364 "antigravity",
365 {
366 driver: ProviderDriverKind.make("antigravity"),
367 header: (_account, platform, architecture) => ({
368 Authorization: "Bearer $TOKEN$",
369 "Content-Type": "application/json",
370 "User-Agent": antigravityUserAgent(platform, architecture),
371 }),
372 read: Effect.fnUntraced(function* ({ account, call, checkedAt }) {
373 const project = account.project_id?.trim();
374 if (!project) {
375 return yield* new UsageLimitSourceError({ detail: "No Antigravity project reported." });
376 }
377 const requestedAt = DateTime.toEpochMillis(yield* DateTime.now);
378 const summary = yield* call(ANTIGRAVITY_SUMMARY_URL, { project });
379 const windows = yield* antigravitySummaryWindows(yield* decodeJson(summary), requestedAt);
380 if (windows.length === 0) {
381 return yield* new UsageLimitSourceError({ detail: "No Antigravity quota reported." });
382 }
383 // Local Antigravity reports no e-mail, so the Google account fingerprint is what pools the two.
384 const fingerprint = yield* call("https://www.googleapis.com/oauth2/v2/userinfo").pipe(
385 Effect.flatMap(decodeJson),
386 Effect.flatMap(antigravityAccountFingerprint),
387 Effect.option,
388 );
389 const usageLimits = makeUsageLimits({ checkedAt, windows });
390 return Option.match(fingerprint, {
391 onNone: () => ({ ...listedIdentity(account), usageLimits }),
392 onSome: (credentialFingerprint) => ({
393 usageLimits: { ...usageLimits, credentialFingerprint },
394 }),
395 });
396 }),
397 },
398 ],
399]);
400​
401export const makeCliproxyApi = Effect.gen(function* () {
402 const client = yield* HttpClient.HttpClient;
403 const digest = yield* Digest.Digest;
404 const platform = yield* HostProcess.Platform;
405 const architecture = yield* HostProcess.Architecture;
406​
407 const management = Effect.fn("CliproxyApi.management")(function* (
408 hub: CliproxyHub,
409 path: string,
410 body?: unknown,
411 ) {
412 const url = yield* Effect.try({
413 try: () => {
414 const base = new URL(hub.url);
415 // Users often paste the hub's web panel URL, which ends in management.html.
416 base.pathname = base.pathname.replace(/(\/management\.html)?\/?$/i, "/");
417 return new URL(`v0/management/${path}`, base).toString();
418 },
419 catch: () => new UsageLimitSourceError({ detail: "The hub URL is not valid." }),
420 });
421 const request = (
422 body === undefined ? HttpClientRequest.get(url) : HttpClientRequest.post(url)
423 ).pipe(HttpClientRequest.setHeader("Authorization", `Bearer ${hub.managementKey}`));
424 const response = yield* client
425 .execute(body === undefined ? request : request.pipe(HttpClientRequest.bodyJsonUnsafe(body)))
426 .pipe(
427 Effect.flatMap(HttpClientResponse.filterStatusOk),
428 Effect.flatMap((response) => response.json),
429 Effect.timeout("15 seconds"),
430 Effect.mapError(
431 (error) => new UsageLimitSourceError({ detail: describeManagementFailure(error) }),
432 ),
433 );
434 return response;
435 });
436​
437 const authFiles = Effect.fn("CliproxyApi.authFiles")(function* (hub: CliproxyHub) {
438 const response = yield* management(hub, "auth-files");
439 return (yield* decodeAuthFiles(response)).files;
440 });
441​
442 const apiCall = Effect.fn("CliproxyApi.apiCall")(function* (
443 hub: CliproxyHub,
444 account: AuthFile,
445 header: Record<string, string>,
446 url: string,
447 data?: unknown,
448 ) {
449 const raw = yield* management(hub, "api-call", {
450 auth_index: account.auth_index,
451 method: data === undefined ? "GET" : "POST",
452 url,
453 header,
454 ...(data === undefined ? {} : { data: yield* encodeJson(data) }),
455 });
456 const response = yield* decodeApiResponse(raw);
457 if (response.status_code < 200 || response.status_code >= 300) {
458 return yield* new UsageLimitSourceError({
459 detail: `The provider refused the hub request (HTTP ${response.status_code}).`,
460 });
461 }
462 return response.body;
463 });
464​
465 const readAccount = Effect.fn("CliproxyApi.readAccount")(function* (
466 hub: CliproxyHub,
467 account: AuthFile,
468 provider: HubProvider,
469 ) {
470 const checkedAt = DateTime.formatIso(yield* DateTime.now);
471 const call: HubCall = (url, data) =>
472 apiCall(hub, account, provider.header(account, platform, architecture), url, data);
473 const reading = yield* provider.read({ account, call, checkedAt }).pipe(
474 Effect.provideService(Digest.Digest, digest),
475 Effect.orElseSucceed(() => ({
476 ...listedIdentity(account),
477 usageLimits: makeUnavailableUsageLimits({
478 checkedAt,
479 reason: "probeFailed",
480 message: "The hub could not read this account's usage.",
481 }),
482 })),
483 );
484 return { id: account.id, driver: provider.driver, ...reading };
485 });
486​
487 const readAccounts = Effect.fn("CliproxyApi.readAccounts")(function* (
488 hub: CliproxyHub,
489 ): Effect.fn.Return<ReadonlyArray<UsageLimitSourceAccount>, UsageLimitSourceError> {
490 const accounts = yield* authFiles(hub).pipe(
491 Effect.mapError((error) =>
492 isUsageLimitSourceError(error)
493 ? error
494 : new UsageLimitSourceError({ detail: "The hub could not list accounts." }),
495 ),
496 );
497 return yield* Effect.forEach(
498 accounts.flatMap((account) => {
499 const provider = HUB_PROVIDERS.get(account.provider);
500 return provider && !account.disabled ? [{ account, provider }] : [];
501 }),
502 ({ account, provider }) => readAccount(hub, account, provider),
503 { concurrency: 4 },
504 );
505 });
506​
507 const consume = Effect.fn("CliproxyApi.consume")(function* (
508 hub: CliproxyHub,
509 accountId: string,
510 creditId: string,
511 ): Effect.fn.Return<ProviderConsumeResetCreditResult, UsageLimitSourceError> {
512 const operation = Effect.gen(function* () {
513 const account = (yield* authFiles(hub)).find((account) => account.id === accountId);
514 if (!account || account.disabled || account.provider !== "codex") {
515 return yield* new UsageLimitSourceError({
516 detail: "The Codex hub account is missing or disabled.",
517 });
518 }
519 const body = yield* apiCall(
520 hub,
521 account,
522 CODEX_HUB.header(account, platform, architecture),
523 `${CREDIT_URL}/consume`,
524 {
525 redeem_request_id: yield* creditRedeemRequestId(
526 account.id_token?.chatgpt_account_id ?? account.id,
527 creditId,
528 ).pipe(Effect.provideService(Digest.Digest, digest)),
529 credit_id: creditId,
530 },
531 );
532 const response = yield* decodeConsumeResponse(body);
533 const outcome = (
534 {
535 reset: "reset",
536 nothing_to_reset: "nothingToReset",
537 no_credit: "noCredit",
538 already_redeemed: "alreadyRedeemed",
539 } as const
540 )[response.code];
541 if (outcome !== "reset" && outcome !== "alreadyRedeemed") return { outcome };
542 const cleared = yield* management(hub, "reset-quota", {
543 auth_index: account.auth_index,
544 }).pipe(Effect.result);
545 return {
546 outcome,
547 ...(cleared._tag === "Failure"
548 ? {
549 warning:
550 "Credit redeemed, but the hub cooldown could not be cleared. Routing may resume after its cooldown expires.",
551 }
552 : {}),
553 } as const;
554 });
555 return yield* operation.pipe(
556 Effect.mapError((error) =>
557 isUsageLimitSourceError(error)
558 ? error
559 : new UsageLimitSourceError({
560 detail: "The hub returned an unexpected reset-credit response.",
561 }),
562 ),
563 );
564 });
565 return { readAccounts, consume };
566});