Open History to see the last commit
1/**
2 * Selection and pace maths for the provider limits view, shared by web and
3 * mobile so both agree on which providers show, what "ahead of pace" means,
4 * and how a reset is phrased.
5 *
6 * @module usageLimits
7 */
8import {
9 type EnvironmentId,
10 type UsageLimitsReport,
11 type ProviderInstanceId,
12 type ProviderConsumeResetCreditInput,
13 type ServerProviderSlashCommand,
14 isProviderAvailable,
15 type ServerProvider,
16 type ServerProviderUsageLimits,
17 type ServerProviderUsageWindow,
18 type UsageLimitSourceSnapshot,
19 type UsageLimitSourceSnapshots,
20} from "@t3tools/contracts";
21
22import * as DateTime from "effect/DateTime";
23
24const MINUTE = 60_000;
25const HOUR = 60 * MINUTE;
26const DAY = 24 * HOUR;
27
28/**
29 * Providers that belong on the Limits view: enabled, installed, and one whose
30 * driver reports subscription usage at all. A driver with no notion of usage
31 * never sets `usageLimits`, so it has no row rather than an empty one.
32 */
33export function providersWithLimits(
34 providers: readonly ServerProvider[],
35): readonly ServerProvider[] {
36 return providers.filter(
37 (provider) =>
38 provider.enabled &&
39 provider.installed &&
40 isProviderAvailable(provider) &&
41 provider.usageLimits !== undefined,
42 );
43}
44
45export interface LimitsGroup {
46 readonly environmentId: EnvironmentId;
47 /** Null while only one environment is connected; there is nothing to tell apart. */
48 readonly environmentLabel: string | null;
49 readonly providers: readonly ServerProvider[];
50}
51
52/**
53 * One group per connected environment with a provider reporting limits.
54 * Provider snapshots come from the config stream every client already holds,
55 * so opening the view costs no extra request.
56 */
57export function collectLimitsGroups(
58 presentations: ReadonlyMap<
59 EnvironmentId,
60 {
61 readonly entry: { readonly target: { readonly label: string } };
62 readonly serverConfig: {
63 readonly providers?: readonly ServerProvider[] | undefined;
64 } | null;
65 }
66 >,
67): readonly LimitsGroup[] {
68 const groups: LimitsGroup[] = [];
69 for (const [environmentId, presentation] of presentations) {
70 const providers = providersWithLimits(presentation.serverConfig?.providers ?? []);
71 if (providers.length === 0) continue;
72 groups.push({ environmentId, environmentLabel: presentation.entry.target.label, providers });
73 }
74 return groups.length > 1 ? groups : groups.map((group) => ({ ...group, environmentLabel: null }));
75}
76
77/**
78 * Every usage-limit source across connected environments, keyed so two
79 * environments pointing at the same hub still get their own rows. The label
80 * carries the environment only when more than one environment has sources.
81 * A native provider with usable limits takes precedence over the same account
82 * in a source, even when it belongs to another connected environment.
83 */
84export function collectLimitSources(
85 presentations: ReadonlyMap<
86 EnvironmentId,
87 {
88 readonly entry: { readonly target: { readonly label: string } };
89 readonly serverConfig: {
90 readonly providers?: readonly ServerProvider[] | undefined;
91 readonly usageLimitSources?: UsageLimitSourceSnapshots | undefined;
92 } | null;
93 }
94 >,
95): ReadonlyArray<
96 UsageLimitSourceSnapshot & {
97 readonly key: string;
98 readonly environmentId: EnvironmentId;
99 readonly hiddenAccountCount: number;
100 }
101> {
102 const nativeAccounts = new Set<string>();
103 for (const presentation of presentations.values()) {
104 for (const provider of providersWithLimits(presentation.serverConfig?.providers ?? [])) {
105 const key = accountKey(provider.driver, provider.auth.email);
106 if (
107 key !== null &&
108 provider.usageLimits?.windows.length &&
109 !provider.usageLimits.unavailable
110 ) {
111 nativeAccounts.add(key);
112 }
113 }
114 }
115 const perEnvironment: Array<{
116 readonly environmentId: EnvironmentId;
117 readonly environmentLabel: string;
118 readonly sources: UsageLimitSourceSnapshots;
119 }> = [];
120 for (const [environmentId, presentation] of presentations) {
121 const sources = presentation.serverConfig?.usageLimitSources ?? [];
122 if (sources.length === 0) continue;
123 perEnvironment.push({
124 environmentId,
125 environmentLabel: presentation.entry.target.label,
126 sources,
127 });
128 }
129 const labelEnvironment = perEnvironment.length > 1;
130 return perEnvironment.flatMap(({ environmentId, environmentLabel, sources }) =>
131 sources.map((source) => {
132 const accounts = source.accounts.filter((account) => {
133 const key = accountKey(account.driver, account.email);
134 return key === null || !nativeAccounts.has(key);
135 });
136 return {
137 ...source,
138 accounts,
139 hiddenAccountCount: source.accounts.length - accounts.length,
140 environmentId,
141 key: `${environmentId}:${source.id}`,
142 label: labelEnvironment ? `${environmentLabel} · ${source.label}` : source.label,
143 };
144 }),
145 );
146}
147
148function accountKey(driver: ServerProvider["driver"], email: string | undefined): string | null {
149 const normalizedEmail = email?.trim().toLowerCase();
150 return normalizedEmail ? `${driver}:${normalizedEmail}` : null;
151}
152
153/**
154 * One subscription account as the pooled views see it, whichever way it was
155 * reported. The same email signed in natively on two environments, or reported
156 * by a hub as well as natively, is one account: its quota is one bucket, so
157 * counting it twice would misstate what is left.
158 */
159export interface LimitAccount {
160 readonly key: string;
161 readonly driver: ServerProvider["driver"];
162 /** The instance's configured name, which is not sensitive; null for hub accounts. */
163 readonly displayName: string | null;
164 readonly email: string | undefined;
165 readonly plan: string | undefined;
166 readonly accentColor: string | undefined;
167 /** Environments the account is signed in on; empty when only a hub reports it. */
168 readonly environments: ReadonlyArray<{
169 readonly environmentId: EnvironmentId;
170 readonly label: string;
171 }>;
172 /** The hub that reported it, when no environment has it natively. */
173 readonly sourceLabel: string | null;
174 /** Where the displayed reset credit can be redeemed. */
175 readonly redeem: {
176 readonly environmentId: EnvironmentId;
177 readonly input: ProviderConsumeResetCreditInput;
178 } | null;
179 readonly limits: ServerProviderUsageLimits;
180}
181
182/**
183 * Every account with usable windows across the connected environments, one
184 * entry per distinct account. The freshest reads supply windows and credits;
185 * native instances supply names and environment labels.
186 */
187export function collectLimitAccounts(
188 presentations: Parameters<typeof collectLimitSources>[0],
189): readonly LimitAccount[] {
190 const accounts = new Map<string, LimitAccount>();
191 const creditSources = new Map<string, LimitAccount>();
192 const hubRedeems = new Map<string, LimitAccount>();
193 const merge = (key: string, next: LimitAccount) => {
194 // Redeeming through a hub also clears the routing cooldown that hub holds
195 // for the account. Redeeming natively against the same subscription resets
196 // it upstream but leaves the hub refusing to route to the account until
197 // its own cooldown expires, so a hub target wins the redemption outright
198 // while the displayed balance still follows the freshest read.
199 const previousHub = hubRedeems.get(key);
200 if (
201 next.redeem &&
202 "sourceId" in next.redeem.input &&
203 (!previousHub || Date.parse(next.limits.checkedAt) > Date.parse(previousHub.limits.checkedAt))
204 ) {
205 hubRedeems.set(key, next);
206 }
207 const previousCredit = creditSources.get(key);
208 if (
209 next.limits.resetCredits &&
210 (!previousCredit ||
211 Date.parse(next.limits.checkedAt) > Date.parse(previousCredit.limits.checkedAt))
212 ) {
213 creditSources.set(key, next);
214 }
215 const previous = accounts.get(key);
216 if (!previous) {
217 accounts.set(key, next);
218 return;
219 }
220 const fresher = Date.parse(next.limits.checkedAt) > Date.parse(previous.limits.checkedAt);
221 // Two instances on one machine sharing an account still name it once.
222 const environments = [
223 ...previous.environments,
224 ...next.environments.filter(
225 (candidate) =>
226 !previous.environments.some((seen) => seen.environmentId === candidate.environmentId),
227 ),
228 ];
229 const winner = fresher ? next : previous;
230 // Credits and their redemption target travel together. A failed credit
231 // probe must not erase a successful read from another environment.
232 const creditSource = creditSources.get(key);
233 accounts.set(key, {
234 ...previous,
235 displayName: previous.displayName ?? next.displayName,
236 plan: previous.plan ?? next.plan,
237 accentColor: previous.accentColor ?? next.accentColor,
238 environments,
239 // A hub only names the account when no environment has it natively.
240 sourceLabel: environments.length > 0 ? null : (previous.sourceLabel ?? next.sourceLabel),
241 redeem:
242 hubRedeems.get(key)?.redeem ??
243 (creditSource ? creditSource.redeem : (winner.redeem ?? previous.redeem ?? next.redeem)),
244 limits: {
245 ...winner.limits,
246 ...(creditSource?.limits.resetCredits
247 ? { resetCredits: creditSource.limits.resetCredits }
248 : { resetCredits: undefined }),
249 },
250 });
251 };
252 for (const [environmentId, presentation] of presentations) {
253 const label = presentation.entry.target.label;
254 for (const provider of providersWithLimits(presentation.serverConfig?.providers ?? [])) {
255 if (!provider.usageLimits || limitsNotice(provider.usageLimits) !== null) continue;
256 merge(
257 accountKey(provider.driver, provider.auth.email) ??
258 `${environmentId}:${provider.instanceId}`,
259 {
260 key: `${environmentId}:${provider.instanceId}`,
261 driver: provider.driver,
262 displayName: provider.displayName?.trim() || null,
263 email: provider.auth.email,
264 plan: provider.auth.label,
265 accentColor: provider.accentColor,
266 environments: [{ environmentId, label }],
267 sourceLabel: null,
268 redeem: { environmentId, input: { instanceId: provider.instanceId } },
269 limits: provider.usageLimits,
270 },
271 );
272 }
273 }
274 // Every hub account, including those a native instance also knows: the hub
275 // may hold a fresher read of the same subscription, and the merge above
276 // keeps the redeem target consistent with whichever snapshot wins.
277 const labelEnvironment = presentations.size > 1;
278 for (const [environmentId, presentation] of presentations) {
279 for (const source of presentation.serverConfig?.usageLimitSources ?? []) {
280 const sourceLabel = labelEnvironment
281 ? `${presentation.entry.target.label} · ${source.label}`
282 : source.label;
283 for (const account of source.accounts) {
284 if (limitsNotice(account.usageLimits) !== null) continue;
285 merge(accountKey(account.driver, account.email) ?? `${source.id}:${account.id}`, {
286 key: `${source.id}:${account.id}`,
287 driver: account.driver,
288 displayName: account.email ? null : account.id.replace(/\.json$/i, ""),
289 email: account.email,
290 plan: account.plan,
291 accentColor: undefined,
292 environments: [],
293 sourceLabel,
294 redeem: account.usageLimits.resetCredits?.nextCreditId
295 ? {
296 environmentId,
297 input: {
298 sourceId: source.id,
299 accountId: account.id,
300 creditId: account.usageLimits.resetCredits.nextCreditId,
301 },
302 }
303 : null,
304 limits: account.usageLimits,
305 });
306 }
307 }
308 }
309 return [...accounts.values()];
310}
311
312/**
313 * What the pooled views cannot draw as a bar: a hub that failed to read, a
314 * provider whose probe failed. Accounts that can never report (API keys)
315 * are left out; there is nothing for the user to act on. The environment
316 * is named only when more than one is connected.
317 */
318export function collectLimitNotices(
319 presentations: Parameters<typeof collectLimitSources>[0],
320): readonly string[] {
321 const label = (environmentLabel: string, subject: string) =>
322 presentations.size > 1 ? `${environmentLabel} · ${subject}` : subject;
323 const notices: string[] = [];
324 for (const presentation of presentations.values()) {
325 const environmentLabel = presentation.entry.target.label;
326 for (const provider of providersWithLimits(presentation.serverConfig?.providers ?? [])) {
327 // An account that can never report (API key) is left out; one that
328 // failed, or reported nothing at all, is worth a line.
329 if (provider.usageLimits?.unavailable?.reason === "unsupported") continue;
330 const notice = provider.usageLimits ? limitsNotice(provider.usageLimits) : null;
331 const name = provider.displayName?.trim() || String(provider.driver);
332 if (notice) notices.push(`${label(environmentLabel, name)}: ${notice}`);
333 }
334 for (const source of presentation.serverConfig?.usageLimitSources ?? []) {
335 if (source.error) {
336 notices.push(`${label(environmentLabel, source.label)}: ${source.error}`);
337 } else if (source.accounts.length === 0) {
338 notices.push(`${label(environmentLabel, source.label)}: No accounts reported.`);
339 }
340 }
341 }
342 return notices;
343}
344
345export interface LimitPoolMember {
346 readonly account: LimitAccount;
347 readonly window: ServerProviderUsageWindow;
348}
349
350/**
351 * One window id across every account that reports it: the pooled share left,
352 * pace against the clock, and the resets in the order they will land, each
353 * with the share of the pool it hands back.
354 */
355export interface LimitPoolWindow {
356 readonly id: string;
357 readonly kind: ServerProviderUsageWindow["kind"];
358 readonly label: string;
359 readonly members: readonly LimitPoolMember[];
360 /** Fixed account positions across rows; a null window leaves a gap. */
361 readonly columns: ReadonlyArray<{
362 readonly account: LimitAccount;
363 readonly window: ServerProviderUsageWindow | null;
364 }>;
365 readonly remainingPercent: number;
366 readonly usedPercent: number;
367 readonly pace: LimitPace | null;
368 readonly resets: ReadonlyArray<{
369 readonly member: LimitPoolMember;
370 readonly at: number;
371 /** Points of the pool the reset restores: the member's used share over the member count. */
372 readonly restoresPercent: number;
373 }>;
374}
375
376export interface LimitPool {
377 readonly driver: ServerProvider["driver"];
378 readonly accounts: readonly LimitAccount[];
379 readonly windows: readonly LimitPoolWindow[];
380}
381
382const WINDOW_KIND_ORDER: Record<ServerProviderUsageWindow["kind"], number> = {
383 session: 0,
384 weekly: 1,
385 monthly: 2,
386 other: 3,
387};
388
389/**
390 * Accounts grouped by driver, each with its windows pooled by kind and id.
391 * Window ids are stable per provider, so a hub row and a native row for the
392 * same window land in the same pool; the kind is part of the key because
393 * Codex's `primary` is a position, not a duration (five hours on paid plans,
394 * a month on Free/Go), and a monthly allowance must not average into a
395 * five-hour pool. Pools order by kind, then first appearance.
396 *
397 * Accounts and columns share the session reset order, soonest first. When
398 * no account reports a session window, use the first window by kind instead.
399 * Missing reset times sort last, with account names and keys breaking ties.
400 * Each window's reset list still follows its own clock.
401 */
402export function collectLimitPools(
403 accounts: readonly LimitAccount[],
404 now: number,
405): readonly LimitPool[] {
406 const byDriver = new Map<ServerProvider["driver"], LimitAccount[]>();
407 for (const account of accounts) {
408 const list = byDriver.get(account.driver);
409 if (list) list.push(account);
410 else byDriver.set(account.driver, [account]);
411 }
412 return [...byDriver].map(([driver, members]) => {
413 const orderWindow = members
414 .flatMap((account) => account.limits.windows)
415 .sort((left, right) => WINDOW_KIND_ORDER[left.kind] - WINDOW_KIND_ORDER[right.kind])[0];
416 const orderReset = (account: LimitAccount) => {
417 const window = account.limits.windows.find(
418 (window) => window.kind === orderWindow?.kind && window.id === orderWindow.id,
419 );
420 return (window ? resetMillis(window) : null) ?? Number.POSITIVE_INFINITY;
421 };
422 const sorted = [...members].sort(
423 (left, right) =>
424 orderReset(left) - orderReset(right) ||
425 accountSortName(left).localeCompare(accountSortName(right)) ||
426 left.key.localeCompare(right.key),
427 );
428 return { driver, accounts: sorted, windows: poolWindows(sorted, now) };
429 });
430}
431
432function accountSortName(account: LimitAccount): string {
433 return (account.displayName ?? account.email ?? account.key).toLowerCase();
434}
435
436function poolWindows(accounts: readonly LimitAccount[], now: number): readonly LimitPoolWindow[] {
437 const byKey = new Map<string, LimitPoolMember[]>();
438 for (const account of accounts) {
439 for (const window of account.limits.windows) {
440 const key = `${window.kind}:${window.id}`;
441 const list = byKey.get(key);
442 if (list) list.push({ account, window });
443 else byKey.set(key, [{ account, window }]);
444 }
445 }
446 const pools = [...byKey.values()].map((members): LimitPoolWindow => {
447 const memberByAccount = new Map(members.map((member) => [member.account.key, member]));
448 const first = members[0]!.window;
449 const usedPercent = members.reduce((sum, m) => sum + m.window.usedPercent, 0) / members.length;
450 // Pace compares spend against the clock, so it is judged only over the
451 // members that have a clock; a window with no reset would otherwise
452 // count as spend with no time elapsed and skew the verdict.
453 const timed = members.flatMap((m) => {
454 const share = elapsedShare(m.window, now);
455 return share === null ? [] : [{ used: m.window.usedPercent, elapsed: share }];
456 });
457 const timedUsed = timed.reduce((sum, t) => sum + t.used, 0) / timed.length;
458 const meanElapsed =
459 timed.length > 0 ? timed.reduce((sum, t) => sum + t.elapsed, 0) / timed.length : null;
460 const resets = members
461 .flatMap((member) => {
462 const at = resetMillis(member.window);
463 return at === null
464 ? []
465 : [
466 {
467 member,
468 at,
469 restoresPercent: Math.round(member.window.usedPercent / members.length),
470 },
471 ];
472 })
473 .sort((left, right) => left.at - right.at);
474 return {
475 id: first.id,
476 kind: first.kind,
477 label: first.label,
478 members,
479 columns: accounts.map(
480 (account) => memberByAccount.get(account.key) ?? { account, window: null },
481 ),
482 usedPercent: Math.round(usedPercent),
483 remainingPercent: Math.round(100 - usedPercent),
484 pace: meanElapsed === null ? null : paceOfShares(timedUsed, meanElapsed),
485 resets,
486 };
487 });
488 return pools.sort((left, right) => WINDOW_KIND_ORDER[left.kind] - WINDOW_KIND_ORDER[right.kind]);
489}
490
491/** The one-line status under a provider heading when there are no bars to draw. */
492export function limitsNotice(limits: ServerProviderUsageLimits): string | null {
493 if (limits.unavailable?.reason === "unsupported") {
494 return limits.unavailable.message ?? "This account has no subscription limits.";
495 }
496 if (limits.unavailable?.reason === "probeFailed") {
497 return limits.unavailable.message ?? "Could not read limits.";
498 }
499 return limits.windows.length === 0 ? "No limits reported." : null;
500}
501
502/** Quota left in the window, 0..100. Bars and labels show what remains, as Codex does. */
503export function remainingPercent(window: ServerProviderUsageWindow): number {
504 return Math.round(100 - Math.max(0, Math.min(100, window.usedPercent)));
505}
506
507function resetMillis(window: ServerProviderUsageWindow): number | null {
508 if (window.resetsAt === undefined) return null;
509 const at = Date.parse(window.resetsAt);
510 return Number.isFinite(at) ? at : null;
511}
512
513/** Elapsed share of the window, 0..1, or null when its length or reset is unknown. */
514export function elapsedShare(window: ServerProviderUsageWindow, now: number): number | null {
515 const resetsAt = resetMillis(window);
516 if (resetsAt === null || window.windowDurationMins === undefined) return null;
517 const length = window.windowDurationMins * MINUTE;
518 if (length <= 0) return null;
519 return Math.max(0, Math.min(1, (length - (resetsAt - now)) / length));
520}
521
522export type LimitPace = "ahead" | "on" | "under";
523
524/**
525 * Usage against the clock. Spending evenly leaves the same share of quota as
526 * there is time left in the window; within five points of that counts as on
527 * pace, further ahead means the window may run dry first.
528 */
529export function paceOf(window: ServerProviderUsageWindow, now: number): LimitPace | null {
530 const elapsed = elapsedShare(window, now);
531 return elapsed === null ? null : paceOfShares(window.usedPercent, elapsed);
532}
533
534function paceOfShares(usedPercent: number, elapsed: number): LimitPace {
535 const gap = usedPercent - elapsed * 100;
536 if (gap > 5) return "ahead";
537 if (gap < -5) return "under";
538 return "on";
539}
540
541/** `2h 13m`, `3d 4h`, `12m`. */
542export function formatDuration(ms: number): string {
543 const remaining = Math.max(0, ms);
544 const days = Math.floor(remaining / DAY);
545 const hours = Math.floor((remaining % DAY) / HOUR);
546 const minutes = Math.floor((remaining % HOUR) / MINUTE);
547 if (days > 0) return `${days}d ${hours}h`;
548 if (hours > 0) return `${hours}h ${minutes}m`;
549 return `${minutes}m`;
550}
551
552/** `resets in 2h 13m`, or null when the window has no reset. */
553export function formatResetsIn(window: ServerProviderUsageWindow, now: number): string | null {
554 const resetsAt = resetMillis(window);
555 if (resetsAt === null) return null;
556 return resetsAt <= now ? "resets now" : `resets in ${formatDuration(resetsAt - now)}`;
557}
558
559/** Limit commands are served by T3 from the same snapshots as Usage → Limits. */
560export const USAGE_LIMITS_COMMAND = {
561 name: "usage-limits",
562 description: "Show this provider's usage limits",
563} satisfies ServerProviderSlashCommand;
564
565/** Handled by the client without sending a turn; anything with arguments stays an ordinary prompt. */
566export function isUsageLimitsCommand(prompt: string): boolean {
567 return prompt.trim().toLowerCase() === "/usage-limits";
568}
569
570/**
571 * Whether Limits has anything to say about this driver. A source that failed to
572 * read keeps no accounts, so its error counts for every driver rather than
573 * disappearing until the next successful refresh.
574 */
575export function hasProviderUsageLimits(
576 driver: ServerProvider["driver"],
577 providers: readonly ServerProvider[],
578 sources: UsageLimitSourceSnapshots,
579): boolean {
580 return (
581 providersWithLimits(providers).some((provider) => provider.driver === driver) ||
582 sources.some(
583 (source) =>
584 source.accounts.some((account) => account.driver === driver) ||
585 (source.error !== undefined && source.accounts.length === 0),
586 )
587 );
588}
589
590/**
591 * The drivers a set of sources would offer the command to, where a source that
592 * failed to read counts for every driver. Two snapshots with the same coverage
593 * need no catalog republish, however much their quotas moved.
594 */
595export function sameUsageLimitCommandCoverage(
596 previous: UsageLimitSourceSnapshots,
597 next: UsageLimitSourceSnapshots,
598): boolean {
599 const coverage = (sources: UsageLimitSourceSnapshots) =>
600 new Set(
601 sources.flatMap((source) =>
602 source.error !== undefined && source.accounts.length === 0
603 ? ["*"]
604 : source.accounts.map((account) => String(account.driver)),
605 ),
606 );
607 const before = coverage(previous);
608 const after = coverage(next);
609 return before.size === after.size && [...before].every((driver) => after.has(driver));
610}
611
612/** Advertise on workspace catalogs too, which replace the global command list. */
613export function withUsageLimitsCommands(
614 providers: readonly ServerProvider[],
615 sources: UsageLimitSourceSnapshots,
616): ServerProvider[] {
617 return providers.map((provider) => {
618 if (!hasProviderUsageLimits(provider.driver, providers, sources)) return provider;
619 const commands = (items: readonly ServerProviderSlashCommand[]) => [
620 ...items.filter((command) => command.name !== USAGE_LIMITS_COMMAND.name),
621 USAGE_LIMITS_COMMAND,
622 ];
623 return {
624 ...provider,
625 slashCommands: commands(provider.slashCommands),
626 ...(provider.workspaceSnapshots
627 ? {
628 workspaceSnapshots: provider.workspaceSnapshots.map((snapshot) => ({
629 ...snapshot,
630 slashCommands: commands(snapshot.slashCommands),
631 })),
632 }
633 : {}),
634 };
635 });
636}
637
638/** A point-in-time report; never refreshes or guesses which pooled account serves a turn. */
639export function collectProviderUsageLimits(
640 instanceId: ProviderInstanceId,
641 providers: readonly ServerProvider[],
642 sources: UsageLimitSourceSnapshots,
643 now: number,
644): UsageLimitsReport | null {
645 const selected = providers.find((provider) => provider.instanceId === instanceId);
646 if (!selected || !hasProviderUsageLimits(selected.driver, providers, sources)) return null;
647 const native = providersWithLimits(providers).filter(
648 (provider) => provider.driver === selected.driver,
649 );
650 const nativeAccounts = new Set(
651 native.flatMap((provider) => {
652 const key = accountKey(provider.driver, provider.auth.email);
653 return key && provider.usageLimits?.windows.length && !provider.usageLimits.unavailable
654 ? [key]
655 : [];
656 }),
657 );
658 const accounts: Array<UsageLimitsReport["accounts"][number]> = [];
659 const notices: string[] = [];
660 for (const provider of native) {
661 if (!provider.usageLimits) continue;
662 const key = accountKey(provider.driver, provider.auth.email);
663 const hubCredits = sources
664 .flatMap((source) => source.accounts.map((account) => ({ source, account })))
665 .filter(
666 ({ account }) =>
667 key !== null &&
668 accountKey(account.driver, account.email) === key &&
669 account.usageLimits.resetCredits &&
670 !limitsNotice(account.usageLimits),
671 )
672 .sort(
673 (a, b) =>
674 Date.parse(b.account.usageLimits.checkedAt) - Date.parse(a.account.usageLimits.checkedAt),
675 )[0];
676 // Two independent decisions. Which balance to *display* follows whichever
677 // snapshot is fresher. Which path to *redeem through* always prefers the
678 // hub, because only the hub path clears the routing cooldown it holds for
679 // that account; redeeming natively against the same account resets the
680 // subscription upstream but leaves the hub refusing to route to it until
681 // its own cooldown expires. A hub credit id that a fresher native redeem
682 // already spent comes back as `alreadyRedeemed`, which still clears the
683 // cooldown, so preferring it is safe even when the hub snapshot is stale.
684 const hubCreditId = hubCredits?.account.usageLimits.resetCredits?.nextCreditId;
685 const showHubCredits =
686 hubCredits &&
687 (!provider.usageLimits.resetCredits ||
688 Date.parse(hubCredits.account.usageLimits.checkedAt) >
689 Date.parse(provider.usageLimits.checkedAt));
690 accounts.push({
691 id: provider.instanceId,
692 driver: provider.driver,
693 label: `${provider.displayName?.trim() || String(provider.driver)} [${provider.instanceId}]`,
694 ...(provider.auth.label ? { plan: provider.auth.label } : {}),
695 instanceId: provider.instanceId,
696 resetCreditInput:
697 hubCreditId && hubCredits
698 ? {
699 sourceId: hubCredits.source.id,
700 accountId: hubCredits.account.id,
701 creditId: hubCreditId,
702 }
703 : { instanceId: provider.instanceId },
704 ...(provider.displayName ? { displayName: provider.displayName } : {}),
705 ...(provider.accentColor ? { accentColor: provider.accentColor } : {}),
706 ...(provider.auth.email ? { email: provider.auth.email } : {}),
707 limits: showHubCredits
708 ? { ...provider.usageLimits, resetCredits: hubCredits.account.usageLimits.resetCredits }
709 : provider.usageLimits,
710 });
711 }
712 for (const source of sources) {
713 const matching = source.accounts.filter((account) => account.driver === selected.driver);
714 for (const account of matching) {
715 const key = accountKey(account.driver, account.email);
716 if (key && nativeAccounts.has(key)) continue;
717 accounts.push({
718 id: `${source.id}:${account.id}`,
719 driver: account.driver,
720 label: `${source.label} · ${account.id}`,
721 sourceLabel: "CLI Proxy",
722 ...(account.usageLimits.resetCredits?.nextCreditId
723 ? {
724 resetCreditInput: {
725 sourceId: source.id,
726 accountId: account.id,
727 creditId: account.usageLimits.resetCredits.nextCreditId,
728 },
729 }
730 : {}),
731 ...(account.plan ? { plan: account.plan } : {}),
732 ...(account.email ? { email: account.email } : {}),
733 limits: account.usageLimits,
734 });
735 }
736 // A source that failed to read has no accounts left to match on, so its
737 // error is reported to every provider rather than silently dropped.
738 if (source.error && (matching.length > 0 || source.accounts.length === 0)) {
739 notices.push(`${source.label}: ${source.error}`);
740 }
741 }
742 return { createdAt: DateTime.formatIso(DateTime.makeUnsafe(now)), accounts, notices };
743}
744
745/** Whether the selected model can use the subscription snapshot. A reset time
746 * triggers a refresh; passing that time alone never proves capacity returned. */
747export function modelUsageAvailability(
748 limits: ServerProviderUsageLimits | undefined,
749 model: string,
750 now: number,
751): { readonly status: "available" | "exhausted" | "unknown"; readonly resetsAt: number | null } {
752 if (!limits || limits.unavailable) return { status: "unknown", resetsAt: null };
753 const modelTokens = model.toLowerCase().split(/[^a-z0-9]+/);
754 const windows = limits.windows.filter((window) => {
755 if (!window.id.startsWith("seven_day_")) return true;
756 const scope = window.id.slice("seven_day_".length);
757 return scope.split("_").every((token) => modelTokens.includes(token));
758 });
759 if (windows.length === 0) return { status: "unknown", resetsAt: null };
760 const exhausted = windows.filter((window) => window.usedPercent >= 100);
761 if (exhausted.length > 0) {
762 const resets = exhausted.map(resetMillis);
763 return {
764 status: "exhausted",
765 resetsAt: resets.some((at) => at === null)
766 ? null
767 : Math.max(...resets.filter((at) => at !== null)),
768 };
769 }
770 // Positive capacity must be recent, and windows from before their reset
771 // must be refreshed before an unattended turn is admitted.
772 const checkedAt = Date.parse(limits.checkedAt);
773 const fresh = checkedAt <= now && now - checkedAt <= 5 * MINUTE;
774 const expired = windows.some((window) => {
775 const reset = resetMillis(window);
776 return reset !== null && reset <= now;
777 });
778 return { status: fresh && !expired ? "available" : "unknown", resetsAt: null };
779}