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 new URL(
189 `v0/management/${path}`,
190 hub.url.endsWith("/") ? hub.url : `${hub.url}/`,
191 ).toString(),
192 catch: () => new UsageLimitSourceError({ detail: "The hub URL is not valid." }),
193 });
194 const request = (
195 body === undefined ? HttpClientRequest.get(url) : HttpClientRequest.post(url)
196 ).pipe(HttpClientRequest.setHeader("Authorization", `Bearer ${hub.managementKey}`));
197 const response = yield* client
198 .execute(body === undefined ? request : request.pipe(HttpClientRequest.bodyJsonUnsafe(body)))
199 .pipe(
200 Effect.flatMap(HttpClientResponse.filterStatusOk),
201 Effect.flatMap((response) => response.json),
202 Effect.timeout("15 seconds"),
203 Effect.mapError(
204 (error) => new UsageLimitSourceError({ detail: describeManagementFailure(error) }),
205 ),
206 );
207 return response;
208 });
209
210 const authFiles = Effect.fn("CliproxyApi.authFiles")(function* (hub: CliproxyHub) {
211 const response = yield* management(hub, "auth-files");
212 return (yield* decodeAuthFiles(response)).files;
213 });
214
215 const apiCall = Effect.fn("CliproxyApi.apiCall")(function* (
216 hub: CliproxyHub,
217 account: typeof AuthFile.Type,
218 url: string,
219 data?: unknown,
220 ) {
221 const header =
222 account.provider === "codex"
223 ? {
224 Authorization: "Bearer $TOKEN$",
225 "Content-Type": "application/json",
226 "OpenAI-Beta": "codex-1",
227 Originator: "Codex Desktop",
228 ...(account.id_token?.chatgpt_account_id
229 ? { "Chatgpt-Account-Id": account.id_token.chatgpt_account_id }
230 : {}),
231 }
232 : {
233 Authorization: "Bearer $TOKEN$",
234 "anthropic-beta": "oauth-2025-04-20",
235 // The OAuth usage endpoint can return 429 without a Claude Code user agent.
236 "User-Agent": "claude-code/2.1.273",
237 };
238 const raw = yield* management(hub, "api-call", {
239 auth_index: account.auth_index,
240 method: data === undefined ? "GET" : "POST",
241 url,
242 header,
243 ...(data === undefined ? {} : { data: yield* encodeJson(data) }),
244 });
245 const response = yield* decodeApiResponse(raw);
246 if (response.status_code < 200 || response.status_code >= 300) {
247 return yield* new UsageLimitSourceError({
248 detail: `The provider refused the hub request (HTTP ${response.status_code}).`,
249 });
250 }
251 return response.body;
252 });
253
254 const credits = Effect.fn("CliproxyApi.credits")(function* (
255 hub: CliproxyHub,
256 account: typeof AuthFile.Type,
257 ) {
258 const body = yield* apiCall(hub, account, CREDIT_URL);
259 const response = yield* decodeCreditList(body);
260 const now = DateTime.toEpochMillis(yield* DateTime.now);
261 return response.credits
262 .filter(
263 (credit) =>
264 credit.reset_type === "codex_rate_limits" &&
265 credit.status === "available" &&
266 Date.parse(credit.expires_at) > now,
267 )
268 .toSorted((a, b) => Date.parse(a.expires_at) - Date.parse(b.expires_at));
269 });
270
271 const readAccount = Effect.fn("CliproxyApi.readAccount")(function* (
272 hub: CliproxyHub,
273 account: typeof AuthFile.Type,
274 ) {
275 const checkedAt = DateTime.formatIso(yield* DateTime.now);
276 const base = {
277 id: account.id,
278 driver: ProviderDriverKind.make(account.provider === "codex" ? "codex" : "claudeAgent"),
279 ...(account.email ? { email: account.email } : {}),
280 ...(account.id_token?.chatgpt_account_id?.trim()
281 ? { workspaceId: account.id_token.chatgpt_account_id.trim() }
282 : {}),
283 };
284 const read = Effect.gen(function* () {
285 if (account.provider === "claude") {
286 const body = yield* apiCall(hub, account, "https://api.anthropic.com/api/oauth/usage");
287 const usage = yield* decodeClaudeUsage(body);
288 const model_scoped = (usage.limits ?? []).flatMap((limit) =>
289 limit.kind === "weekly_scoped" && limit.scope?.model && typeof limit.percent === "number"
290 ? [
291 {
292 display_name: limit.scope.model.display_name,
293 utilization: limit.percent,
294 resets_at: limit.resets_at ?? null,
295 },
296 ]
297 : [],
298 );
299 const rateLimits = {
300 five_hour: usage.five_hour ?? null,
301 seven_day: usage.seven_day ?? null,
302 model_scoped,
303 spend: usage.spend,
304 extra_usage: usage.extra_usage ?? null,
305 };
306 return {
307 ...base,
308 plan: "Claude Subscription",
309 usageLimits: claudeUsageResponseToLimits({
310 checkedAt,
311 response: {
312 rate_limits_available: true,
313 rate_limits: rateLimits,
314 },
315 }).limits,
316 };
317 }
318 const body = yield* apiCall(hub, account, `${CODEX_BASE}/usage`);
319 const usage = yield* decodeCodexUsage(body);
320 const toWindow = (window: typeof CodexWindow.Type | null | undefined) =>
321 window
322 ? {
323 usedPercent: window.used_percent,
324 resetsAt: window.reset_at ?? null,
325 ...(window.limit_window_seconds === undefined
326 ? {}
327 : { windowDurationMins: window.limit_window_seconds / 60 }),
328 }
329 : null;
330 const available = yield* credits(hub, account).pipe(Effect.orElseSucceed(() => undefined));
331 const next = available?.[0];
332 const planType =
333 usage.plan_type ?? account.id_token?.plan_type ?? account.id_token?.chatgpt_plan_type;
334 return {
335 ...base,
336 plan: codexPlanLabel(planType),
337 usageLimits: {
338 ...codexRateLimitsToLimits({
339 checkedAt,
340 snapshot: {
341 planType: planType ?? null,
342 primary: toWindow(usage.rate_limit?.primary_window),
343 secondary: toWindow(usage.rate_limit?.secondary_window),
344 },
345 }),
346 ...(available
347 ? {
348 resetCredits: {
349 availableCount: available.length,
350 ...(next
351 ? {
352 nextCreditId: next.id,
353 nextExpiresAt: DateTime.formatIso(DateTime.makeUnsafe(next.expires_at)),
354 }
355 : {}),
356 },
357 }
358 : {}),
359 },
360 };
361 });
362 return yield* read.pipe(
363 Effect.orElseSucceed(() => ({
364 ...base,
365 usageLimits: makeUnavailableUsageLimits({
366 checkedAt,
367 reason: "probeFailed",
368 message: "The hub could not read this account's usage.",
369 }),
370 })),
371 );
372 });
373
374 const readAccounts = Effect.fn("CliproxyApi.readAccounts")(function* (
375 hub: CliproxyHub,
376 ): Effect.fn.Return<ReadonlyArray<UsageLimitSourceAccount>, UsageLimitSourceError> {
377 const accounts = yield* authFiles(hub).pipe(
378 Effect.mapError((error) =>
379 isUsageLimitSourceError(error)
380 ? error
381 : new UsageLimitSourceError({ detail: "The hub could not list accounts." }),
382 ),
383 );
384 return yield* Effect.forEach(
385 accounts.filter(
386 (account) =>
387 !account.disabled && (account.provider === "codex" || account.provider === "claude"),
388 ),
389 (account) => readAccount(hub, account),
390 { concurrency: 4 },
391 );
392 });
393
394 const consume = Effect.fn("CliproxyApi.consume")(function* (
395 hub: CliproxyHub,
396 accountId: string,
397 creditId: string,
398 ): Effect.fn.Return<ProviderConsumeResetCreditResult, UsageLimitSourceError> {
399 const operation = Effect.gen(function* () {
400 const account = (yield* authFiles(hub)).find((account) => account.id === accountId);
401 if (!account || account.disabled || account.provider !== "codex") {
402 return yield* new UsageLimitSourceError({
403 detail: "The Codex hub account is missing or disabled.",
404 });
405 }
406 const body = yield* apiCall(hub, account, `${CREDIT_URL}/consume`, {
407 redeem_request_id: yield* creditRedeemRequestId(
408 account.id_token?.chatgpt_account_id ?? account.id,
409 creditId,
410 ).pipe(Effect.provideService(Digest.Digest, digest)),
411 credit_id: creditId,
412 });
413 const response = yield* decodeConsumeResponse(body);
414 const outcome = (
415 {
416 reset: "reset",
417 nothing_to_reset: "nothingToReset",
418 no_credit: "noCredit",
419 already_redeemed: "alreadyRedeemed",
420 } as const
421 )[response.code];
422 if (outcome !== "reset" && outcome !== "alreadyRedeemed") return { outcome };
423 const cleared = yield* management(hub, "reset-quota", {
424 auth_index: account.auth_index,
425 }).pipe(Effect.result);
426 return {
427 outcome,
428 ...(cleared._tag === "Failure"
429 ? {
430 warning:
431 "Credit redeemed, but the hub cooldown could not be cleared. Routing may resume after its cooldown expires.",
432 }
433 : {}),
434 } as const;
435 });
436 return yield* operation.pipe(
437 Effect.mapError((error) =>
438 isUsageLimitSourceError(error)
439 ? error
440 : new UsageLimitSourceError({
441 detail: "The hub returned an unexpected reset-credit response.",
442 }),
443 ),
444 );
445 });
446 return { readAccounts, consume };
447});