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