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 merge = (key: string, next: LimitAccount) => {
193 const previousCredit = creditSources.get(key);
194 if (
195 next.limits.resetCredits &&
196 (!previousCredit ||
197 Date.parse(next.limits.checkedAt) > Date.parse(previousCredit.limits.checkedAt))
198 ) {
199 creditSources.set(key, next);
200 }
201 const previous = accounts.get(key);
202 if (!previous) {
203 accounts.set(key, next);
204 return;
205 }
206 const fresher = Date.parse(next.limits.checkedAt) > Date.parse(previous.limits.checkedAt);
207 // Two instances on one machine sharing an account still name it once.
208 const environments = [
209 ...previous.environments,
210 ...next.environments.filter(
211 (candidate) =>
212 !previous.environments.some((seen) => seen.environmentId === candidate.environmentId),
213 ),
214 ];
215 const winner = fresher ? next : previous;
216 // Credits and their redemption target travel together. A failed credit
217 // probe must not erase a successful read from another environment.
218 const creditSource = creditSources.get(key);
219 accounts.set(key, {
220 ...previous,
221 displayName: previous.displayName ?? next.displayName,
222 plan: previous.plan ?? next.plan,
223 accentColor: previous.accentColor ?? next.accentColor,
224 environments,
225 // A hub only names the account when no environment has it natively.
226 sourceLabel: environments.length > 0 ? null : (previous.sourceLabel ?? next.sourceLabel),
227 redeem: creditSource
228 ? creditSource.redeem
229 : (winner.redeem ?? previous.redeem ?? next.redeem),
230 limits: {
231 ...winner.limits,
232 ...(creditSource?.limits.resetCredits
233 ? { resetCredits: creditSource.limits.resetCredits }
234 : { resetCredits: undefined }),
235 },
236 });
237 };
238 for (const [environmentId, presentation] of presentations) {
239 const label = presentation.entry.target.label;
240 for (const provider of providersWithLimits(presentation.serverConfig?.providers ?? [])) {
241 if (!provider.usageLimits || limitsNotice(provider.usageLimits) !== null) continue;
242 merge(
243 accountKey(provider.driver, provider.auth.email) ??
244 `${environmentId}:${provider.instanceId}`,
245 {
246 key: `${environmentId}:${provider.instanceId}`,
247 driver: provider.driver,
248 displayName: provider.displayName?.trim() || null,
249 email: provider.auth.email,
250 plan: provider.auth.label,
251 accentColor: provider.accentColor,
252 environments: [{ environmentId, label }],
253 sourceLabel: null,
254 redeem: { environmentId, input: { instanceId: provider.instanceId } },
255 limits: provider.usageLimits,
256 },
257 );
258 }
259 }
260 // Every hub account, including those a native instance also knows: the hub
261 // may hold a fresher read of the same subscription, and the merge above
262 // keeps the redeem target consistent with whichever snapshot wins.
263 const labelEnvironment = presentations.size > 1;
264 for (const [environmentId, presentation] of presentations) {
265 for (const source of presentation.serverConfig?.usageLimitSources ?? []) {
266 const sourceLabel = labelEnvironment
267 ? `${presentation.entry.target.label} · ${source.label}`
268 : source.label;
269 for (const account of source.accounts) {
270 if (limitsNotice(account.usageLimits) !== null) continue;
271 merge(accountKey(account.driver, account.email) ?? `${source.id}:${account.id}`, {
272 key: `${source.id}:${account.id}`,
273 driver: account.driver,
274 displayName: account.email ? null : account.id.replace(/\.json$/i, ""),
275 email: account.email,
276 plan: account.plan,
277 accentColor: undefined,
278 environments: [],
279 sourceLabel,
280 redeem: account.usageLimits.resetCredits?.nextCreditId
281 ? {
282 environmentId,
283 input: {
284 sourceId: source.id,
285 accountId: account.id,
286 creditId: account.usageLimits.resetCredits.nextCreditId,
287 },
288 }
289 : null,
290 limits: account.usageLimits,
291 });
292 }
293 }
294 }
295 return [...accounts.values()];
296}
297
298/**
299 * What the pooled views cannot draw as a bar: a hub that failed to read, a
300 * provider whose probe failed. Accounts that can never report (API keys)
301 * are left out; there is nothing for the user to act on. The environment
302 * is named only when more than one is connected.
303 */
304export function collectLimitNotices(
305 presentations: Parameters<typeof collectLimitSources>[0],
306): readonly string[] {
307 const label = (environmentLabel: string, subject: string) =>
308 presentations.size > 1 ? `${environmentLabel} · ${subject}` : subject;
309 const notices: string[] = [];
310 for (const presentation of presentations.values()) {
311 const environmentLabel = presentation.entry.target.label;
312 for (const provider of providersWithLimits(presentation.serverConfig?.providers ?? [])) {
313 // An account that can never report (API key) is left out; one that
314 // failed, or reported nothing at all, is worth a line.
315 if (provider.usageLimits?.unavailable?.reason === "unsupported") continue;
316 const notice = provider.usageLimits ? limitsNotice(provider.usageLimits) : null;
317 const name = provider.displayName?.trim() || String(provider.driver);
318 if (notice) notices.push(`${label(environmentLabel, name)}: ${notice}`);
319 }
320 for (const source of presentation.serverConfig?.usageLimitSources ?? []) {
321 if (source.error) {
322 notices.push(`${label(environmentLabel, source.label)}: ${source.error}`);
323 } else if (source.accounts.length === 0) {
324 notices.push(`${label(environmentLabel, source.label)}: No accounts reported.`);
325 }
326 }
327 }
328 return notices;
329}
330
331export interface LimitPoolMember {
332 readonly account: LimitAccount;
333 readonly window: ServerProviderUsageWindow;
334}
335
336/**
337 * One window id across every account that reports it: the pooled share left,
338 * pace against the clock, and the resets in the order they will land, each
339 * with the share of the pool it hands back.
340 */
341export interface LimitPoolWindow {
342 readonly id: string;
343 readonly kind: ServerProviderUsageWindow["kind"];
344 readonly label: string;
345 readonly members: readonly LimitPoolMember[];
346 readonly remainingPercent: number;
347 readonly usedPercent: number;
348 readonly pace: LimitPace | null;
349 readonly resets: ReadonlyArray<{
350 readonly member: LimitPoolMember;
351 readonly at: number;
352 /** Points of the pool the reset restores: the member's used share over the member count. */
353 readonly restoresPercent: number;
354 }>;
355}
356
357export interface LimitPool {
358 readonly driver: ServerProvider["driver"];
359 readonly accounts: readonly LimitAccount[];
360 readonly windows: readonly LimitPoolWindow[];
361}
362
363const WINDOW_KIND_ORDER: Record<ServerProviderUsageWindow["kind"], number> = {
364 session: 0,
365 weekly: 1,
366 monthly: 2,
367 other: 3,
368};
369
370/**
371 * Accounts grouped by driver, each with its windows pooled by kind and id.
372 * Window ids are stable per provider, so a hub row and a native row for the
373 * same window land in the same pool; the kind is part of the key because
374 * Codex's `primary` is a position, not a duration (five hours on paid plans,
375 * a month on Free/Go), and a monthly allowance must not average into a
376 * five-hour pool. Pools order by kind, then first appearance.
377 *
378 * `accounts` is the table order: instances the user can act on (native,
379 * named) before hub-only accounts, each group alphabetical. Each window's
380 * `members` sort by reset instead, soonest first, so a bar reads left to
381 * right as "who refills next" and matches the reset list under it.
382 */
383export function collectLimitPools(
384 accounts: readonly LimitAccount[],
385 now: number,
386): readonly LimitPool[] {
387 const byDriver = new Map<ServerProvider["driver"], LimitAccount[]>();
388 for (const account of accounts) {
389 const list = byDriver.get(account.driver);
390 if (list) list.push(account);
391 else byDriver.set(account.driver, [account]);
392 }
393 return [...byDriver].map(([driver, members]) => {
394 const sorted = [...members].sort(
395 (left, right) =>
396 Number(left.redeem === null) - Number(right.redeem === null) ||
397 accountSortName(left).localeCompare(accountSortName(right)),
398 );
399 return { driver, accounts: sorted, windows: poolWindows(sorted, now) };
400 });
401}
402
403function accountSortName(account: LimitAccount): string {
404 return (account.displayName ?? account.email ?? account.key).toLowerCase();
405}
406
407function poolWindows(accounts: readonly LimitAccount[], now: number): readonly LimitPoolWindow[] {
408 const byKey = new Map<string, LimitPoolMember[]>();
409 for (const account of accounts) {
410 for (const window of account.limits.windows) {
411 const key = `${window.kind}:${window.id}`;
412 const list = byKey.get(key);
413 if (list) list.push({ account, window });
414 else byKey.set(key, [{ account, window }]);
415 }
416 }
417 const pools = [...byKey.values()].map((unordered): LimitPoolWindow => {
418 const members = [...unordered].sort(
419 (left, right) =>
420 (resetMillis(left.window) ?? Number.POSITIVE_INFINITY) -
421 (resetMillis(right.window) ?? Number.POSITIVE_INFINITY),
422 );
423 const first = members[0]!.window;
424 const usedPercent = members.reduce((sum, m) => sum + m.window.usedPercent, 0) / members.length;
425 // Pace compares spend against the clock, so it is judged only over the
426 // members that have a clock; a window with no reset would otherwise
427 // count as spend with no time elapsed and skew the verdict.
428 const timed = members.flatMap((m) => {
429 const share = elapsedShare(m.window, now);
430 return share === null ? [] : [{ used: m.window.usedPercent, elapsed: share }];
431 });
432 const timedUsed = timed.reduce((sum, t) => sum + t.used, 0) / timed.length;
433 const meanElapsed =
434 timed.length > 0 ? timed.reduce((sum, t) => sum + t.elapsed, 0) / timed.length : null;
435 const resets = members
436 .flatMap((member) => {
437 const at = resetMillis(member.window);
438 return at === null
439 ? []
440 : [
441 {
442 member,
443 at,
444 restoresPercent: Math.round(member.window.usedPercent / members.length),
445 },
446 ];
447 })
448 .sort((left, right) => left.at - right.at);
449 return {
450 id: first.id,
451 kind: first.kind,
452 label: first.label,
453 members,
454 usedPercent: Math.round(usedPercent),
455 remainingPercent: Math.round(100 - usedPercent),
456 pace: meanElapsed === null ? null : paceOfShares(timedUsed, meanElapsed),
457 resets,
458 };
459 });
460 return pools.sort((left, right) => WINDOW_KIND_ORDER[left.kind] - WINDOW_KIND_ORDER[right.kind]);
461}
462
463/** The one-line status under a provider heading when there are no bars to draw. */
464export function limitsNotice(limits: ServerProviderUsageLimits): string | null {
465 if (limits.unavailable?.reason === "unsupported") {
466 return limits.unavailable.message ?? "This account has no subscription limits.";
467 }
468 if (limits.unavailable?.reason === "probeFailed") {
469 return limits.unavailable.message ?? "Could not read limits.";
470 }
471 return limits.windows.length === 0 ? "No limits reported." : null;
472}
473
474/** Quota left in the window, 0..100. Bars and labels show what remains, as Codex does. */
475export function remainingPercent(window: ServerProviderUsageWindow): number {
476 return Math.round(100 - Math.max(0, Math.min(100, window.usedPercent)));
477}
478
479function resetMillis(window: ServerProviderUsageWindow): number | null {
480 if (window.resetsAt === undefined) return null;
481 const at = Date.parse(window.resetsAt);
482 return Number.isFinite(at) ? at : null;
483}
484
485/** Elapsed share of the window, 0..1, or null when its length or reset is unknown. */
486export function elapsedShare(window: ServerProviderUsageWindow, now: number): number | null {
487 const resetsAt = resetMillis(window);
488 if (resetsAt === null || window.windowDurationMins === undefined) return null;
489 const length = window.windowDurationMins * MINUTE;
490 if (length <= 0) return null;
491 return Math.max(0, Math.min(1, (length - (resetsAt - now)) / length));
492}
493
494export type LimitPace = "ahead" | "on" | "under";
495
496/**
497 * Usage against the clock. Spending evenly leaves the same share of quota as
498 * there is time left in the window; within five points of that counts as on
499 * pace, further ahead means the window may run dry first.
500 */
501export function paceOf(window: ServerProviderUsageWindow, now: number): LimitPace | null {
502 const elapsed = elapsedShare(window, now);
503 return elapsed === null ? null : paceOfShares(window.usedPercent, elapsed);
504}
505
506function paceOfShares(usedPercent: number, elapsed: number): LimitPace {
507 const gap = usedPercent - elapsed * 100;
508 if (gap > 5) return "ahead";
509 if (gap < -5) return "under";
510 return "on";
511}
512
513/** `2h 13m`, `3d 4h`, `12m`. */
514export function formatDuration(ms: number): string {
515 const remaining = Math.max(0, ms);
516 const days = Math.floor(remaining / DAY);
517 const hours = Math.floor((remaining % DAY) / HOUR);
518 const minutes = Math.floor((remaining % HOUR) / MINUTE);
519 if (days > 0) return `${days}d ${hours}h`;
520 if (hours > 0) return `${hours}h ${minutes}m`;
521 return `${minutes}m`;
522}
523
524/** `resets in 2h 13m`, or null when the window has no reset. */
525export function formatResetsIn(window: ServerProviderUsageWindow, now: number): string | null {
526 const resetsAt = resetMillis(window);
527 if (resetsAt === null) return null;
528 return resetsAt <= now ? "resets now" : `resets in ${formatDuration(resetsAt - now)}`;
529}
530
531/** Limit commands are served by T3 from the same snapshots as Usage → Limits. */
532export const USAGE_LIMITS_COMMAND = {
533 name: "usage-limits",
534 description: "Show this provider's usage limits",
535} satisfies ServerProviderSlashCommand;
536
537/** Handled by the client without sending a turn; anything with arguments stays an ordinary prompt. */
538export function isUsageLimitsCommand(prompt: string): boolean {
539 return prompt.trim().toLowerCase() === "/usage-limits";
540}
541
542/**
543 * Whether Limits has anything to say about this driver. A source that failed to
544 * read keeps no accounts, so its error counts for every driver rather than
545 * disappearing until the next successful refresh.
546 */
547export function hasProviderUsageLimits(
548 driver: ServerProvider["driver"],
549 providers: readonly ServerProvider[],
550 sources: UsageLimitSourceSnapshots,
551): boolean {
552 return (
553 providersWithLimits(providers).some((provider) => provider.driver === driver) ||
554 sources.some(
555 (source) =>
556 source.accounts.some((account) => account.driver === driver) ||
557 (source.error !== undefined && source.accounts.length === 0),
558 )
559 );
560}
561
562/**
563 * The drivers a set of sources would offer the command to, where a source that
564 * failed to read counts for every driver. Two snapshots with the same coverage
565 * need no catalog republish, however much their quotas moved.
566 */
567export function sameUsageLimitCommandCoverage(
568 previous: UsageLimitSourceSnapshots,
569 next: UsageLimitSourceSnapshots,
570): boolean {
571 const coverage = (sources: UsageLimitSourceSnapshots) =>
572 new Set(
573 sources.flatMap((source) =>
574 source.error !== undefined && source.accounts.length === 0
575 ? ["*"]
576 : source.accounts.map((account) => String(account.driver)),
577 ),
578 );
579 const before = coverage(previous);
580 const after = coverage(next);
581 return before.size === after.size && [...before].every((driver) => after.has(driver));
582}
583
584/** Advertise on workspace catalogs too, which replace the global command list. */
585export function withUsageLimitsCommands(
586 providers: readonly ServerProvider[],
587 sources: UsageLimitSourceSnapshots,
588): ServerProvider[] {
589 return providers.map((provider) => {
590 if (!hasProviderUsageLimits(provider.driver, providers, sources)) return provider;
591 const commands = (items: readonly ServerProviderSlashCommand[]) => [
592 ...items.filter((command) => command.name !== USAGE_LIMITS_COMMAND.name),
593 USAGE_LIMITS_COMMAND,
594 ];
595 return {
596 ...provider,
597 slashCommands: commands(provider.slashCommands),
598 ...(provider.workspaceSnapshots
599 ? {
600 workspaceSnapshots: provider.workspaceSnapshots.map((snapshot) => ({
601 ...snapshot,
602 slashCommands: commands(snapshot.slashCommands),
603 })),
604 }
605 : {}),
606 };
607 });
608}
609
610/** A point-in-time report; never refreshes or guesses which pooled account serves a turn. */
611export function collectProviderUsageLimits(
612 instanceId: ProviderInstanceId,
613 providers: readonly ServerProvider[],
614 sources: UsageLimitSourceSnapshots,
615 now: number,
616): UsageLimitsReport | null {
617 const selected = providers.find((provider) => provider.instanceId === instanceId);
618 if (!selected || !hasProviderUsageLimits(selected.driver, providers, sources)) return null;
619 const native = providersWithLimits(providers).filter(
620 (provider) => provider.driver === selected.driver,
621 );
622 const nativeAccounts = new Set(
623 native.flatMap((provider) => {
624 const key = accountKey(provider.driver, provider.auth.email);
625 return key && provider.usageLimits?.windows.length && !provider.usageLimits.unavailable
626 ? [key]
627 : [];
628 }),
629 );
630 const accounts: Array<UsageLimitsReport["accounts"][number]> = [];
631 const notices: string[] = [];
632 for (const provider of native) {
633 if (!provider.usageLimits) continue;
634 const key = accountKey(provider.driver, provider.auth.email);
635 const hubCredits = sources
636 .flatMap((source) => source.accounts.map((account) => ({ source, account })))
637 .filter(
638 ({ account }) =>
639 key !== null &&
640 accountKey(account.driver, account.email) === key &&
641 account.usageLimits.resetCredits &&
642 !limitsNotice(account.usageLimits),
643 )
644 .sort(
645 (a, b) =>
646 Date.parse(b.account.usageLimits.checkedAt) - Date.parse(a.account.usageLimits.checkedAt),
647 )[0];
648 const useHubCredits =
649 hubCredits &&
650 (!provider.usageLimits.resetCredits ||
651 Date.parse(hubCredits.account.usageLimits.checkedAt) >
652 Date.parse(provider.usageLimits.checkedAt));
653 const hubCreditId = useHubCredits
654 ? hubCredits.account.usageLimits.resetCredits?.nextCreditId
655 : undefined;
656 accounts.push({
657 id: provider.instanceId,
658 driver: provider.driver,
659 label: `${provider.displayName?.trim() || String(provider.driver)} [${provider.instanceId}]`,
660 ...(provider.auth.label ? { plan: provider.auth.label } : {}),
661 instanceId: provider.instanceId,
662 resetCreditInput:
663 hubCreditId && hubCredits
664 ? {
665 sourceId: hubCredits.source.id,
666 accountId: hubCredits.account.id,
667 creditId: hubCreditId,
668 }
669 : { instanceId: provider.instanceId },
670 ...(provider.displayName ? { displayName: provider.displayName } : {}),
671 ...(provider.accentColor ? { accentColor: provider.accentColor } : {}),
672 ...(provider.auth.email ? { email: provider.auth.email } : {}),
673 limits: useHubCredits
674 ? { ...provider.usageLimits, resetCredits: hubCredits.account.usageLimits.resetCredits }
675 : provider.usageLimits,
676 });
677 }
678 for (const source of sources) {
679 const matching = source.accounts.filter((account) => account.driver === selected.driver);
680 for (const account of matching) {
681 const key = accountKey(account.driver, account.email);
682 if (key && nativeAccounts.has(key)) continue;
683 accounts.push({
684 id: `${source.id}:${account.id}`,
685 driver: account.driver,
686 label: `${source.label} · ${account.id}`,
687 sourceLabel: "CLI Proxy",
688 ...(account.usageLimits.resetCredits?.nextCreditId
689 ? {
690 resetCreditInput: {
691 sourceId: source.id,
692 accountId: account.id,
693 creditId: account.usageLimits.resetCredits.nextCreditId,
694 },
695 }
696 : {}),
697 ...(account.plan ? { plan: account.plan } : {}),
698 ...(account.email ? { email: account.email } : {}),
699 limits: account.usageLimits,
700 });
701 }
702 // A source that failed to read has no accounts left to match on, so its
703 // error is reported to every provider rather than silently dropped.
704 if (source.error && (matching.length > 0 || source.accounts.length === 0)) {
705 notices.push(`${source.label}: ${source.error}`);
706 }
707 }
708 return { createdAt: DateTime.formatIso(DateTime.makeUnsafe(now)), accounts, notices };
709}