Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

cliproxyApi.ts

441 lines16.1 KB

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