Open History to see the last commit
1import {
2 ProviderDriverKind,
3 UsageLimitSourceError,
4 type ProviderConsumeResetCreditResult,
5 type ServerProviderUsageWindow,
6 type UsageLimitSourceAccount,
7 type UsageLimitSourceConfig,
8} from "@t3tools/contracts";
9import * as Cause from "effect/Cause";
10import * as Digest from "effect/crypto/Digest";
11import * as DateTime from "effect/DateTime";
12import * as Effect from "effect/Effect";
13import * as Hex from "effect/encoding/Hex";
14import * as Option from "effect/Option";
15import * as Schema from "effect/Schema";
16import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http";
17
18import { codexPlanLabel } from "../provider/CodexProvider.ts";
19import { codexRateLimitsToLimits } from "../provider/codexUsageLimits.ts";
20import { claudeUsageResponseToLimits } from "../provider/claudeUsageLimits.ts";
21import {
22 clampPercent,
23 makeUnavailableUsageLimits,
24 makeUsageLimits,
25} from "@t3tools/provider-core/server/usageLimits";
26
27/** A hub with its management key already read from wherever the setting keeps it. */
28export interface CliproxyHub {
29 readonly url: UsageLimitSourceConfig["url"];
30 readonly managementKey: string;
31}
32
33const AuthFile = Schema.Struct({
34 id: Schema.String,
35 auth_index: Schema.String,
36 provider: Schema.String,
37 email: Schema.optional(Schema.String),
38 disabled: Schema.optional(Schema.Boolean),
39 id_token: Schema.optional(
40 Schema.Struct({
41 chatgpt_account_id: Schema.optional(Schema.String),
42 chatgpt_plan_type: Schema.optional(Schema.String),
43 plan_type: Schema.optional(Schema.String),
44 }),
45 ),
46});
47const AuthFiles = Schema.Struct({ files: Schema.Array(AuthFile) });
48const AuthFileModels = Schema.Struct({
49 models: Schema.Array(Schema.Struct({ id: Schema.String })),
50});
51const ApiResponse = Schema.Struct({ status_code: Schema.Number, body: Schema.String });
52const CodexWindow = Schema.Struct({
53 used_percent: Schema.Number,
54 reset_at: Schema.optional(Schema.NullOr(Schema.Number)),
55 limit_window_seconds: Schema.optional(Schema.Number),
56});
57const CodexUsage = Schema.Struct({
58 plan_type: Schema.optional(Schema.String),
59 rate_limit: Schema.NullOr(
60 Schema.Struct({
61 primary_window: Schema.optional(Schema.NullOr(CodexWindow)),
62 secondary_window: Schema.optional(Schema.NullOr(CodexWindow)),
63 }),
64 ),
65});
66const OPTIONAL_HUB_CALL_TIMEOUT = "2 seconds";
67// The usage endpoint can report a window without a utilization, as the CLI's own schema allows.
68const ClaudeWindow = Schema.Struct({
69 utilization: Schema.NullOr(Schema.Number),
70 resets_at: Schema.NullOr(Schema.String),
71});
72const ClaudeUsage = Schema.Struct({
73 five_hour: Schema.optional(Schema.NullOr(ClaudeWindow)),
74 seven_day: Schema.optional(Schema.NullOr(ClaudeWindow)),
75 spend: Schema.optional(Schema.Unknown),
76 extra_usage: Schema.optional(
77 Schema.NullOr(
78 Schema.Struct({
79 is_enabled: Schema.Boolean,
80 monthly_limit: Schema.NullOr(Schema.Number),
81 used_credits: Schema.NullOr(Schema.Number),
82 utilization: Schema.NullOr(Schema.Number),
83 }),
84 ),
85 ),
86 limits: Schema.optional(
87 Schema.Array(
88 Schema.Struct({
89 kind: Schema.String,
90 percent: Schema.optional(Schema.NullOr(Schema.Number)),
91 resets_at: Schema.optional(Schema.NullOr(Schema.String)),
92 scope: Schema.optional(
93 Schema.NullOr(
94 Schema.Struct({
95 model: Schema.optional(Schema.NullOr(Schema.Struct({ display_name: Schema.String }))),
96 }),
97 ),
98 ),
99 }),
100 ),
101 ),
102});
103const CreditList = Schema.Struct({
104 credits: Schema.Array(
105 Schema.Struct({
106 id: Schema.String,
107 status: Schema.String,
108 reset_type: Schema.String,
109 expires_at: Schema.String,
110 }),
111 ),
112});
113
114const decodeAuthFiles = Schema.decodeUnknownEffect(AuthFiles);
115const decodeAuthFileModels = Schema.decodeUnknownEffect(AuthFileModels);
116const encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
117const decodeApiResponse = Schema.decodeUnknownEffect(ApiResponse);
118const decodeCreditList = Schema.decodeUnknownEffect(Schema.fromJsonString(CreditList));
119const decodeClaudeUsage = Schema.decodeUnknownEffect(Schema.fromJsonString(ClaudeUsage));
120const decodeCodexUsage = Schema.decodeUnknownEffect(Schema.fromJsonString(CodexUsage));
121const GROK_USAGE_URL = "https://cli-chat-proxy.grok.com/v1/billing?format=credits";
122const GrokUsageResponse = Schema.Struct({
123 config: Schema.optional(
124 Schema.Struct({
125 creditUsagePercent: Schema.optional(Schema.Number),
126 currentPeriod: Schema.optional(
127 Schema.Struct({
128 type: Schema.optional(Schema.String),
129 start: Schema.optional(Schema.Unknown),
130 end: Schema.optional(Schema.String),
131 }),
132 ),
133 }),
134 ),
135});
136
137function parsePeriodBoundary(value: string | undefined) {
138 if (
139 !value ||
140 value !== value.trim() ||
141 !/^(?:\d{4}|[+-]\d{6})-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?|24:00(?::00(?:\.0+)?)?)(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/.test(
142 value,
143 )
144 ) {
145 return Number.NaN;
146 }
147 // Date parsing can normalize impossible calendar dates instead of rejecting them.
148 const datePart = value.slice(0, value.indexOf("T"));
149 const date = DateTime.make(`${datePart}T00:00:00.000Z`);
150 if (Option.isNone(date)) return Number.NaN;
151 const parts = DateTime.toPartsUtc(date.value);
152 if (parts.month !== Number(datePart.slice(-5, -3)) || parts.day !== Number(datePart.slice(-2))) {
153 return Number.NaN;
154 }
155 return Date.parse(value);
156}
157
158function grokUsageResponseToLimits(response: typeof GrokUsageResponse.Type, checkedAt: string) {
159 const period = response.config?.currentPeriod;
160 const periodType = period?.type?.replace(/^USAGE_PERIOD_TYPE_/, "");
161 const kind = periodType === "WEEKLY" ? "weekly" : periodType === "MONTHLY" ? "monthly" : "other";
162 const start = typeof period?.start === "string" ? parsePeriodBoundary(period.start) : NaN;
163 const end = parsePeriodBoundary(period?.end);
164 const windowDurationMins = Math.round((end - start) / 60_000);
165 let usedPercent = response.config?.creditUsagePercent;
166 if (usedPercent === undefined && (kind === "weekly" || kind === "monthly") && start < end) {
167 // Grok omits a zero percentage while retaining the complete subscription period.
168 usedPercent = 0;
169 }
170 if (usedPercent === undefined || !Number.isFinite(usedPercent)) {
171 return makeUsageLimits({ checkedAt, windows: [] });
172 }
173 const reset = period?.end ? DateTime.make(period.end) : Option.none();
174 const window: ServerProviderUsageWindow = {
175 id: "subscription",
176 kind,
177 label: kind === "weekly" ? "Weekly" : kind === "monthly" ? "Monthly" : "Subscription",
178 usedPercent: clampPercent(usedPercent),
179 ...(Option.isSome(reset) ? { resetsAt: DateTime.formatIso(reset.value) } : {}),
180 ...(windowDurationMins > 0 ? { windowDurationMins } : {}),
181 };
182 return makeUsageLimits({ checkedAt, windows: [window] });
183}
184
185const decodeGrokUsage = Schema.decodeUnknownEffect(Schema.fromJsonString(GrokUsageResponse));
186const isUsageLimitSourceError = Schema.is(UsageLimitSourceError);
187
188// Extra CAs can fix untrusted chains; expiry/hostname failures report codes only.
189const UNTRUSTED_CERTIFICATE_CODES = new Set([
190 "DEPTH_ZERO_SELF_SIGNED_CERT",
191 "SELF_SIGNED_CERT_IN_CHAIN",
192 "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
193 "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
194]);
195
196// fetch wraps Node error codes in generic TypeErrors.
197const nodeErrorCode = (cause: unknown) => {
198 for (let error = cause, depth = 0; error instanceof Error && depth < 3; depth += 1) {
199 const code = (error as { readonly code?: unknown }).code;
200 if (typeof code === "string" && /^[A-Z0-9_]{1,64}$/.test(code)) return code;
201 error = error.cause;
202 }
203 return undefined;
204};
205
206// Hub responses can contain credentials; expose only failure kind, HTTP status or Node code.
207const describeManagementFailure = (error: unknown) => {
208 if (Cause.isTimeoutError(error)) return "The hub did not answer within 15 seconds.";
209 if (HttpClientError.isHttpClientError(error)) {
210 const reason = error.reason;
211 if (reason._tag === "StatusCodeError") {
212 return `The hub answered with HTTP ${reason.response.status}.`;
213 }
214 const code = reason._tag === "TransportError" ? nodeErrorCode(reason.cause) : undefined;
215 if (code !== undefined && UNTRUSTED_CERTIFICATE_CODES.has(code)) {
216 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.`;
217 }
218 if (code !== undefined) return `The hub request failed (${code}).`;
219 }
220 return "The hub management request failed.";
221};
222const decodeConsumeResponse = Schema.decodeUnknownEffect(
223 Schema.fromJsonString(
224 Schema.Struct({
225 code: Schema.Literals(["reset", "nothing_to_reset", "no_credit", "already_redeemed"]),
226 }),
227 ),
228);
229
230const CODEX_BASE = "https://chatgpt.com/backend-api/wham";
231const CREDIT_URL = `${CODEX_BASE}/rate-limit-reset-credits`;
232
233const CREDIT_REDEEM_NAMESPACE = new Uint8Array([
234 0x6f, 0x1c, 0x2a, 0x9e, 0x2d, 0x4b, 0x4c, 0x1e, 0x9a, 0x7f, 0x3b, 0x8d, 0x5e, 0x0c, 0x1a, 0x42,
235]);
236
237// UUIDv5 per account and credit also deduplicates retries across T3 environments.
238const creditRedeemRequestId = Effect.fn("CliproxyApi.creditRedeemRequestId")(function* (
239 accountId: string,
240 creditId: string,
241) {
242 const digest = yield* Digest.Digest;
243 const name = new TextEncoder().encode(`${accountId}:${creditId}`);
244 const input = new Uint8Array(CREDIT_REDEEM_NAMESPACE.length + name.length);
245 input.set(CREDIT_REDEEM_NAMESPACE);
246 input.set(name, CREDIT_REDEEM_NAMESPACE.length);
247 const bytes = (yield* digest.digest(Digest.sha1, input).pipe(Effect.orDie)).slice(0, 16);
248 bytes[6] = (bytes[6]! & 0x0f) | 0x50;
249 bytes[8] = (bytes[8]! & 0x3f) | 0x80;
250 const hex = Hex.encode(bytes);
251 return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
252});
253
254type AuthFile = typeof AuthFile.Type;
255/** Sends one upstream request with the account's token, as GET or as a JSON POST of `data`. */
256type HubCall = (
257 url: string,
258 data?: unknown,
259) => Effect.Effect<string, UsageLimitSourceError | Schema.SchemaError>;
260type HubReading = Omit<UsageLimitSourceAccount, "id" | "driver">;
261interface HubProvider {
262 readonly driver: ProviderDriverKind;
263 readonly header: (account: AuthFile) => Record<string, string>;
264 readonly read: (input: {
265 readonly account: AuthFile;
266 readonly call: HubCall;
267 readonly checkedAt: string;
268 }) => Effect.Effect<HubReading, UsageLimitSourceError | Schema.SchemaError>;
269}
270
271const listedIdentity = (account: AuthFile) => ({
272 ...(account.email ? { email: account.email } : {}),
273 ...(account.id_token?.chatgpt_account_id?.trim()
274 ? { workspaceId: account.id_token.chatgpt_account_id.trim() }
275 : {}),
276});
277
278const credits = Effect.fn("CliproxyApi.credits")(function* (call: HubCall) {
279 const response = yield* decodeCreditList(yield* call(CREDIT_URL));
280 const now = DateTime.toEpochMillis(yield* DateTime.now);
281 return response.credits
282 .filter(
283 (credit) =>
284 credit.reset_type === "codex_rate_limits" &&
285 credit.status === "available" &&
286 Date.parse(credit.expires_at) > now,
287 )
288 .toSorted((a, b) => Date.parse(a.expires_at) - Date.parse(b.expires_at));
289});
290
291const CODEX_HUB: HubProvider = {
292 driver: ProviderDriverKind.make("codex"),
293 header: (account) => ({
294 Authorization: "Bearer $TOKEN$",
295 "Content-Type": "application/json",
296 "OpenAI-Beta": "codex-1",
297 Originator: "Codex Desktop",
298 ...(account.id_token?.chatgpt_account_id
299 ? { "Chatgpt-Account-Id": account.id_token.chatgpt_account_id }
300 : {}),
301 }),
302 read: Effect.fnUntraced(function* ({ account, call, checkedAt }) {
303 const [usage, available] = yield* Effect.all(
304 [
305 call(`${CODEX_BASE}/usage`).pipe(Effect.flatMap(decodeCodexUsage)),
306 credits(call).pipe(
307 Effect.timeoutOption(OPTIONAL_HUB_CALL_TIMEOUT),
308 Effect.map(Option.getOrUndefined),
309 Effect.orElseSucceed(() => undefined),
310 ),
311 ],
312 { concurrency: 2 },
313 );
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 next = available?.[0];
325 const planType =
326 usage.plan_type ?? account.id_token?.plan_type ?? account.id_token?.chatgpt_plan_type;
327 return {
328 ...listedIdentity(account),
329 plan: codexPlanLabel(planType),
330 usageLimits: {
331 ...codexRateLimitsToLimits({
332 checkedAt,
333 snapshot: {
334 planType: planType ?? null,
335 primary: toWindow(usage.rate_limit?.primary_window),
336 secondary: toWindow(usage.rate_limit?.secondary_window),
337 },
338 }),
339 ...(available
340 ? {
341 resetCredits: {
342 availableCount: available.length,
343 ...(next
344 ? {
345 nextCreditId: next.id,
346 nextExpiresAt: DateTime.formatIso(DateTime.makeUnsafe(next.expires_at)),
347 }
348 : {}),
349 },
350 }
351 : {}),
352 },
353 };
354 }),
355};
356
357const GROK_CLI_VERSION = "1.0.77";
358
359// Keyed by the auth-files `provider`; accounts of any other provider are skipped.
360const HUB_PROVIDERS = new Map<string, HubProvider>([
361 ["codex", CODEX_HUB],
362 [
363 "claude",
364 {
365 driver: ProviderDriverKind.make("claudeAgent"),
366 header: () => ({
367 Authorization: "Bearer $TOKEN$",
368 "anthropic-beta": "oauth-2025-04-20",
369 // The OAuth usage endpoint can return 429 without a Claude Code user agent.
370 "User-Agent": "claude-code/2.1.273",
371 }),
372 read: Effect.fnUntraced(function* ({ account, call, checkedAt }) {
373 const usage = yield* decodeClaudeUsage(
374 yield* call("https://api.anthropic.com/api/oauth/usage"),
375 );
376 const model_scoped = (usage.limits ?? []).flatMap((limit) =>
377 limit.kind === "weekly_scoped" && limit.scope?.model && typeof limit.percent === "number"
378 ? [
379 {
380 display_name: limit.scope.model.display_name,
381 utilization: limit.percent,
382 resets_at: limit.resets_at ?? null,
383 },
384 ]
385 : [],
386 );
387 const rateLimits = {
388 five_hour: usage.five_hour ?? null,
389 seven_day: usage.seven_day ?? null,
390 model_scoped,
391 spend: usage.spend,
392 extra_usage: usage.extra_usage ?? null,
393 };
394 return {
395 ...listedIdentity(account),
396 plan: "Claude Subscription",
397 usageLimits: claudeUsageResponseToLimits({
398 checkedAt,
399 response: { rate_limits_available: true, rate_limits: rateLimits },
400 }).limits,
401 };
402 }),
403 },
404 ],
405 [
406 "xai",
407 {
408 driver: ProviderDriverKind.make("grok"),
409 header: () => ({
410 Authorization: "Bearer $TOKEN$",
411 "x-xai-token-auth": "xai-grok-cli",
412 "x-grok-client-version": GROK_CLI_VERSION,
413 "User-Agent": `grok-cli/${GROK_CLI_VERSION}`,
414 }),
415 read: Effect.fnUntraced(function* ({ account, call, checkedAt }) {
416 const usage = yield* decodeGrokUsage(yield* call(GROK_USAGE_URL));
417 return {
418 ...listedIdentity(account),
419 usageLimits: grokUsageResponseToLimits(usage, checkedAt),
420 };
421 }),
422 },
423 ],
424]);
425
426export const makeCliproxyApi = Effect.gen(function* () {
427 const client = yield* HttpClient.HttpClient;
428 const digest = yield* Digest.Digest;
429
430 const management = Effect.fn("CliproxyApi.management")(function* (
431 hub: CliproxyHub,
432 path: string,
433 body?: unknown,
434 ) {
435 const url = yield* Effect.try({
436 try: () => {
437 const base = new URL(hub.url);
438 // Users often paste the hub's web panel URL, which ends in management.html.
439 base.pathname = base.pathname.replace(/(\/management\.html)?\/?$/i, "/");
440 return new URL(`v0/management/${path}`, base).toString();
441 },
442 catch: () => new UsageLimitSourceError({ detail: "The hub URL is not valid." }),
443 });
444 const request = (
445 body === undefined ? HttpClientRequest.get(url) : HttpClientRequest.post(url)
446 ).pipe(HttpClientRequest.setHeader("Authorization", `Bearer ${hub.managementKey}`));
447 const response = yield* client
448 .execute(body === undefined ? request : request.pipe(HttpClientRequest.bodyJsonUnsafe(body)))
449 .pipe(
450 Effect.flatMap(HttpClientResponse.filterStatusOk),
451 Effect.flatMap((response) => response.json),
452 Effect.timeout("15 seconds"),
453 Effect.mapError(
454 (error) => new UsageLimitSourceError({ detail: describeManagementFailure(error) }),
455 ),
456 );
457 return response;
458 });
459
460 const authFiles = Effect.fn("CliproxyApi.authFiles")(function* (hub: CliproxyHub) {
461 const response = yield* management(hub, "auth-files");
462 return (yield* decodeAuthFiles(response)).files;
463 });
464
465 // Older hubs lack this endpoint; the account then counts for every model of its driver.
466 const routedModels = Effect.fn("CliproxyApi.routedModels")(function* (
467 hub: CliproxyHub,
468 account: AuthFile,
469 ) {
470 const response = yield* management(
471 hub,
472 `auth-files/models?name=${encodeURIComponent(account.id)}`,
473 );
474 return (yield* decodeAuthFileModels(response)).models.flatMap(({ id }) =>
475 id.trim() ? [id.trim()] : [],
476 );
477 });
478
479 const apiCall = Effect.fn("CliproxyApi.apiCall")(function* (
480 hub: CliproxyHub,
481 account: AuthFile,
482 header: Record<string, string>,
483 url: string,
484 data?: unknown,
485 ) {
486 const raw = yield* management(hub, "api-call", {
487 auth_index: account.auth_index,
488 method: data === undefined ? "GET" : "POST",
489 url,
490 header,
491 ...(data === undefined ? {} : { data: yield* encodeJson(data) }),
492 });
493 const response = yield* decodeApiResponse(raw);
494 if (response.status_code < 200 || response.status_code >= 300) {
495 return yield* new UsageLimitSourceError({
496 detail: `The provider refused the hub request (HTTP ${response.status_code}).`,
497 });
498 }
499 return response.body;
500 });
501
502 const readAccount = Effect.fn("CliproxyApi.readAccount")(function* (
503 hub: CliproxyHub,
504 account: AuthFile,
505 provider: HubProvider,
506 ) {
507 const checkedAt = DateTime.formatIso(yield* DateTime.now);
508 const call: HubCall = (url, data) => apiCall(hub, account, provider.header(account), url, data);
509 const reading = yield* provider.read({ account, call, checkedAt }).pipe(
510 Effect.catch((error) =>
511 Effect.succeed({
512 ...listedIdentity(account),
513 usageLimits: makeUnavailableUsageLimits({
514 checkedAt,
515 reason: "probeFailed",
516 // Source-error details are already credential-free (status codes only).
517 message: isUsageLimitSourceError(error)
518 ? error.detail
519 : "The hub could not read this account's usage.",
520 }),
521 }),
522 ),
523 );
524 return { id: account.id, driver: provider.driver, ...reading };
525 });
526
527 const readAccounts = Effect.fn("CliproxyApi.readAccounts")(function* (
528 hub: CliproxyHub,
529 ): Effect.fn.Return<
530 {
531 readonly accounts: ReadonlyArray<UsageLimitSourceAccount>;
532 readonly unreadProviders: ReadonlyArray<string>;
533 },
534 UsageLimitSourceError
535 > {
536 const accounts = yield* authFiles(hub).pipe(
537 Effect.mapError((error) =>
538 isUsageLimitSourceError(error)
539 ? error
540 : new UsageLimitSourceError({ detail: "The hub could not list accounts." }),
541 ),
542 );
543 const readable = accounts.flatMap((account) => {
544 const provider = HUB_PROVIDERS.get(account.provider);
545 return provider && !account.disabled ? [{ account, provider }] : [];
546 });
547 const unreadProviders = [
548 ...new Set(
549 accounts.flatMap((account) =>
550 account.disabled || HUB_PROVIDERS.has(account.provider) || !account.provider.trim()
551 ? []
552 : [account.provider.trim()],
553 ),
554 ),
555 ].toSorted();
556 // Model lists are optional, so their lookups run apart from the quota reads and stop at one
557 // short deadline; a slow lookup must not push a refresh past its budget.
558 const [readings, models] = yield* Effect.all(
559 [
560 Effect.forEach(readable, ({ account, provider }) => readAccount(hub, account, provider), {
561 concurrency: 16,
562 }),
563 Effect.forEach(
564 readable,
565 ({ account }) =>
566 routedModels(hub, account).pipe(
567 Effect.timeoutOption("2 seconds"),
568 Effect.orElseSucceed(() => Option.none()),
569 ),
570 { concurrency: "unbounded" },
571 ),
572 ],
573 { concurrency: 2 },
574 );
575 return {
576 accounts: readings.map((reading, index) => {
577 const listed = models[index];
578 return listed && Option.isSome(listed) ? { ...reading, models: listed.value } : reading;
579 }),
580 unreadProviders,
581 };
582 });
583
584 const consume = Effect.fn("CliproxyApi.consume")(function* (
585 hub: CliproxyHub,
586 accountId: string,
587 creditId: string,
588 ): Effect.fn.Return<ProviderConsumeResetCreditResult, UsageLimitSourceError> {
589 const operation = Effect.gen(function* () {
590 const account = (yield* authFiles(hub)).find((account) => account.id === accountId);
591 if (!account || account.disabled || account.provider !== "codex") {
592 return yield* new UsageLimitSourceError({
593 detail: "The Codex hub account is missing or disabled.",
594 });
595 }
596 const body = yield* apiCall(
597 hub,
598 account,
599 CODEX_HUB.header(account),
600 `${CREDIT_URL}/consume`,
601 {
602 redeem_request_id: yield* creditRedeemRequestId(
603 account.id_token?.chatgpt_account_id ?? account.id,
604 creditId,
605 ).pipe(Effect.provideService(Digest.Digest, digest)),
606 credit_id: creditId,
607 },
608 );
609 const response = yield* decodeConsumeResponse(body);
610 const outcome = (
611 {
612 reset: "reset",
613 nothing_to_reset: "nothingToReset",
614 no_credit: "noCredit",
615 already_redeemed: "alreadyRedeemed",
616 } as const
617 )[response.code];
618 if (outcome !== "reset" && outcome !== "alreadyRedeemed") return { outcome };
619 const cleared = yield* management(hub, "reset-quota", {
620 auth_index: account.auth_index,
621 }).pipe(Effect.result);
622 return {
623 outcome,
624 ...(cleared._tag === "Failure"
625 ? {
626 warning:
627 "Credit redeemed, but the hub cooldown could not be cleared. Routing may resume after its cooldown expires.",
628 }
629 : {}),
630 } as const;
631 });
632 return yield* operation.pipe(
633 Effect.mapError((error) =>
634 isUsageLimitSourceError(error)
635 ? error
636 : new UsageLimitSourceError({
637 detail: "The hub returned an unexpected reset-credit response.",
638 }),
639 ),
640 );
641 });
642 return { readAccounts, consume };
643});