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