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

cliproxyApi.ts

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