Open History to see the last commit
1/**
2 * Maps a CLIProxyAPI hub's `quota-scheduler/status` response onto the usage
3 * limit windows the Limits view renders, one account per pooled auth file.
4 *
5 * The hub already normalises each upstream: Claude accounts carry
6 * `five_hour` / `seven_day` / `fable`, Codex accounts `five_hour` / `weekly`.
7 * Every window is `{ used_percent, reset_at?, known, hard_limited }`.
8 *
9 * @module usage/cliproxyUsageLimits
10 */
11import {
12 ProviderDriverKind,
13 type ServerProviderUsageLimits,
14 type ServerProviderUsageWindow,
15 type UsageLimitSourceAccount,
16} from "@t3tools/contracts";
17import * as DateTime from "effect/DateTime";
18import * as Option from "effect/Option";
19import * as Schema from "effect/Schema";
20
21import { codexPlanLabel } from "../provider/Layers/CodexProvider.ts";
22import { clampPercent, makeUsageLimits } from "../provider/providerUsageLimits.ts";
23
24const QuotaWindow = Schema.Struct({
25 used_percent: Schema.Number,
26 reset_at: Schema.optional(Schema.String),
27 known: Schema.optional(Schema.Boolean),
28 hard_limited: Schema.optional(Schema.Boolean),
29});
30
31const QuotaAccount = Schema.Struct({
32 provider: Schema.String,
33 plan: Schema.optional(Schema.String),
34 fetched_at: Schema.optional(Schema.String),
35 five_hour: Schema.optional(QuotaWindow),
36 seven_day: Schema.optional(QuotaWindow),
37 weekly: Schema.optional(QuotaWindow),
38 fable: Schema.optional(QuotaWindow),
39});
40
41export const CliproxyQuotaStatus = Schema.Struct({
42 accounts: Schema.Record(Schema.String, QuotaAccount),
43});
44export type CliproxyQuotaStatus = typeof CliproxyQuotaStatus.Type;
45export const decodeCliproxyQuotaStatus = Schema.decodeUnknownEffect(CliproxyQuotaStatus);
46
47const SESSION_MINS = 5 * 60;
48const WEEK_MINS = 7 * 24 * 60;
49
50/** Window ids match what the provider drivers emit, so rows read the same across sources. */
51const WINDOWS: ReadonlyArray<{
52 readonly key: keyof Omit<typeof QuotaAccount.Type, "provider" | "plan" | "fetched_at">;
53 readonly id: string;
54 readonly kind: ServerProviderUsageWindow["kind"];
55 readonly label: string;
56 readonly windowDurationMins: number;
57}> = [
58 {
59 key: "five_hour",
60 id: "five_hour",
61 kind: "session",
62 label: "Session",
63 windowDurationMins: SESSION_MINS,
64 },
65 {
66 key: "seven_day",
67 id: "seven_day",
68 kind: "weekly",
69 label: "Weekly",
70 windowDurationMins: WEEK_MINS,
71 },
72 {
73 key: "weekly",
74 id: "secondary",
75 kind: "weekly",
76 label: "Weekly",
77 windowDurationMins: WEEK_MINS,
78 },
79 {
80 key: "fable",
81 id: "seven_day_fable",
82 kind: "weekly",
83 label: "Weekly · Fable",
84 windowDurationMins: WEEK_MINS,
85 },
86];
87
88const DRIVER_BY_HUB_PROVIDER: Readonly<Record<string, ProviderDriverKind>> = {
89 claude: ProviderDriverKind.make("claudeAgent"),
90 codex: ProviderDriverKind.make("codex"),
91};
92
93function isoFromHub(value: string | undefined): string | undefined {
94 if (!value) return undefined;
95 const dt = DateTime.make(value);
96 return Option.isSome(dt) ? DateTime.formatIso(dt.value) : undefined;
97}
98
99/** `claude-julius@ping.gg.json` → `julius@ping.gg`; `codex-<hash>-x@y-pro.json` → `x@y`. */
100export function accountEmailFromAuthFile(fileName: string): string | undefined {
101 const stem = fileName.replace(/\.json$/i, "");
102 // Strip the provider prefix (and Codex's hash) rather than splitting on
103 // `-`, so a hyphenated local part such as `first-last@` survives.
104 return stem.match(/^(?:claude-|codex-[a-z0-9]+-)?([^\s/]+@[^\s/]+?)(?:-[a-z0-9]+)?$/i)?.[1];
105}
106
107/**
108 * The hub only reports a plan slug for Codex. Claude accounts carry no tier
109 * in the scheduler status, so the row says what it is: a Claude subscription.
110 */
111function planLabel(account: typeof QuotaAccount.Type): string | undefined {
112 if (account.provider === "codex") return codexPlanLabel(account.plan);
113 if (account.provider === "claude") return "Claude Subscription";
114 return undefined;
115}
116
117export function cliproxyAccountToUsageLimits(
118 account: typeof QuotaAccount.Type,
119 checkedAt: string,
120): ServerProviderUsageLimits {
121 const windows: ServerProviderUsageWindow[] = [];
122 for (const spec of WINDOWS) {
123 const window = account[spec.key];
124 if (!window || window.known === false) continue;
125 const resetsAt = isoFromHub(window.reset_at);
126 windows.push({
127 id: spec.id,
128 kind: spec.kind,
129 label: spec.label,
130 windowDurationMins: spec.windowDurationMins,
131 // The hub flags a window it has seen a 429 on; the percent may lag.
132 usedPercent: window.hard_limited ? 100 : clampPercent(window.used_percent),
133 ...(resetsAt ? { resetsAt } : {}),
134 });
135 }
136 return makeUsageLimits({ checkedAt: isoFromHub(account.fetched_at) ?? checkedAt, windows });
137}
138
139export function cliproxyStatusToAccounts(
140 status: CliproxyQuotaStatus,
141 checkedAt: string,
142): ReadonlyArray<UsageLimitSourceAccount> {
143 const accounts: UsageLimitSourceAccount[] = [];
144 for (const [fileName, account] of Object.entries(status.accounts)) {
145 const driver = DRIVER_BY_HUB_PROVIDER[account.provider];
146 if (!driver) continue;
147 const email = accountEmailFromAuthFile(fileName);
148 const plan = planLabel(account);
149 accounts.push({
150 id: fileName,
151 driver,
152 ...(email ? { email } : {}),
153 ...(plan ? { plan } : {}),
154 usageLimits: cliproxyAccountToUsageLimits(account, checkedAt),
155 });
156 }
157 return accounts.toSorted(
158 (left, right) => left.driver.localeCompare(right.driver) || left.id.localeCompare(right.id),
159 );
160}