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 Crypto from "effect/Crypto";
9import * as DateTime from "effect/DateTime";
10import * as Effect from "effect/Effect";
11import * as Hex from "effect/encoding/Hex";
12import * as Schema from "effect/Schema";
13import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
14
15import { codexPlanLabel } from "../provider/CodexProvider.ts";
16import { codexRateLimitsToLimits } from "../provider/codexUsageLimits.ts";
17import { claudeUsageResponseToLimits } from "../provider/claudeUsageLimits.ts";
18import { makeUnavailableUsageLimits } from "@t3tools/provider-core/server/usageLimits";
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
102const CREDIT_REDEEM_NAMESPACE = new Uint8Array([
103 0x6f, 0x1c, 0x2a, 0x9e, 0x2d, 0x4b, 0x4c, 0x1e, 0x9a, 0x7f, 0x3b, 0x8d, 0x5e, 0x0c, 0x1a, 0x42,
104]);
105
106// UUIDv5 per account and credit also deduplicates retries across T3 environments.
107const creditRedeemRequestId = Effect.fn("CliproxyApi.creditRedeemRequestId")(function* (
108 accountId: string,
109 creditId: string,
110) {
111 const crypto = yield* Crypto.Crypto;
112 const name = new TextEncoder().encode(`${accountId}:${creditId}`);
113 const input = new Uint8Array(CREDIT_REDEEM_NAMESPACE.length + name.length);
114 input.set(CREDIT_REDEEM_NAMESPACE);
115 input.set(name, CREDIT_REDEEM_NAMESPACE.length);
116 const bytes = (yield* crypto.digest("SHA-1", input).pipe(Effect.orDie)).slice(0, 16);
117 bytes[6] = (bytes[6]! & 0x0f) | 0x50;
118 bytes[8] = (bytes[8]! & 0x3f) | 0x80;
119 const hex = Hex.encode(bytes);
120 return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
121});
122
123export const makeCliproxyApi = Effect.gen(function* () {
124 const client = yield* HttpClient.HttpClient;
125 const crypto = yield* Crypto.Crypto;
126
127 const management = Effect.fn("CliproxyApi.management")(function* (
128 config: UsageLimitSourceConfig,
129 path: string,
130 body?: unknown,
131 ) {
132 const url = yield* Effect.try({
133 try: () => new URL(`/v0/management/${path}`, config.url).toString(),
134 catch: () => new UsageLimitSourceError({ detail: "The hub URL is not valid." }),
135 });
136 const request = (
137 body === undefined ? HttpClientRequest.get(url) : HttpClientRequest.post(url)
138 ).pipe(HttpClientRequest.setHeader("Authorization", `Bearer ${config.managementKey}`));
139 const response = yield* client
140 .execute(body === undefined ? request : request.pipe(HttpClientRequest.bodyJsonUnsafe(body)))
141 .pipe(
142 Effect.flatMap(HttpClientResponse.filterStatusOk),
143 Effect.flatMap((response) => response.json),
144 Effect.timeout("15 seconds"),
145 Effect.mapError(
146 () => new UsageLimitSourceError({ detail: "The hub management request failed." }),
147 ),
148 );
149 return response;
150 });
151
152 const authFiles = Effect.fn("CliproxyApi.authFiles")(function* (config: UsageLimitSourceConfig) {
153 const response = yield* management(config, "auth-files");
154 return (yield* decodeAuthFiles(response)).files;
155 });
156
157 const apiCall = Effect.fn("CliproxyApi.apiCall")(function* (
158 config: UsageLimitSourceConfig,
159 account: typeof AuthFile.Type,
160 url: string,
161 data?: unknown,
162 ) {
163 const header =
164 account.provider === "codex"
165 ? {
166 Authorization: "Bearer $TOKEN$",
167 "Content-Type": "application/json",
168 "OpenAI-Beta": "codex-1",
169 Originator: "Codex Desktop",
170 ...(account.id_token?.chatgpt_account_id
171 ? { "Chatgpt-Account-Id": account.id_token.chatgpt_account_id }
172 : {}),
173 }
174 : { Authorization: "Bearer $TOKEN$", "anthropic-beta": "oauth-2025-04-20" };
175 const raw = yield* management(config, "api-call", {
176 auth_index: account.auth_index,
177 method: data === undefined ? "GET" : "POST",
178 url,
179 header,
180 ...(data === undefined ? {} : { data: yield* encodeJson(data) }),
181 });
182 const response = yield* decodeApiResponse(raw);
183 if (response.status_code < 200 || response.status_code >= 300) {
184 return yield* new UsageLimitSourceError({
185 detail: `The provider refused the hub request (HTTP ${response.status_code}).`,
186 });
187 }
188 return response.body;
189 });
190
191 const credits = Effect.fn("CliproxyApi.credits")(function* (
192 config: UsageLimitSourceConfig,
193 account: typeof AuthFile.Type,
194 ) {
195 const body = yield* apiCall(config, account, CREDIT_URL);
196 const response = yield* decodeCreditList(body);
197 const now = DateTime.toEpochMillis(yield* DateTime.now);
198 return response.credits
199 .filter(
200 (credit) =>
201 credit.reset_type === "codex_rate_limits" &&
202 credit.status === "available" &&
203 Date.parse(credit.expires_at) > now,
204 )
205 .toSorted((a, b) => Date.parse(a.expires_at) - Date.parse(b.expires_at));
206 });
207
208 const readAccount = Effect.fn("CliproxyApi.readAccount")(function* (
209 config: UsageLimitSourceConfig,
210 account: typeof AuthFile.Type,
211 ) {
212 const checkedAt = DateTime.formatIso(yield* DateTime.now);
213 const base = {
214 id: account.id,
215 driver: ProviderDriverKind.make(account.provider === "codex" ? "codex" : "claudeAgent"),
216 ...(account.email ? { email: account.email } : {}),
217 ...(account.id_token?.chatgpt_account_id?.trim()
218 ? { workspaceId: account.id_token.chatgpt_account_id.trim() }
219 : {}),
220 };
221 const read = Effect.gen(function* () {
222 if (account.provider === "claude") {
223 const body = yield* apiCall(config, account, "https://api.anthropic.com/api/oauth/usage");
224 const usage = yield* decodeClaudeUsage(body);
225 const model_scoped = (usage.limits ?? []).flatMap((limit) =>
226 limit.kind === "weekly_scoped" && limit.scope?.model && typeof limit.percent === "number"
227 ? [
228 {
229 display_name: limit.scope.model.display_name,
230 utilization: limit.percent,
231 resets_at: limit.resets_at ?? null,
232 },
233 ]
234 : [],
235 );
236 return {
237 ...base,
238 plan: "Claude Subscription",
239 usageLimits: claudeUsageResponseToLimits({
240 checkedAt,
241 response: {
242 rate_limits_available: true,
243 rate_limits: {
244 five_hour: usage.five_hour ?? null,
245 seven_day: usage.seven_day ?? null,
246 model_scoped,
247 },
248 },
249 }).limits,
250 };
251 }
252 const body = yield* apiCall(config, account, `${CODEX_BASE}/usage`);
253 const usage = yield* decodeCodexUsage(body);
254 const toWindow = (window: typeof CodexWindow.Type | null | undefined) =>
255 window
256 ? {
257 usedPercent: window.used_percent,
258 resetsAt: window.reset_at ?? null,
259 ...(window.limit_window_seconds === undefined
260 ? {}
261 : { windowDurationMins: window.limit_window_seconds / 60 }),
262 }
263 : null;
264 const available = yield* credits(config, account).pipe(Effect.orElseSucceed(() => undefined));
265 const next = available?.[0];
266 return {
267 ...base,
268 plan: codexPlanLabel(usage.plan_type ?? account.id_token?.chatgpt_plan_type),
269 usageLimits: {
270 ...codexRateLimitsToLimits({
271 checkedAt,
272 snapshot: {
273 planType: usage.plan_type ?? null,
274 primary: toWindow(usage.rate_limit?.primary_window),
275 secondary: toWindow(usage.rate_limit?.secondary_window),
276 },
277 }),
278 ...(available
279 ? {
280 resetCredits: {
281 availableCount: available.length,
282 ...(next
283 ? {
284 nextCreditId: next.id,
285 nextExpiresAt: DateTime.formatIso(DateTime.makeUnsafe(next.expires_at)),
286 }
287 : {}),
288 },
289 }
290 : {}),
291 },
292 };
293 });
294 return yield* read.pipe(
295 Effect.orElseSucceed(() => ({
296 ...base,
297 usageLimits: makeUnavailableUsageLimits({
298 checkedAt,
299 reason: "probeFailed",
300 message: "The hub could not read this account's usage.",
301 }),
302 })),
303 );
304 });
305
306 const readAccounts = Effect.fn("CliproxyApi.readAccounts")(function* (
307 config: UsageLimitSourceConfig,
308 ): Effect.fn.Return<ReadonlyArray<UsageLimitSourceAccount>, UsageLimitSourceError> {
309 const accounts = yield* authFiles(config).pipe(
310 Effect.mapError(
311 () => new UsageLimitSourceError({ detail: "The hub could not list accounts." }),
312 ),
313 );
314 return yield* Effect.forEach(
315 accounts.filter(
316 (account) =>
317 !account.disabled && (account.provider === "codex" || account.provider === "claude"),
318 ),
319 (account) => readAccount(config, account),
320 { concurrency: 4 },
321 );
322 });
323
324 const consume = Effect.fn("CliproxyApi.consume")(function* (
325 config: UsageLimitSourceConfig,
326 accountId: string,
327 creditId: string,
328 ): Effect.fn.Return<ProviderConsumeResetCreditResult, UsageLimitSourceError> {
329 const operation = Effect.gen(function* () {
330 const account = (yield* authFiles(config)).find((account) => account.id === accountId);
331 if (!account || account.disabled || account.provider !== "codex") {
332 return yield* new UsageLimitSourceError({
333 detail: "The Codex hub account is missing or disabled.",
334 });
335 }
336 const body = yield* apiCall(config, account, `${CREDIT_URL}/consume`, {
337 redeem_request_id: yield* creditRedeemRequestId(
338 account.id_token?.chatgpt_account_id ?? account.id,
339 creditId,
340 ).pipe(Effect.provideService(Crypto.Crypto, crypto)),
341 credit_id: creditId,
342 });
343 const response = yield* decodeConsumeResponse(body);
344 const outcome = (
345 {
346 reset: "reset",
347 nothing_to_reset: "nothingToReset",
348 no_credit: "noCredit",
349 already_redeemed: "alreadyRedeemed",
350 } as const
351 )[response.code];
352 if (outcome !== "reset" && outcome !== "alreadyRedeemed") return { outcome };
353 const cleared = yield* management(config, "reset-quota", {
354 auth_index: account.auth_index,
355 }).pipe(Effect.result);
356 return {
357 outcome,
358 ...(cleared._tag === "Failure"
359 ? {
360 warning:
361 "Credit redeemed, but the hub cooldown could not be cleared. Routing may resume after its cooldown expires.",
362 }
363 : {}),
364 } as const;
365 });
366 return yield* operation.pipe(
367 Effect.mapError((error) =>
368 isUsageLimitSourceError(error)
369 ? error
370 : new UsageLimitSourceError({
371 detail: "The hub returned an unexpected reset-credit response.",
372 }),
373 ),
374 );
375 });
376 return { readAccounts, consume };
377});