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

cliproxyApi.ts

551 lines19.8 KB

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