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

cliproxyApi.ts

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