Open History to see the last commit
1import * as NodeCrypto from "node:crypto";
2
3import {
4 ProviderDriverKind,
5 UsageLimitSourceError,
6 type ProviderConsumeResetCreditResult,
7 type UsageLimitSourceAccount,
8 type UsageLimitSourceConfig,
9} from "@t3tools/contracts";
10import * as DateTime from "effect/DateTime";
11import * as Effect from "effect/Effect";
12import * as Schema from "effect/Schema";
13import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
14
15import { codexPlanLabel } from "../provider/Layers/CodexProvider.ts";
16import { codexRateLimitsToLimits } from "../provider/Layers/codexUsageLimits.ts";
17import { claudeUsageResponseToLimits } from "../provider/Layers/claudeUsageLimits.ts";
18import { makeUnavailableUsageLimits } from "../provider/providerUsageLimits.ts";
19
20const AuthFile = Schema.Struct({
21 id: Schema.String,
22 auth_index: Schema.String,
23 provider: Schema.String,
24 email: Schema.optional(Schema.String),
25 disabled: Schema.optional(Schema.Boolean),
26 id_token: Schema.optional(
27 Schema.Struct({
28 chatgpt_account_id: Schema.optional(Schema.String),
29 chatgpt_plan_type: Schema.optional(Schema.String),
30 }),
31 ),
32});
33const AuthFiles = Schema.Struct({ files: Schema.Array(AuthFile) });
34const ApiResponse = Schema.Struct({ status_code: Schema.Number, body: Schema.String });
35const CodexWindow = Schema.Struct({
36 used_percent: Schema.Number,
37 reset_at: Schema.optional(Schema.NullOr(Schema.Number)),
38 limit_window_seconds: Schema.optional(Schema.Number),
39});
40const CodexUsage = Schema.Struct({
41 plan_type: Schema.optional(Schema.String),
42 rate_limit: Schema.NullOr(
43 Schema.Struct({
44 primary_window: Schema.optional(Schema.NullOr(CodexWindow)),
45 secondary_window: Schema.optional(Schema.NullOr(CodexWindow)),
46 }),
47 ),
48});
49const ClaudeWindow = Schema.Struct({
50 utilization: Schema.Number,
51 resets_at: Schema.NullOr(Schema.String),
52});
53const ClaudeUsage = Schema.Struct({
54 five_hour: Schema.optional(Schema.NullOr(ClaudeWindow)),
55 seven_day: Schema.optional(Schema.NullOr(ClaudeWindow)),
56 limits: Schema.optional(
57 Schema.Array(
58 Schema.Struct({
59 kind: Schema.String,
60 percent: Schema.optional(Schema.NullOr(Schema.Number)),
61 resets_at: Schema.optional(Schema.NullOr(Schema.String)),
62 scope: Schema.optional(
63 Schema.NullOr(
64 Schema.Struct({
65 model: Schema.optional(Schema.NullOr(Schema.Struct({ display_name: Schema.String }))),
66 }),
67 ),
68 ),
69 }),
70 ),
71 ),
72});
73const CreditList = Schema.Struct({
74 credits: Schema.Array(
75 Schema.Struct({
76 id: Schema.String,
77 status: Schema.String,
78 reset_type: Schema.String,
79 expires_at: Schema.String,
80 }),
81 ),
82});
83
84const decodeAuthFiles = Schema.decodeUnknownEffect(AuthFiles);
85const encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
86const decodeApiResponse = Schema.decodeUnknownEffect(ApiResponse);
87const decodeCreditList = Schema.decodeUnknownEffect(Schema.fromJsonString(CreditList));
88const decodeClaudeUsage = Schema.decodeUnknownEffect(Schema.fromJsonString(ClaudeUsage));
89const decodeCodexUsage = Schema.decodeUnknownEffect(Schema.fromJsonString(CodexUsage));
90const isUsageLimitSourceError = Schema.is(UsageLimitSourceError);
91const decodeConsumeResponse = Schema.decodeUnknownEffect(
92 Schema.fromJsonString(
93 Schema.Struct({
94 code: Schema.Literals(["reset", "nothing_to_reset", "no_credit", "already_redeemed"]),
95 }),
96 ),
97);
98
99const CODEX_BASE = "https://chatgpt.com/backend-api/wham";
100const CREDIT_URL = `${CODEX_BASE}/rate-limit-reset-credits`;
101
102// UUIDv5 per account and credit also deduplicates retries across T3 environments.
103export function creditRedeemRequestId(accountId: string, creditId: string): string {
104 const bytes = NodeCrypto.createHash("sha1")
105 .update(Buffer.from("6f1c2a9e2d4b4c1e9a7f3b8d5e0c1a42", "hex"))
106 .update(`${accountId}:${creditId}`)
107 .digest()
108 .subarray(0, 16);
109 bytes[6] = (bytes[6]! & 0x0f) | 0x50;
110 bytes[8] = (bytes[8]! & 0x3f) | 0x80;
111 const hex = bytes.toString("hex");
112 return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
113}
114
115export const makeCliproxyApi = Effect.gen(function* () {
116 const client = yield* HttpClient.HttpClient;
117
118 const management = Effect.fn("CliproxyApi.management")(function* (
119 config: UsageLimitSourceConfig,
120 path: string,
121 body?: unknown,
122 ) {
123 const url = yield* Effect.try({
124 try: () => new URL(`/v0/management/${path}`, config.url).toString(),
125 catch: () => new UsageLimitSourceError({ detail: "The hub URL is not valid." }),
126 });
127 const request = (
128 body === undefined ? HttpClientRequest.get(url) : HttpClientRequest.post(url)
129 ).pipe(HttpClientRequest.setHeader("Authorization", `Bearer ${config.managementKey}`));
130 const response = yield* client
131 .execute(body === undefined ? request : request.pipe(HttpClientRequest.bodyJsonUnsafe(body)))
132 .pipe(
133 Effect.flatMap(HttpClientResponse.filterStatusOk),
134 Effect.flatMap((response) => response.json),
135 Effect.timeout("15 seconds"),
136 Effect.mapError(
137 () => new UsageLimitSourceError({ detail: "The hub management request failed." }),
138 ),
139 );
140 return response;
141 });
142
143 const authFiles = Effect.fn("CliproxyApi.authFiles")(function* (config: UsageLimitSourceConfig) {
144 const response = yield* management(config, "auth-files");
145 return (yield* decodeAuthFiles(response)).files;
146 });
147
148 const apiCall = Effect.fn("CliproxyApi.apiCall")(function* (
149 config: UsageLimitSourceConfig,
150 account: typeof AuthFile.Type,
151 url: string,
152 data?: unknown,
153 ) {
154 const header =
155 account.provider === "codex"
156 ? {
157 Authorization: "Bearer $TOKEN$",
158 "Content-Type": "application/json",
159 "OpenAI-Beta": "codex-1",
160 Originator: "Codex Desktop",
161 ...(account.id_token?.chatgpt_account_id
162 ? { "Chatgpt-Account-Id": account.id_token.chatgpt_account_id }
163 : {}),
164 }
165 : { Authorization: "Bearer $TOKEN$", "anthropic-beta": "oauth-2025-04-20" };
166 const raw = yield* management(config, "api-call", {
167 auth_index: account.auth_index,
168 method: data === undefined ? "GET" : "POST",
169 url,
170 header,
171 ...(data === undefined ? {} : { data: yield* encodeJson(data) }),
172 });
173 const response = yield* decodeApiResponse(raw);
174 if (response.status_code < 200 || response.status_code >= 300) {
175 return yield* new UsageLimitSourceError({
176 detail: `The provider refused the hub request (HTTP ${response.status_code}).`,
177 });
178 }
179 return response.body;
180 });
181
182 const credits = Effect.fn("CliproxyApi.credits")(function* (
183 config: UsageLimitSourceConfig,
184 account: typeof AuthFile.Type,
185 ) {
186 const body = yield* apiCall(config, account, CREDIT_URL);
187 const response = yield* decodeCreditList(body);
188 const now = DateTime.toEpochMillis(yield* DateTime.now);
189 return response.credits
190 .filter(
191 (credit) =>
192 credit.reset_type === "codex_rate_limits" &&
193 credit.status === "available" &&
194 Date.parse(credit.expires_at) > now,
195 )
196 .toSorted((a, b) => Date.parse(a.expires_at) - Date.parse(b.expires_at));
197 });
198
199 const readAccount = Effect.fn("CliproxyApi.readAccount")(function* (
200 config: UsageLimitSourceConfig,
201 account: typeof AuthFile.Type,
202 ) {
203 const checkedAt = DateTime.formatIso(yield* DateTime.now);
204 const base = {
205 id: account.id,
206 driver: ProviderDriverKind.make(account.provider === "codex" ? "codex" : "claudeAgent"),
207 ...(account.email ? { email: account.email } : {}),
208 };
209 const read = Effect.gen(function* () {
210 if (account.provider === "claude") {
211 const body = yield* apiCall(config, account, "https://api.anthropic.com/api/oauth/usage");
212 const usage = yield* decodeClaudeUsage(body);
213 const model_scoped = (usage.limits ?? []).flatMap((limit) =>
214 limit.kind === "weekly_scoped" && limit.scope?.model && typeof limit.percent === "number"
215 ? [
216 {
217 display_name: limit.scope.model.display_name,
218 utilization: limit.percent,
219 resets_at: limit.resets_at ?? null,
220 },
221 ]
222 : [],
223 );
224 return {
225 ...base,
226 plan: "Claude Subscription",
227 usageLimits: claudeUsageResponseToLimits({
228 checkedAt,
229 response: {
230 rate_limits_available: true,
231 rate_limits: {
232 five_hour: usage.five_hour ?? null,
233 seven_day: usage.seven_day ?? null,
234 model_scoped,
235 },
236 },
237 }).limits,
238 };
239 }
240 const body = yield* apiCall(config, account, `${CODEX_BASE}/usage`);
241 const usage = yield* decodeCodexUsage(body);
242 const toWindow = (window: typeof CodexWindow.Type | null | undefined) =>
243 window
244 ? {
245 usedPercent: window.used_percent,
246 resetsAt: window.reset_at ?? null,
247 ...(window.limit_window_seconds === undefined
248 ? {}
249 : { windowDurationMins: window.limit_window_seconds / 60 }),
250 }
251 : null;
252 // A credits outage must not hide successfully fetched quota windows.
253 const available = yield* credits(config, account).pipe(Effect.orElseSucceed(() => undefined));
254 const next = available?.[0];
255 return {
256 ...base,
257 plan: codexPlanLabel(usage.plan_type ?? account.id_token?.chatgpt_plan_type),
258 usageLimits: {
259 ...codexRateLimitsToLimits({
260 checkedAt,
261 snapshot: {
262 planType: usage.plan_type ?? null,
263 primary: toWindow(usage.rate_limit?.primary_window),
264 secondary: toWindow(usage.rate_limit?.secondary_window),
265 },
266 }),
267 ...(available
268 ? {
269 resetCredits: {
270 availableCount: available.length,
271 ...(next
272 ? {
273 nextCreditId: next.id,
274 nextExpiresAt: DateTime.formatIso(DateTime.makeUnsafe(next.expires_at)),
275 }
276 : {}),
277 },
278 }
279 : {}),
280 },
281 };
282 });
283 return yield* read.pipe(
284 Effect.orElseSucceed(() => ({
285 ...base,
286 usageLimits: makeUnavailableUsageLimits({
287 checkedAt,
288 reason: "probeFailed",
289 message: "The hub could not read this account's usage.",
290 }),
291 })),
292 );
293 });
294
295 const readAccounts = Effect.fn("CliproxyApi.readAccounts")(function* (
296 config: UsageLimitSourceConfig,
297 ): Effect.fn.Return<ReadonlyArray<UsageLimitSourceAccount>, UsageLimitSourceError> {
298 const accounts = yield* authFiles(config).pipe(
299 Effect.mapError(
300 () => new UsageLimitSourceError({ detail: "The hub could not list accounts." }),
301 ),
302 );
303 return yield* Effect.forEach(
304 accounts.filter(
305 (account) =>
306 !account.disabled && (account.provider === "codex" || account.provider === "claude"),
307 ),
308 (account) => readAccount(config, account),
309 { concurrency: 4 },
310 );
311 });
312
313 const consume = Effect.fn("CliproxyApi.consume")(function* (
314 config: UsageLimitSourceConfig,
315 accountId: string,
316 creditId: string,
317 ): Effect.fn.Return<ProviderConsumeResetCreditResult, UsageLimitSourceError> {
318 const operation = Effect.gen(function* () {
319 const account = (yield* authFiles(config)).find((account) => account.id === accountId);
320 if (!account || account.disabled || account.provider !== "codex") {
321 return yield* new UsageLimitSourceError({
322 detail: "The Codex hub account is missing or disabled.",
323 });
324 }
325 const body = yield* apiCall(config, account, `${CREDIT_URL}/consume`, {
326 redeem_request_id: creditRedeemRequestId(
327 account.id_token?.chatgpt_account_id ?? account.id,
328 creditId,
329 ),
330 credit_id: creditId,
331 });
332 const response = yield* decodeConsumeResponse(body);
333 const outcome = (
334 {
335 reset: "reset",
336 nothing_to_reset: "nothingToReset",
337 no_credit: "noCredit",
338 already_redeemed: "alreadyRedeemed",
339 } as const
340 )[response.code];
341 if (outcome !== "reset" && outcome !== "alreadyRedeemed") return { outcome };
342 const cleared = yield* management(config, "reset-quota", {
343 auth_index: account.auth_index,
344 }).pipe(Effect.result);
345 return {
346 outcome,
347 ...(cleared._tag === "Failure"
348 ? {
349 warning:
350 "Credit redeemed, but the hub cooldown could not be cleared. Routing may resume after its cooldown expires.",
351 }
352 : {}),
353 } as const;
354 });
355 return yield* operation.pipe(
356 Effect.mapError((error) =>
357 isUsageLimitSourceError(error)
358 ? error
359 : new UsageLimitSourceError({
360 detail: "The hub returned an unexpected reset-credit response.",
361 }),
362 ),
363 );
364 });
365 return { readAccounts, consume };
366});