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

usageLimits.ts

646 lines25.5 KB

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