Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

usageLimits.ts

697 lines25.5 KB

1import {
2 type EnvironmentId,
3 type UsageLimitsReport,
4 type ProviderInstanceId,
5 type ProviderConsumeResetCreditInput,
6 type ServerProviderSlashCommand,
7 isProviderAvailable,
8 type ServerProvider,
9 type ServerProviderUsageLimits,
10 type ServerProviderUsageWindow,
11 type UsageLimitSourceSnapshots,
12} from "@t3tools/contracts";
13​
14import * as DateTime from "effect/DateTime";
15​
16const MINUTE = 60_000;
17const HOUR = 60 * MINUTE;
18const DAY = 24 * HOUR;
19​
20export const CHATGPT_USAGE_URL = "https://chatgpt.com/#settings/Usage";
21​
22export function usesChatGptSharing(provider: ServerProvider | null | undefined): boolean {
23 return provider?.auth.status === "authenticated" && provider.auth.subscriptionSharing === true;
25​
26export const CURSOR_USAGE_WINDOWS = [
27 {
28 id: "totalPercentUsed",
29 label: "Overall",
30 description: "Combined usage across both allowances, not a third quota.",
31 },
32 {
33 id: "autoPercentUsed",
34 label: "Cursor Models",
35 description: "Grok and Composer use this first. Auto can use either pool.",
36 },
37 {
38 id: "apiPercentUsed",
39 label: "Other Models",
40 description: "Claude, GPT, and Gemini use this pool. Grok and Composer fall back here.",
41 },
42] as const;
43​
44export function cursorUsageWindowDetails(id: string) {
45 return CURSOR_USAGE_WINDOWS.find((window) => window.id === id);
47​
48function cursorUsageWindowRank(id: string): number {
49 const rank = CURSOR_USAGE_WINDOWS.findIndex((window) => window.id === id);
50 return rank < 0 ? CURSOR_USAGE_WINDOWS.length : rank;
52​
53export function providersWithLimits(
54 providers: readonly ServerProvider[],
55): readonly ServerProvider[] {
56 return providers.filter(
57 (provider) =>
58 provider.enabled &&
59 provider.installed &&
60 isProviderAvailable(provider) &&
61 provider.usageLimits !== undefined,
62 );
64​
65export type LimitPresentations = ReadonlyMap<
66 EnvironmentId,
67 {
68 readonly entry: { readonly target: { readonly label: string } };
69 readonly serverConfig: {
70 readonly providers: readonly ServerProvider[];
71 readonly usageLimitSources?: UsageLimitSourceSnapshots | undefined;
72 } | null;
73 }
74>;
75​
76export function collectExternalUsageLinks(presentations: LimitPresentations) {
77 const links = new Map<
78 string,
79 {
80 readonly label: string;
81 readonly url: string;
82 readonly message: string | undefined;
83 readonly accounts: readonly string[];
84 }
85 >();
86 for (const presentation of presentations.values()) {
87 for (const provider of providersWithLimits(presentation.serverConfig?.providers ?? [])) {
88 const external = provider.usageLimits?.externalUsage;
89 if (external && provider.auth.status === "authenticated") {
90 const account = `${provider.displayName ?? provider.instanceId} on ${presentation.entry.target.label}`;
91 links.set(external.url, {
92 ...external,
93 message: provider.usageLimits?.unavailable?.message,
94 accounts: [...new Set([...(links.get(external.url)?.accounts ?? []), account])],
95 });
96 }
97 }
98 }
99 return [...links.values()];
101​
102function accountKey(
103 driver: ServerProvider["driver"],
104 email: string | undefined,
105 limits?: ServerProviderUsageLimits,
106): string | null {
107 const normalizedEmail = email?.trim().toLowerCase();
108 if (normalizedEmail) return `${driver}:${normalizedEmail}`;
109 return limits?.credentialFingerprint
110 ? `${driver}:credential:${limits.credentialFingerprint}`
111 : null;
113​
114interface AccountReport {
115 readonly driver: ServerProvider["driver"];
116 readonly email?: string | undefined;
117 readonly workspaceId?: string | undefined;
118 readonly usageLimits?: ServerProviderUsageLimits | undefined;
120​
121const nativeReport = (provider: ServerProvider): AccountReport => ({
122 driver: provider.driver,
123 email: provider.auth.email,
124 workspaceId: provider.auth.workspaceId,
125 usageLimits: provider.usageLimits,
126});
127​
128/**
129 * Pass every enabled login, read or not, so an unreadable workspace still
130 * counts as one.
131 */
132function accountKeyResolver(reports: Iterable<AccountReport>) {
133 const workspaces = new Map<string, Set<string>>();
134 for (const report of reports) {
135 const key = accountKey(report.driver, report.email, report.usageLimits);
136 if (key && report.workspaceId) {
137 workspaces.set(key, (workspaces.get(key) ?? new Set()).add(report.workspaceId));
138 }
139 }
140 return (report: AccountReport): string | null => {
141 const key = accountKey(report.driver, report.email, report.usageLimits);
142 if (!key) return null;
143 if (report.workspaceId) return `${key}:${report.workspaceId}`;
144 const known = workspaces.get(key);
145 if (!known) return key;
146 return known.size === 1 ? `${key}:${[...known][0]}` : null;
147 };
149​
150export interface LimitAccount {
151 readonly key: string;
152 readonly driver: ServerProvider["driver"];
153 readonly displayName: string | null;
154 readonly email: string | undefined;
155 readonly plan: string | undefined;
156 readonly accentColor: string | undefined;
157 readonly environments: ReadonlyArray<{
158 readonly environmentId: EnvironmentId;
159 readonly label: string;
160 }>;
161 readonly sourceLabel: string | null;
162 readonly redeem: {
163 readonly environmentId: EnvironmentId;
164 readonly input: ProviderConsumeResetCreditInput;
165 } | null;
166 readonly limits: ServerProviderUsageLimits;
168​
169export function collectLimitAccounts(presentations: LimitPresentations): readonly LimitAccount[] {
170 const accounts = new Map<string, LimitAccount>();
171 const creditSources = new Map<string, LimitAccount>();
172 const hubRedeems = new Map<string, LimitAccount>();
173 const merge = (key: string, next: LimitAccount) => {
174 // Redeeming through a hub also clears the routing cooldown that hub holds
175 // for the account. Redeeming natively against the same subscription resets
176 // it upstream but leaves the hub refusing to route to the account until
177 // its own cooldown expires, so a hub target wins the redemption outright
178 // while the displayed balance still follows the freshest read.
179 const previousHub = hubRedeems.get(key);
180 if (
181 next.redeem &&
182 "sourceId" in next.redeem.input &&
183 (!previousHub || Date.parse(next.limits.checkedAt) > Date.parse(previousHub.limits.checkedAt))
184 ) {
185 hubRedeems.set(key, next);
186 }
187 const previousCredit = creditSources.get(key);
188 if (
189 next.limits.resetCredits &&
190 (!previousCredit ||
191 Date.parse(next.limits.checkedAt) > Date.parse(previousCredit.limits.checkedAt))
192 ) {
193 creditSources.set(key, next);
194 }
195 const previous = accounts.get(key);
196 if (!previous) {
197 accounts.set(key, next);
198 return;
199 }
200 const fresher = Date.parse(next.limits.checkedAt) > Date.parse(previous.limits.checkedAt);
201 const environments = [
202 ...previous.environments,
203 ...next.environments.filter(
204 (candidate) =>
205 !previous.environments.some((seen) => seen.environmentId === candidate.environmentId),
206 ),
207 ];
208 const winner = fresher ? next : previous;
209 const creditSource = creditSources.get(key);
210 accounts.set(key, {
211 ...previous,
212 displayName: previous.displayName ?? next.displayName,
213 plan: previous.plan ?? next.plan,
214 accentColor: previous.accentColor ?? next.accentColor,
215 environments,
216 sourceLabel: environments.length > 0 ? null : (previous.sourceLabel ?? next.sourceLabel),
217 redeem:
218 hubRedeems.get(key)?.redeem ??
219 (creditSource ? creditSource.redeem : (winner.redeem ?? previous.redeem ?? next.redeem)),
220 limits: {
221 ...winner.limits,
222 ...(creditSource?.limits.resetCredits
223 ? { resetCredits: creditSource.limits.resetCredits }
224 : { resetCredits: undefined }),
225 },
226 });
227 };
228 const resolveKey = accountKeyResolver(
229 [...presentations.values()].flatMap((presentation) => [
230 ...(presentation.serverConfig?.providers ?? [])
231 .filter((provider) => provider.enabled)
232 .map(nativeReport),
233 ...(presentation.serverConfig?.usageLimitSources ?? []).flatMap((source) => source.accounts),
234 ]),
235 );
236 for (const [environmentId, presentation] of presentations) {
237 const label = presentation.entry.target.label;
238 for (const provider of providersWithLimits(presentation.serverConfig?.providers ?? [])) {
239 if (!provider.usageLimits || limitsNotice(provider.usageLimits) !== null) continue;
240 merge(resolveKey(nativeReport(provider)) ?? `${environmentId}:${provider.instanceId}`, {
241 key: `${environmentId}:${provider.instanceId}`,
242 driver: provider.driver,
243 displayName: provider.displayName?.trim() || null,
244 email: provider.auth.email,
245 plan: provider.auth.label,
246 accentColor: provider.accentColor,
247 environments: [{ environmentId, label }],
248 sourceLabel: null,
249 redeem: { environmentId, input: { instanceId: provider.instanceId } },
250 limits: provider.usageLimits,
251 });
252 }
253 }
254 const labelEnvironment = presentations.size > 1;
255 for (const [environmentId, presentation] of presentations) {
256 for (const source of presentation.serverConfig?.usageLimitSources ?? []) {
257 const sourceLabel = labelEnvironment
258 ? `${presentation.entry.target.label} · ${source.label}`
259 : source.label;
260 for (const account of source.accounts) {
261 if (limitsNotice(account.usageLimits) !== null) continue;
262 const key = `${source.id}:${account.id}${account.workspaceId ? `:${account.workspaceId}` : ""}`;
263 merge(resolveKey(account) ?? key, {
264 key,
265 driver: account.driver,
266 displayName: account.email ? null : account.id.replace(/\.json$/i, ""),
267 email: account.email,
268 plan: account.plan,
269 accentColor: undefined,
270 environments: [],
271 sourceLabel,
272 redeem: account.usageLimits.resetCredits?.nextCreditId
273 ? {
274 environmentId,
275 input: {
276 sourceId: source.id,
277 accountId: account.id,
278 creditId: account.usageLimits.resetCredits.nextCreditId,
279 },
280 }
281 : null,
282 limits: account.usageLimits,
283 });
284 }
285 }
286 }
287 return [...accounts.values()];
289​
290export function collectLimitNotices(presentations: LimitPresentations): readonly string[] {
291 const label = (environmentLabel: string, subject: string) =>
292 presentations.size > 1 ? `${environmentLabel} · ${subject}` : subject;
293 const notices: string[] = [];
294 for (const presentation of presentations.values()) {
295 const environmentLabel = presentation.entry.target.label;
296 for (const provider of providersWithLimits(presentation.serverConfig?.providers ?? [])) {
297 if (provider.usageLimits?.unavailable?.reason === "unsupported") continue;
298 const notice = provider.usageLimits ? limitsNotice(provider.usageLimits) : null;
299 const name = provider.displayName?.trim() || String(provider.driver);
300 if (notice) notices.push(`${label(environmentLabel, name)}: ${notice}`);
301 }
302 for (const source of presentation.serverConfig?.usageLimitSources ?? []) {
303 if (source.error) {
304 notices.push(`${label(environmentLabel, source.label)}: ${source.error}`);
305 } else if (source.accounts.length === 0) {
306 notices.push(`${label(environmentLabel, source.label)}: No accounts reported.`);
307 }
308 }
309 }
310 return notices;
312​
313export interface LimitPoolMember {
314 readonly account: LimitAccount;
315 readonly window: ServerProviderUsageWindow;
317​
318export interface LimitPoolWindow {
319 readonly id: string;
320 readonly kind: ServerProviderUsageWindow["kind"];
321 readonly label: string;
322 readonly members: readonly LimitPoolMember[];
323 readonly columns: ReadonlyArray<{
324 readonly account: LimitAccount;
325 readonly window: ServerProviderUsageWindow | null;
326 }>;
327 readonly remainingPercent: number;
328 readonly usedPercent: number;
329 readonly pace: LimitPace | null;
330 readonly resets: ReadonlyArray<{
331 readonly member: LimitPoolMember;
332 readonly at: number;
333 readonly restoresPercent: number;
334 }>;
336​
337export interface LimitPool {
338 readonly driver: ServerProvider["driver"];
339 readonly accounts: readonly LimitAccount[];
340 readonly windows: readonly LimitPoolWindow[];
342​
343export function displayLimitWindows(pool: LimitPool) {
344 if (pool.driver === "antigravity") {
345 return [...pool.windows].sort(
346 (left, right) =>
347 Number(!left.id.startsWith("gemini-")) - Number(!right.id.startsWith("gemini-")) ||
348 left.id
349 .replace(/-(5h|weekly|quota)$/, "")
350 .localeCompare(right.id.replace(/-(5h|weekly|quota)$/, "")) ||
351 WINDOW_KIND_ORDER[left.kind] - WINDOW_KIND_ORDER[right.kind],
352 );
353 }
354 if (pool.driver !== "cursor") return pool.windows;
355 const hasAuto = pool.windows.some((window) => window.id === "autoPercentUsed");
356 const hasApi = pool.windows.some((window) => window.id === "apiPercentUsed");
357 const hasBothPools = hasAuto && hasApi;
358 return pool.windows
359 .filter((window) => !hasBothPools || window.id !== "totalPercentUsed")
360 .sort((left, right) => cursorUsageWindowRank(left.id) - cursorUsageWindowRank(right.id));
362​
363const WINDOW_KIND_ORDER: Record<ServerProviderUsageWindow["kind"], number> = {
364 session: 0,
365 weekly: 1,
366 monthly: 2,
367 other: 3,
368};
369​
370export function collectLimitPools(
371 accounts: readonly LimitAccount[],
372 now: number,
373): readonly LimitPool[] {
374 const byDriver = new Map<ServerProvider["driver"], LimitAccount[]>();
375 for (const account of accounts) {
376 const list = byDriver.get(account.driver);
377 if (list) list.push(account);
378 else byDriver.set(account.driver, [account]);
379 }
380 return [...byDriver].map(([driver, members]) => {
381 const orderWindow = members
382 .flatMap((account) => account.limits.windows)
383 .sort((left, right) => WINDOW_KIND_ORDER[left.kind] - WINDOW_KIND_ORDER[right.kind])[0];
384 const orderReset = (account: LimitAccount) => {
385 const window = account.limits.windows.find(
386 (window) => orderWindow && poolKey(driver, window) === poolKey(driver, orderWindow),
387 );
388 return (window ? resetMillis(window) : null) ?? Number.POSITIVE_INFINITY;
389 };
390 const sorted = [...members].sort(
391 (left, right) =>
392 orderReset(left) - orderReset(right) ||
393 accountSortName(left).localeCompare(accountSortName(right)) ||
394 left.key.localeCompare(right.key),
395 );
396 return { driver, accounts: sorted, windows: poolWindows(sorted, now) };
397 });
399​
400function accountSortName(account: LimitAccount): string {
401 return (account.displayName ?? account.email ?? account.key).toLowerCase();
403​
404/**
405 * Codex ids are slots, not allowances: a weekly-only plan reports its weekly
406 * window as `primary`, other plans as `secondary`. Its windows pool by kind;
407 * other drivers' ids name distinct allowances.
408 */
409function poolKey(driver: ServerProvider["driver"], window: ServerProviderUsageWindow): string {
410 return driver === "codex" ? window.kind : `${window.kind}:${window.id}`;
412​
413function poolWindows(accounts: readonly LimitAccount[], now: number): readonly LimitPoolWindow[] {
414 const byKey = new Map<string, LimitPoolMember[]>();
415 for (const account of accounts) {
416 for (const window of account.limits.windows) {
417 const pooled = poolKey(account.driver, window);
418 const key = byKey.get(pooled)?.some((member) => member.account === account)
419 ? `${window.kind}:${window.id}`
420 : pooled;
421 const list = byKey.get(key);
422 if (list) list.push({ account, window });
423 else byKey.set(key, [{ account, window }]);
424 }
425 }
426 const pools = [...byKey].map(([key, members]): LimitPoolWindow => {
427 const memberByAccount = new Map(members.map((member) => [member.account.key, member]));
428 const first = members[0]!.window;
429 const id = members[0]!.account.driver === "codex" ? key : first.id;
430 const usedPercent = members.reduce((sum, m) => sum + m.window.usedPercent, 0) / members.length;
431 // Pace compares spend against the clock, so it is judged only over the
432 // members that have a clock; a window with no reset would otherwise
433 // count as spend with no time elapsed and skew the verdict.
434 const timed = members.flatMap((m) => {
435 const share = elapsedShare(m.window, now);
436 return share === null ? [] : [{ used: m.window.usedPercent, elapsed: share }];
437 });
438 const timedUsed = timed.reduce((sum, t) => sum + t.used, 0) / timed.length;
439 const meanElapsed =
440 timed.length > 0 ? timed.reduce((sum, t) => sum + t.elapsed, 0) / timed.length : null;
441 const resets = members
442 .flatMap((member) => {
443 const at = resetMillis(member.window);
444 return at === null
445 ? []
446 : [
447 {
448 member,
449 at,
450 restoresPercent: Math.round(member.window.usedPercent / members.length),
451 },
452 ];
453 })
454 .sort((left, right) => left.at - right.at);
455 return {
456 id,
457 kind: first.kind,
458 label: first.label,
459 members,
460 columns: accounts.map(
461 (account) => memberByAccount.get(account.key) ?? { account, window: null },
462 ),
463 usedPercent: Math.round(usedPercent),
464 remainingPercent: Math.round(100 - usedPercent),
465 pace: meanElapsed === null ? null : paceOfShares(timedUsed, meanElapsed),
466 resets,
467 };
468 });
469 return pools.sort((left, right) => WINDOW_KIND_ORDER[left.kind] - WINDOW_KIND_ORDER[right.kind]);
471​
472export function limitsNotice(limits: ServerProviderUsageLimits): string | null {
473 if (limits.unavailable?.reason === "unsupported") {
474 return limits.unavailable.message ?? "This account has no subscription limits.";
475 }
476 if (limits.unavailable?.reason === "probeFailed") {
477 return limits.unavailable.message ?? "Could not read limits.";
478 }
479 return limits.windows.length === 0 ? "No limits reported." : null;
481​
482export function remainingPercent(window: ServerProviderUsageWindow): number {
483 return Math.round(100 - Math.max(0, Math.min(100, window.usedPercent)));
485​
486function resetMillis(window: ServerProviderUsageWindow): number | null {
487 if (window.resetsAt === undefined) return null;
488 const at = Date.parse(window.resetsAt);
489 return Number.isFinite(at) ? at : null;
491​
492export function elapsedShare(window: ServerProviderUsageWindow, now: number): number | null {
493 const resetsAt = resetMillis(window);
494 if (resetsAt === null || window.windowDurationMins === undefined) return null;
495 const length = window.windowDurationMins * MINUTE;
496 if (length <= 0) return null;
497 return Math.max(0, Math.min(1, (length - (resetsAt - now)) / length));
499​
500export type LimitPace = "ahead" | "on" | "under";
501​
502export function paceOf(window: ServerProviderUsageWindow, now: number): LimitPace | null {
503 const elapsed = elapsedShare(window, now);
504 return elapsed === null ? null : paceOfShares(window.usedPercent, elapsed);
506​
507function paceOfShares(usedPercent: number, elapsed: number): LimitPace {
508 const gap = usedPercent - elapsed * 100;
509 if (gap > 5) return "ahead";
510 if (gap < -5) return "under";
511 return "on";
513​
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`;
523​
524export function formatResetsIn(window: ServerProviderUsageWindow, now: number): string | null {
525 const resetsAt = resetMillis(window);
526 if (resetsAt === null) return null;
527 if (resetsAt <= now) return "resets now";
528 if (resetsAt - now < MINUTE) return "Resets momentarily";
529 return `resets in ${formatDuration(resetsAt - now)}`;
531​
532export const USAGE_LIMITS_COMMAND = {
533 name: "usage-limits",
534 description: "Show this provider's usage limits",
535} satisfies ServerProviderSlashCommand;
536​
537export function isUsageLimitsCommand(prompt: string): boolean {
538 return prompt.trim().toLowerCase() === "/usage-limits";
540​
541export function hasProviderUsageLimits(
542 driver: ServerProvider["driver"],
543 providers: readonly ServerProvider[],
544 sources: UsageLimitSourceSnapshots,
545): boolean {
546 return (
547 providersWithLimits(providers).some((provider) => provider.driver === driver) ||
548 sources.some(
549 (source) =>
550 source.accounts.some((account) => account.driver === driver) ||
551 (source.error !== undefined && source.accounts.length === 0),
552 )
553 );
555​
556export function sameUsageLimitCommandCoverage(
557 previous: UsageLimitSourceSnapshots,
558 next: UsageLimitSourceSnapshots,
559): boolean {
560 const coverage = (sources: UsageLimitSourceSnapshots) =>
561 new Set(
562 sources.flatMap((source) =>
563 source.error !== undefined && source.accounts.length === 0
564 ? ["*"]
565 : source.accounts.map((account) => String(account.driver)),
566 ),
567 );
568 const before = coverage(previous);
569 const after = coverage(next);
570 return before.size === after.size && [...before].every((driver) => after.has(driver));
572​
573/** Advertise on workspace catalogs too, which replace the global command list. */
574export function withUsageLimitsCommands(
575 providers: readonly ServerProvider[],
576 sources: UsageLimitSourceSnapshots,
577): ServerProvider[] {
578 return providers.map((provider) => {
579 if (!hasProviderUsageLimits(provider.driver, providers, sources)) return provider;
580 const commands = (items: readonly ServerProviderSlashCommand[]) => [
581 ...items.filter((command) => command.name !== USAGE_LIMITS_COMMAND.name),
582 USAGE_LIMITS_COMMAND,
583 ];
584 return {
585 ...provider,
586 slashCommands: commands(provider.slashCommands),
587 ...(provider.workspaceSnapshots
588 ? {
589 workspaceSnapshots: provider.workspaceSnapshots.map((snapshot) => ({
590 ...snapshot,
591 slashCommands: commands(snapshot.slashCommands),
592 })),
593 }
594 : {}),
595 };
596 });
598​
599export function collectProviderUsageLimits(
600 instanceId: ProviderInstanceId,
601 providers: readonly ServerProvider[],
602 sources: UsageLimitSourceSnapshots,
603 now: number,
604): UsageLimitsReport | null {
605 const selected = providers.find((provider) => provider.instanceId === instanceId);
606 if (!selected || !hasProviderUsageLimits(selected.driver, providers, sources)) return null;
607 const native = providersWithLimits(providers).filter(
608 (provider) => provider.driver === selected.driver,
609 );
610 const resolveKey = accountKeyResolver([
611 ...providers.filter((provider) => provider.enabled).map(nativeReport),
612 ...sources.flatMap((source) => source.accounts),
613 ]);
614 const nativeAccounts = new Set(
615 native.flatMap((provider) => {
616 const key = resolveKey(nativeReport(provider));
617 return key && provider.usageLimits?.windows.length && !provider.usageLimits.unavailable
618 ? [key]
619 : [];
620 }),
621 );
622 const accounts: Array<UsageLimitsReport["accounts"][number]> = [];
623 const notices: string[] = [];
624 for (const provider of native) {
625 if (!provider.usageLimits) continue;
626 const key = resolveKey(nativeReport(provider));
627 const hubCredits = sources
628 .flatMap((source) => source.accounts.map((account) => ({ source, account })))
629 .filter(
630 ({ account }) =>
631 key !== null &&
632 resolveKey(account) === key &&
633 account.usageLimits.resetCredits &&
634 !limitsNotice(account.usageLimits),
635 )
636 .sort(
637 (a, b) =>
638 Date.parse(b.account.usageLimits.checkedAt) - Date.parse(a.account.usageLimits.checkedAt),
639 )[0];
640 const hubCreditId = hubCredits?.account.usageLimits.resetCredits?.nextCreditId;
641 const showHubCredits =
642 hubCredits &&
643 (!provider.usageLimits.resetCredits ||
644 Date.parse(hubCredits.account.usageLimits.checkedAt) >
645 Date.parse(provider.usageLimits.checkedAt));
646 accounts.push({
647 id: provider.instanceId,
648 driver: provider.driver,
649 label: `${provider.displayName?.trim() || String(provider.driver)} [${provider.instanceId}]`,
650 ...(provider.auth.label ? { plan: provider.auth.label } : {}),
651 instanceId: provider.instanceId,
652 resetCreditInput:
653 hubCreditId && hubCredits
654 ? {
655 sourceId: hubCredits.source.id,
656 accountId: hubCredits.account.id,
657 creditId: hubCreditId,
658 }
659 : { instanceId: provider.instanceId },
660 ...(provider.displayName ? { displayName: provider.displayName } : {}),
661 ...(provider.accentColor ? { accentColor: provider.accentColor } : {}),
662 ...(provider.auth.email ? { email: provider.auth.email } : {}),
663 limits: showHubCredits
664 ? { ...provider.usageLimits, resetCredits: hubCredits.account.usageLimits.resetCredits }
665 : provider.usageLimits,
666 });
667 }
668 for (const source of sources) {
669 const matching = source.accounts.filter((account) => account.driver === selected.driver);
670 for (const account of matching) {
671 const key = resolveKey(account);
672 if (key && nativeAccounts.has(key)) continue;
673 accounts.push({
674 id: `${source.id}:${account.id}`,
675 driver: account.driver,
676 label: `${source.label} · ${account.id}`,
677 sourceLabel: "CLI Proxy",
678 ...(account.usageLimits.resetCredits?.nextCreditId
679 ? {
680 resetCreditInput: {
681 sourceId: source.id,
682 accountId: account.id,
683 creditId: account.usageLimits.resetCredits.nextCreditId,
684 },
685 }
686 : {}),
687 ...(account.plan ? { plan: account.plan } : {}),
688 ...(account.email ? { email: account.email } : {}),
689 limits: account.usageLimits,
690 });
691 }
692 if (source.error && (matching.length > 0 || source.accounts.length === 0)) {
693 notices.push(`${source.label}: ${source.error}`);
694 }
695 }
696 return { createdAt: DateTime.formatIso(DateTime.makeUnsafe(now)), accounts, notices };