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