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