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 readonly remainingPercent: number;
361 readonly usedPercent: number;
362 readonly pace: LimitPace | null;
363 readonly resets: ReadonlyArray<{
364 readonly member: LimitPoolMember;
365 readonly at: number;
366 /** Points of the pool the reset restores: the member's used share over the member count. */
367 readonly restoresPercent: number;
368 }>;
369}
370
371export interface LimitPool {
372 readonly driver: ServerProvider["driver"];
373 readonly accounts: readonly LimitAccount[];
374 readonly windows: readonly LimitPoolWindow[];
375}
376
377const WINDOW_KIND_ORDER: Record<ServerProviderUsageWindow["kind"], number> = {
378 session: 0,
379 weekly: 1,
380 monthly: 2,
381 other: 3,
382};
383
384/**
385 * Accounts grouped by driver, each with its windows pooled by kind and id.
386 * Window ids are stable per provider, so a hub row and a native row for the
387 * same window land in the same pool; the kind is part of the key because
388 * Codex's `primary` is a position, not a duration (five hours on paid plans,
389 * a month on Free/Go), and a monthly allowance must not average into a
390 * five-hour pool. Pools order by kind, then first appearance.
391 *
392 * `accounts` is the table order: instances the user can act on (native,
393 * named) before hub-only accounts, each group alphabetical. Each window's
394 * `members` sort by reset instead, soonest first, so a bar reads left to
395 * right as "who refills next" and matches the reset list under it.
396 */
397export function collectLimitPools(
398 accounts: readonly LimitAccount[],
399 now: number,
400): readonly LimitPool[] {
401 const byDriver = new Map<ServerProvider["driver"], LimitAccount[]>();
402 for (const account of accounts) {
403 const list = byDriver.get(account.driver);
404 if (list) list.push(account);
405 else byDriver.set(account.driver, [account]);
406 }
407 return [...byDriver].map(([driver, members]) => {
408 const sorted = [...members].sort(
409 (left, right) =>
410 Number(left.redeem === null) - Number(right.redeem === null) ||
411 accountSortName(left).localeCompare(accountSortName(right)),
412 );
413 return { driver, accounts: sorted, windows: poolWindows(sorted, now) };
414 });
415}
416
417function accountSortName(account: LimitAccount): string {
418 return (account.displayName ?? account.email ?? account.key).toLowerCase();
419}
420
421function poolWindows(accounts: readonly LimitAccount[], now: number): readonly LimitPoolWindow[] {
422 const byKey = new Map<string, LimitPoolMember[]>();
423 for (const account of accounts) {
424 for (const window of account.limits.windows) {
425 const key = `${window.kind}:${window.id}`;
426 const list = byKey.get(key);
427 if (list) list.push({ account, window });
428 else byKey.set(key, [{ account, window }]);
429 }
430 }
431 const pools = [...byKey.values()].map((unordered): LimitPoolWindow => {
432 const members = [...unordered].sort(
433 (left, right) =>
434 (resetMillis(left.window) ?? Number.POSITIVE_INFINITY) -
435 (resetMillis(right.window) ?? Number.POSITIVE_INFINITY),
436 );
437 const first = members[0]!.window;
438 const usedPercent = members.reduce((sum, m) => sum + m.window.usedPercent, 0) / members.length;
439 // Pace compares spend against the clock, so it is judged only over the
440 // members that have a clock; a window with no reset would otherwise
441 // count as spend with no time elapsed and skew the verdict.
442 const timed = members.flatMap((m) => {
443 const share = elapsedShare(m.window, now);
444 return share === null ? [] : [{ used: m.window.usedPercent, elapsed: share }];
445 });
446 const timedUsed = timed.reduce((sum, t) => sum + t.used, 0) / timed.length;
447 const meanElapsed =
448 timed.length > 0 ? timed.reduce((sum, t) => sum + t.elapsed, 0) / timed.length : null;
449 const resets = members
450 .flatMap((member) => {
451 const at = resetMillis(member.window);
452 return at === null
453 ? []
454 : [
455 {
456 member,
457 at,
458 restoresPercent: Math.round(member.window.usedPercent / members.length),
459 },
460 ];
461 })
462 .sort((left, right) => left.at - right.at);
463 return {
464 id: first.id,
465 kind: first.kind,
466 label: first.label,
467 members,
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);
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);
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) === 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);
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}