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