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