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