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