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

usageLimits.ts

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