Open History to see the last commit
1import {
2 type EnvironmentId,
3 type ModelSelection,
4 type ServerSettings,
5 type ProjectId,
6 resolveProjectProviderInstanceEnabled,
7 type UsageLimitsReport,
8 type ProviderInstanceId,
9 type ProviderConsumeResetCreditInput,
10 type ServerProviderSlashCommand,
11 isProviderAvailable,
12 PROVIDER_DISPLAY_NAMES,
13 type ServerProvider,
14 type ServerProviderUsageLimits,
15 type ServerProviderUsageWindow,
16 type UsageLimitSourceAccount,
17 type UsageLimitSourceSnapshot,
18 type UsageLimitSourceSnapshots,
19} from "@t3tools/contracts";
20
21import * as DateTime from "effect/DateTime";
22
23import { isLocalLoopbackHost, isWildcardHost } from "./hostClassification.ts";
24
25const MINUTE = 60_000;
26
27export function exhaustedUsageWindow(
28 provider: ServerProvider | undefined,
29 now: number,
30 model?: string,
31) {
32 const windows = provider?.usageLimits?.windows ?? [];
33 const exhausted = windows.filter(
34 (window) =>
35 (window.usedPercent ?? 0) >= 100 &&
36 (model === undefined || window.modelIds === undefined || window.modelIds.includes(model)) &&
37 (model === undefined ||
38 window.providerIds === undefined ||
39 window.providerIds.includes(model.split("/")[0] ?? "")) &&
40 (!window.resetsAt ||
41 !Number.isFinite(Date.parse(window.resetsAt)) ||
42 Date.parse(window.resetsAt) > now),
43 );
44 if (model === undefined) return exhausted[0];
45 switch (provider?.driver) {
46 case "cursor": {
47 const api = exhausted.find((window) => window.id === "apiPercentUsed");
48 const auto = exhausted.find((window) => window.id === "autoPercentUsed");
49 return /^(auto|default|grok|composer)/.test(model) ? auto && api : api;
50 }
51 case "codex": {
52 // Seat-based plans spend credits only past their plan windows, so the credit cap blocks only plans without them.
53 const hasPlanWindows = windows.some(
54 (window) => window.id === "primary" || window.id === "secondary",
55 );
56 return exhausted.find((window) => window.id !== "individual" || !hasPlanWindows);
57 }
58 case "opencode":
59 return exhausted.find(
60 (window) => !window.id.startsWith("go_") || model.startsWith("opencode-go/"),
61 );
62 default:
63 return exhausted[0];
64 }
65}
66
67export function resolveNewThreadModelSelection(input: {
68 readonly defaultSelection: ModelSelection | null;
69 readonly explicitSelection?: ModelSelection | null;
70 readonly fallbackSelection: ModelSelection | null;
71 readonly providers: readonly ServerProvider[];
72 readonly now: number;
73 readonly settings?: ServerSettings;
74 readonly projectId?: ProjectId | null;
75}) {
76 const selection = input.explicitSelection ?? input.defaultSelection;
77 const unchanged = { selection, fallback: null };
78 if (input.explicitSelection || !selection || !input.fallbackSelection) return unchanged;
79 const provider = input.providers.find((entry) => entry.instanceId === selection.instanceId);
80 const window = exhaustedUsageWindow(provider, input.now, selection.model);
81 const fallback = input.providers.find(
82 (entry) => entry.instanceId === input.fallbackSelection?.instanceId,
83 );
84 if (
85 !provider ||
86 !window ||
87 !fallback?.enabled ||
88 !fallback.installed ||
89 fallback.auth.status === "unauthenticated" ||
90 !isProviderAvailable(fallback) ||
91 exhaustedUsageWindow(fallback, input.now, input.fallbackSelection.model) ||
92 (input.settings &&
93 !resolveProjectProviderInstanceEnabled(
94 input.settings,
95 input.projectId ?? null,
96 fallback.instanceId,
97 ))
98 )
99 return unchanged;
100 return {
101 selection: input.fallbackSelection,
102 fallback: { provider, resetsAt: window.resetsAt ?? null },
103 };
104}
105
106export const CHATGPT_USAGE_URL = "https://chatgpt.com/#settings/Usage";
107export const CHATGPT_USAGE_LIMIT_CODE = "subscription_sharing_usage_limit_exceeded";
108/** A ChatGPT Business admin caps plan use in other apps; only the admin can raise it. */
109export const CHATGPT_WORKSPACE_USAGE_LIMIT_CODE =
110 "subscription_sharing_workplace_individual_usage_limit_exceeded";
111/** OpenAI's partner guidelines fix this wording; the user sends it to their admin themselves. */
112export const CHATGPT_WORKSPACE_ADMIN_REQUEST =
113 "I've reached the limit for using my ChatGPT plan in T3 Code. Could you increase our workspace's usage limits so I can continue?\n\nGo to admin.openai.com → Workspace → Usage limits. Thank you!";
114
115export function usesChatGptSharing(provider: ServerProvider | null | undefined): boolean {
116 return provider?.auth.status === "authenticated" && provider.auth.subscriptionSharing === true;
117}
118
119export const CURSOR_USAGE_WINDOWS = [
120 {
121 id: "totalPercentUsed",
122 label: "Overall",
123 description: "All usage on your plan this billing cycle.",
124 },
125 {
126 id: "autoPercentUsed",
127 label: "Cursor Models",
128 description: "Grok, Composer, and Auto use this allowance.",
129 },
130 {
131 id: "apiPercentUsed",
132 label: "Other Models",
133 description: "Usage allowance for third-party models such as Claude, GPT, and Gemini.",
134 },
135] as const;
136
137export function cursorUsageWindowDetails(id: string, pool: LimitPool) {
138 const details = CURSOR_USAGE_WINDOWS.find((window) => window.id === id);
139 return details &&
140 ((pool.windows.length === 1 && id === "totalPercentUsed") || hasDuplicateCursorTotal(pool))
141 ? { ...details, label: null, description: undefined }
142 : details;
143}
144
145function cursorUsageWindowRank(id: string): number {
146 const rank = CURSOR_USAGE_WINDOWS.findIndex((window) => window.id === id);
147 return rank < 0 ? CURSOR_USAGE_WINDOWS.length : rank;
148}
149
150export function providersWithLimits(
151 providers: readonly ServerProvider[],
152): readonly ServerProvider[] {
153 return providers.filter(
154 (provider) =>
155 provider.enabled &&
156 provider.installed &&
157 isProviderAvailable(provider) &&
158 provider.usageLimits !== undefined,
159 );
160}
161
162export type LimitPresentations = ReadonlyMap<
163 EnvironmentId,
164 {
165 readonly entry: { readonly target: { readonly label: string } };
166 readonly serverConfig: {
167 readonly providers: readonly ServerProvider[];
168 readonly usageLimitSources?: UsageLimitSourceSnapshots | undefined;
169 } | null;
170 }
171>;
172
173export function collectExternalUsageLinks(
174 presentations: LimitPresentations,
175 accountLabel = (provider: string, environment: string) => `${provider} on ${environment}`,
176) {
177 const links = new Map<
178 string,
179 {
180 readonly label: string;
181 readonly url: string;
182 readonly message: string | undefined;
183 readonly accounts: readonly string[];
184 }
185 >();
186 for (const presentation of presentations.values()) {
187 for (const provider of providersWithLimits(presentation.serverConfig?.providers ?? [])) {
188 const external = provider.usageLimits?.externalUsage;
189 if (external && provider.auth.status === "authenticated") {
190 const account = accountLabel(
191 provider.displayName ?? provider.instanceId,
192 presentation.entry.target.label,
193 );
194 links.set(external.url, {
195 ...external,
196 message: provider.usageLimits?.unavailable?.message,
197 accounts: [...new Set([...(links.get(external.url)?.accounts ?? []), account])],
198 });
199 }
200 }
201 }
202 return [...links.values()];
203}
204
205function accountKey(
206 driver: ServerProvider["driver"],
207 email: string | undefined,
208 limits?: ServerProviderUsageLimits,
209): string | null {
210 const normalizedEmail = email?.trim().toLowerCase();
211 if (normalizedEmail) return `${driver}:${normalizedEmail}`;
212 return limits?.credentialFingerprint
213 ? `${driver}:credential:${limits.credentialFingerprint}`
214 : null;
215}
216
217interface AccountReport {
218 readonly driver: ServerProvider["driver"];
219 readonly email?: string | undefined;
220 readonly workspaceId?: string | undefined;
221 readonly usageLimits?: ServerProviderUsageLimits | undefined;
222}
223
224const nativeReport = (provider: ServerProvider): AccountReport => ({
225 driver: provider.driver,
226 email: provider.auth.email,
227 workspaceId: provider.auth.workspaceId,
228 usageLimits: provider.usageLimits,
229});
230
231// Include every enabled login, even unreadable workspaces.
232function accountKeyResolver(reports: Iterable<AccountReport>) {
233 const workspaces = new Map<string, Set<string>>();
234 for (const report of reports) {
235 const key = accountKey(report.driver, report.email, report.usageLimits);
236 if (key && report.workspaceId) {
237 workspaces.set(key, (workspaces.get(key) ?? new Set()).add(report.workspaceId));
238 }
239 }
240 return (report: AccountReport): string | null => {
241 const key = accountKey(report.driver, report.email, report.usageLimits);
242 if (!key) return null;
243 if (report.workspaceId) return `${key}:${report.workspaceId}`;
244 const known = workspaces.get(key);
245 if (!known) return key;
246 return known.size === 1 ? `${key}:${[...known][0]}` : null;
247 };
248}
249
250const hubAccountName = (account: { readonly id: string }) => account.id.replace(/\.json$/i, "");
251
252function limitAccountKeyResolver(presentations: LimitPresentations) {
253 return accountKeyResolver(
254 [...presentations.values()].flatMap((presentation) => [
255 ...(presentation.serverConfig?.providers ?? [])
256 .filter((provider) => provider.enabled)
257 .map(nativeReport),
258 ...(presentation.serverConfig?.usageLimitSources ?? []).flatMap((source) => source.accounts),
259 ]),
260 );
261}
262
263const nativeRowKey = (
264 resolveKey: ReturnType<typeof accountKeyResolver>,
265 environmentId: EnvironmentId,
266 provider: ServerProvider,
267) => resolveKey(nativeReport(provider)) ?? `${environmentId}:${provider.instanceId}`;
268
269const hubRowKey = (
270 resolveKey: ReturnType<typeof accountKeyResolver>,
271 environmentId: EnvironmentId,
272 source: UsageLimitSourceSnapshot,
273 account: UsageLimitSourceAccount,
274) =>
275 resolveKey(account) ??
276 `${hubIdentity(environmentId, source)}:${account.id}${account.workspaceId ? `:${account.workspaceId}` : ""}`;
277
278// Source ids are environment-local, so only a remote endpoint names the same hub across environments.
279function hubIdentity(environmentId: EnvironmentId, source: UsageLimitSourceSnapshot): string {
280 // The server supplies canonical endpoints; native URL polyfills can misparse IPv6 hosts.
281 const endpoint = source.endpoint;
282 const host = endpoint?.match(/^https?:\/\/(\[[\da-f:.]+\]|[^:/?#@]+)(?::\d+)?(?:\/|$)/)?.[1];
283 const local =
284 !host ||
285 isLocalLoopbackHost(host) ||
286 isWildcardHost(host) ||
287 // Each machine resolves these to itself too; shared host classification leaves them out.
288 /\.localhost\.*$|^\[::ffff:(?:127\.|7f[\da-f]{2}:)/i.test(host);
289 return endpoint && !local ? endpoint : `${environmentId}:${source.id}`;
290}
291
292export interface LimitAccount {
293 readonly key: string;
294 readonly driver: ServerProvider["driver"];
295 readonly displayName: string | null;
296 readonly email: string | undefined;
297 readonly plan: string | undefined;
298 readonly accentColor: string | undefined;
299 readonly environments: ReadonlyArray<{
300 readonly environmentId: EnvironmentId;
301 readonly label: string;
302 }>;
303 readonly sourceLabel: string | null;
304 readonly redeem: {
305 readonly environmentId: EnvironmentId;
306 readonly input: ProviderConsumeResetCreditInput;
307 } | null;
308 readonly limits: ServerProviderUsageLimits;
309}
310
311export function collectHttpQuotaSources(presentations: Parameters<typeof collectLimitAccounts>[0]) {
312 return [...presentations].flatMap(([environmentId, presentation]) =>
313 (presentation.serverConfig?.usageLimitSources ?? []).flatMap((source) =>
314 source.kind === "http" && source.quotaAccounts?.length
315 ? [
316 {
317 ...source,
318 key: `${environmentId}:${source.id}`,
319 label:
320 presentations.size > 1
321 ? `${presentation.entry.target.label} · ${source.label}`
322 : source.label,
323 },
324 ]
325 : [],
326 ),
327 );
328}
329
330export function collectLimitAccounts(presentations: LimitPresentations): readonly LimitAccount[] {
331 const accounts = new Map<string, LimitAccount>();
332 const creditSources = new Map<string, LimitAccount>();
333 const hubRedeems = new Map<string, LimitAccount>();
334 const planSources = new Map<string, LimitAccount>();
335 const merge = (key: string, next: LimitAccount) => {
336 // Prefer hub redemption to clear its routing cooldown too; displayed balance still follows the freshest read.
337 const previousHub = hubRedeems.get(key);
338 if (
339 next.redeem &&
340 "sourceId" in next.redeem.input &&
341 (!previousHub || Date.parse(next.limits.checkedAt) > Date.parse(previousHub.limits.checkedAt))
342 ) {
343 hubRedeems.set(key, next);
344 }
345 const previousCredit = creditSources.get(key);
346 if (
347 next.limits.resetCredits &&
348 (!previousCredit ||
349 Date.parse(next.limits.checkedAt) > Date.parse(previousCredit.limits.checkedAt))
350 ) {
351 creditSources.set(key, next);
352 }
353 const previousPlan = planSources.get(key);
354 if (
355 next.plan &&
356 (!previousPlan ||
357 Date.parse(next.limits.checkedAt) > Date.parse(previousPlan.limits.checkedAt))
358 ) {
359 planSources.set(key, next);
360 }
361 const previous = accounts.get(key);
362 if (!previous) {
363 accounts.set(key, next);
364 return;
365 }
366 const fresher = Date.parse(next.limits.checkedAt) > Date.parse(previous.limits.checkedAt);
367 const environments = [
368 ...previous.environments,
369 ...next.environments.filter(
370 (candidate) =>
371 !previous.environments.some((seen) => seen.environmentId === candidate.environmentId),
372 ),
373 ];
374 const winner = fresher ? next : previous;
375 const creditSource = creditSources.get(key);
376 // A hub e-mail names the account better than the driver's default instance name.
377 const hubEmail = [previous, next].some(
378 (account) => account.environments.length === 0 && account.email,
379 );
380 const displayName = previous.displayName ?? next.displayName;
381 accounts.set(key, {
382 ...previous,
383 displayName:
384 hubEmail &&
385 displayName?.toLowerCase() === PROVIDER_DISPLAY_NAMES[previous.driver]?.toLowerCase()
386 ? null
387 : displayName,
388 plan: planSources.get(key)?.plan ?? previous.plan ?? next.plan,
389 accentColor: previous.accentColor ?? next.accentColor,
390 environments,
391 sourceLabel: environments.length > 0 ? null : (previous.sourceLabel ?? next.sourceLabel),
392 redeem:
393 hubRedeems.get(key)?.redeem ??
394 (creditSource ? creditSource.redeem : (winner.redeem ?? previous.redeem ?? next.redeem)),
395 limits: {
396 ...winner.limits,
397 ...(creditSource?.limits.resetCredits
398 ? { resetCredits: creditSource.limits.resetCredits }
399 : { resetCredits: undefined }),
400 },
401 });
402 };
403 const resolveKey = limitAccountKeyResolver(presentations);
404 for (const [environmentId, presentation] of presentations) {
405 const label = presentation.entry.target.label;
406 for (const provider of providersWithLimits(presentation.serverConfig?.providers ?? [])) {
407 if (!provider.usageLimits || limitsNotice(provider.usageLimits) !== null) continue;
408 merge(nativeRowKey(resolveKey, environmentId, provider), {
409 key: `${environmentId}:${provider.instanceId}`,
410 driver: provider.driver,
411 displayName: provider.displayName?.trim() || null,
412 email: provider.auth.email,
413 plan: provider.auth.label,
414 accentColor: provider.accentColor,
415 environments: [{ environmentId, label }],
416 sourceLabel: null,
417 redeem: { environmentId, input: { instanceId: provider.instanceId } },
418 limits: provider.usageLimits,
419 });
420 }
421 }
422 const labelEnvironment = presentations.size > 1;
423 for (const [environmentId, presentation] of presentations) {
424 for (const source of presentation.serverConfig?.usageLimitSources ?? []) {
425 const sourceLabel = labelEnvironment
426 ? `${presentation.entry.target.label} · ${source.label}`
427 : source.label;
428 for (const account of source.accounts) {
429 if (limitsNotice(account.usageLimits) !== null) continue;
430 const resolved = resolveKey(account);
431 // A resolved account already has an identity; its public key must stay distinct from others'.
432 const hub = resolved ? `${environmentId}:${source.id}` : hubIdentity(environmentId, source);
433 const key = `${hub}:${account.id}${account.workspaceId ? `:${account.workspaceId}` : ""}`;
434 merge(hubRowKey(resolveKey, environmentId, source, account), {
435 key,
436 driver: account.driver,
437 displayName: account.email ? null : hubAccountName(account),
438 email: account.email,
439 plan: account.plan,
440 accentColor: undefined,
441 environments: [],
442 sourceLabel,
443 redeem: account.usageLimits.resetCredits?.nextCreditId
444 ? {
445 environmentId,
446 input: {
447 sourceId: source.id,
448 accountId: account.id,
449 creditId: account.usageLimits.resetCredits.nextCreditId,
450 },
451 }
452 : null,
453 limits: account.usageLimits,
454 });
455 }
456 }
457 }
458 return [...accounts.values()];
459}
460
461/** Hub accounts whose read failed and that no other report shows as a row, with their names. */
462export function unshownFailedHubAccounts(
463 presentations: LimitPresentations,
464): ReadonlyMap<UsageLimitSourceAccount, string> {
465 const resolveKey = limitAccountKeyResolver(presentations);
466 const shownRows = new Set<string>();
467 for (const [environmentId, presentation] of presentations) {
468 for (const provider of providersWithLimits(presentation.serverConfig?.providers ?? [])) {
469 if (provider.usageLimits && limitsNotice(provider.usageLimits) === null) {
470 shownRows.add(nativeRowKey(resolveKey, environmentId, provider));
471 }
472 }
473 for (const source of presentation.serverConfig?.usageLimitSources ?? []) {
474 for (const account of source.accounts) {
475 if (limitsNotice(account.usageLimits) === null) {
476 shownRows.add(hubRowKey(resolveKey, environmentId, source, account));
477 }
478 }
479 }
480 }
481 const failed = new Map<UsageLimitSourceAccount, string>();
482 for (const [environmentId, presentation] of presentations) {
483 for (const source of presentation.serverConfig?.usageLimitSources ?? []) {
484 for (const account of source.accounts) {
485 if (account.usageLimits.unavailable?.reason !== "probeFailed") continue;
486 if (shownRows.has(hubRowKey(resolveKey, environmentId, source, account))) continue;
487 failed.set(account, account.email ?? hubAccountName(account));
488 }
489 }
490 }
491 return failed;
492}
493
494export interface LimitPoolMember {
495 readonly account: LimitAccount;
496 readonly window: ServerProviderUsageWindow;
497 readonly refillPercent: number;
498}
499
500export interface LimitPoolWindow {
501 readonly id: string;
502 readonly kind: ServerProviderUsageWindow["kind"];
503 readonly label: string;
504 readonly members: readonly LimitPoolMember[];
505 readonly columns: ReadonlyArray<
506 LimitPoolMember | { readonly account: LimitAccount; readonly window: null }
507 >;
508 readonly remainingPercent: number;
509 readonly usedPercent: number;
510 readonly pace: LimitPace | null;
511 readonly paceRemainingPercent: number | null;
512 readonly resets: ReadonlyArray<{
513 readonly member: LimitPoolMember;
514 readonly at: number;
515 readonly restoresPercent: number;
516 }>;
517}
518
519export interface LimitPool {
520 readonly driver: ServerProvider["driver"];
521 readonly accounts: readonly LimitAccount[];
522 readonly windows: readonly LimitPoolWindow[];
523}
524
525function hasDuplicateCursorTotal(pool: LimitPool): boolean {
526 if (pool.windows.length !== 2) return false;
527 const total = pool.windows.find((window) => window.id === "totalPercentUsed");
528 const auto = pool.windows.find((window) => window.id === "autoPercentUsed");
529 return (
530 total !== undefined &&
531 auto !== undefined &&
532 total.members.length === auto.members.length &&
533 total.members.every(({ account, window }) =>
534 account.limits.windows.some(
535 (candidate) =>
536 candidate.id === auto.id &&
537 candidate.kind === auto.kind &&
538 candidate.usedPercent === window.usedPercent &&
539 candidate.resetsAt === window.resetsAt,
540 ),
541 )
542 );
543}
544
545export function displayLimitWindows(pool: LimitPool) {
546 if (pool.driver !== "cursor") return pool.windows;
547 const hasAuto = pool.windows.some((window) => window.id === "autoPercentUsed");
548 const hasApi = pool.windows.some((window) => window.id === "apiPercentUsed");
549 const hideTotal = (hasAuto && hasApi) || hasDuplicateCursorTotal(pool);
550 return pool.windows
551 .filter((window) => !hideTotal || window.id !== "totalPercentUsed")
552 .sort((left, right) => cursorUsageWindowRank(left.id) - cursorUsageWindowRank(right.id));
553}
554
555const WINDOW_KIND_ORDER: Record<ServerProviderUsageWindow["kind"], number> = {
556 session: 0,
557 weekly: 1,
558 monthly: 2,
559 other: 3,
560};
561
562export function collectLimitPools(
563 accounts: readonly LimitAccount[],
564 now: number,
565): readonly LimitPool[] {
566 const byDriver = new Map<ServerProvider["driver"], LimitAccount[]>();
567 for (const account of accounts) {
568 const list = byDriver.get(account.driver);
569 if (list) list.push(account);
570 else byDriver.set(account.driver, [account]);
571 }
572 return [...byDriver].map(([driver, members]) => {
573 const orderWindow = members
574 .flatMap((account) => account.limits.windows)
575 .sort((left, right) => WINDOW_KIND_ORDER[left.kind] - WINDOW_KIND_ORDER[right.kind])[0];
576 const orderReset = (account: LimitAccount) => {
577 const window = account.limits.windows.find(
578 (window) => orderWindow && poolKey(driver, window) === poolKey(driver, orderWindow),
579 );
580 return (
581 (window ? resetMillis(poolMember(account, window, now).window) : null) ??
582 Number.POSITIVE_INFINITY
583 );
584 };
585 const sorted = [...members].sort(
586 (left, right) =>
587 orderReset(left) - orderReset(right) ||
588 accountSortName(left).localeCompare(accountSortName(right)) ||
589 left.key.localeCompare(right.key),
590 );
591 return { driver, accounts: sorted, windows: poolWindows(sorted, now) };
592 });
593}
594
595function accountSortName(account: LimitAccount): string {
596 return (account.displayName ?? account.email ?? account.key).toLowerCase();
597}
598
599const CODEX_PLAN_CAPACITY: Record<string, number> = {
600 "ChatGPT Plus Subscription": 1,
601 "ChatGPT Pro 100 Subscription": 5,
602 "ChatGPT Pro 200 Subscription": 20,
603};
604// Claude's published plan multipliers describe the session allowance only.
605const CLAUDE_SESSION_CAPACITY: Record<string, number> = { Pro: 1, Max: 5, Ultra: 20 };
606
607function planCapacity(account: LimitAccount, kind: ServerProviderUsageWindow["kind"]) {
608 if (!account.plan) return undefined;
609 if (account.driver === "codex" && (kind === "session" || kind === "weekly")) {
610 return CODEX_PLAN_CAPACITY[account.plan];
611 }
612 if (account.driver === "claudeAgent" && kind === "session") {
613 return CLAUDE_SESSION_CAPACITY[account.plan];
614 }
615 return undefined;
616}
617
618// Codex ids name slots, so pool by kind; other drivers' ids identify distinct allowances.
619function poolKey(driver: ServerProvider["driver"], window: ServerProviderUsageWindow): string {
620 return driver === "codex" ? window.kind : `${window.kind}:${window.id}`;
621}
622
623function poolMember(account: LimitAccount, reported: ServerProviderUsageWindow, now: number) {
624 const spentWeekly =
625 reported.kind === "session"
626 ? account.limits.windows.find(
627 (window) =>
628 window.usedPercent >= 100 &&
629 (account.driver === "claudeAgent"
630 ? window.id === "seven_day"
631 : account.driver === "codex" && window.kind === "weekly"),
632 )
633 : undefined;
634 if (!spentWeekly) return { account, window: reported, refillPercent: reported.usedPercent };
635
636 const weeklyReset = resetMillis(spentWeekly);
637 const sessionReset = resetMillis(reported);
638 const cutoff = Math.max(now, Date.parse(account.limits.checkedAt));
639 let resetsAt: string | undefined;
640 let refillPercent = 0;
641 // A stale or missing clock cannot tell us when blocked quota becomes usable.
642 if (
643 weeklyReset !== null &&
644 sessionReset !== null &&
645 weeklyReset > cutoff &&
646 sessionReset > cutoff
647 ) {
648 if (sessionReset <= weeklyReset) {
649 resetsAt = spentWeekly.resetsAt;
650 refillPercent = 100;
651 } else if (reported.usedPercent >= 100) {
652 resetsAt = reported.resetsAt;
653 refillPercent = 100;
654 } else {
655 resetsAt = spentWeekly.resetsAt;
656 refillPercent = 100 - Math.max(0, Math.min(100, reported.usedPercent));
657 }
658 }
659 return {
660 account,
661 // Suppression is not session spending, so it has no session pace clock.
662 window: { ...reported, usedPercent: 100, resetsAt, windowDurationMins: undefined },
663 refillPercent,
664 };
665}
666
667/** Neumaier compensated summation. */
668function compensatedSum(values: readonly number[]): number {
669 let sum = 0;
670 let correction = 0;
671 for (const value of values) {
672 const next = sum + value;
673 correction += Math.abs(sum) >= Math.abs(value) ? sum - next + value : value - next + sum;
674 sum = next;
675 }
676 return sum + correction;
677}
678
679function poolWindows(accounts: readonly LimitAccount[], now: number): readonly LimitPoolWindow[] {
680 const byKey = new Map<string, LimitPoolMember[]>();
681 for (const account of accounts) {
682 for (const reported of account.limits.windows) {
683 const member = poolMember(account, reported, now);
684 const { window } = member;
685 const pooled = poolKey(account.driver, window);
686 const key = byKey.get(pooled)?.some((member) => member.account === account)
687 ? `${window.kind}:${window.id}`
688 : pooled;
689 const list = byKey.get(key);
690 if (list) list.push(member);
691 else byKey.set(key, [member]);
692 }
693 }
694 const pools = [...byKey].map(([key, members]): LimitPoolWindow => {
695 const memberByAccount = new Map(members.map((member) => [member.account.key, member]));
696 const first = members[0]!.window;
697 const id = members[0]!.account.driver === "codex" ? key : first.id;
698 // One unknown plan makes the pool incomparable by plan, so every member then counts once.
699 const capacities = members.map((m) => planCapacity(m.account, first.kind));
700 const weights = capacities.every((capacity) => capacity !== undefined)
701 ? capacities
702 : members.map(() => 1);
703 const weightOf = new Map(members.map((m, index) => [m, weights[index]!]));
704 const totalWeight = weights.reduce((sum, weight) => sum + weight, 0);
705 // Sum in value order so reset order cannot change the rounded result.
706 const usedPercent =
707 compensatedSum(
708 members.map((m) => m.window.usedPercent * weightOf.get(m)!).sort((a, b) => a - b),
709 ) / totalWeight;
710 // Judge pace only for windows with reset clocks; others add spend without elapsed time.
711 const timed = members.flatMap((m) => {
712 const share = elapsedShare(m.window, now);
713 return share === null
714 ? []
715 : [{ used: m.window.usedPercent, elapsed: share, weight: weightOf.get(m)! }];
716 });
717 const timedWeight = timed.reduce((sum, t) => sum + t.weight, 0);
718 const timedUsed = timed.reduce((sum, t) => sum + t.used * t.weight, 0) / timedWeight;
719 const meanElapsed =
720 timed.length > 0
721 ? timed.reduce((sum, t) => sum + t.elapsed * t.weight, 0) / timedWeight
722 : null;
723 const resets = members
724 .flatMap((member) => {
725 const at = resetMillis(member.window);
726 return at === null
727 ? []
728 : [
729 {
730 member,
731 at,
732 restoresPercent: Math.round(
733 (member.refillPercent * weightOf.get(member)!) / totalWeight,
734 ),
735 },
736 ];
737 })
738 .sort((left, right) => left.at - right.at);
739 return {
740 id,
741 kind: first.kind,
742 label: first.label,
743 members,
744 columns: accounts.map(
745 (account) => memberByAccount.get(account.key) ?? { account, window: null },
746 ),
747 usedPercent: Math.round(usedPercent),
748 remainingPercent: Math.round(100 - usedPercent),
749 pace: meanElapsed === null ? null : paceOfShares(timedUsed, meanElapsed),
750 paceRemainingPercent: meanElapsed === null ? null : Math.round((1 - meanElapsed) * 100),
751 resets,
752 };
753 });
754 return pools.sort((left, right) => WINDOW_KIND_ORDER[left.kind] - WINDOW_KIND_ORDER[right.kind]);
755}
756
757function limitsNotice(limits: ServerProviderUsageLimits): string | null {
758 if (limits.unavailable?.reason === "unsupported") {
759 return limits.unavailable.message ?? "This account has no subscription limits.";
760 }
761 if (limits.unavailable?.reason === "probeFailed") {
762 return limits.unavailable.message ?? "Could not read limits.";
763 }
764 return limits.windows.length === 0 ? "No limits reported." : null;
765}
766
767export function remainingPercent(window: ServerProviderUsageWindow): number {
768 return Math.round(100 - Math.max(0, Math.min(100, window.usedPercent)));
769}
770
771function resetMillis(window: ServerProviderUsageWindow): number | null {
772 if (window.resetsAt === undefined) return null;
773 const at = Date.parse(window.resetsAt);
774 return Number.isFinite(at) ? at : null;
775}
776
777export function elapsedShare(window: ServerProviderUsageWindow, now: number): number | null {
778 const resetsAt = resetMillis(window);
779 if (resetsAt === null || window.windowDurationMins === undefined) return null;
780 const length = window.windowDurationMins * MINUTE;
781 if (length <= 0) return null;
782 return Math.max(0, Math.min(1, (length - (resetsAt - now)) / length));
783}
784
785// Bars show quota remaining, so even pace tracks time remaining.
786export function paceRemainingPercent(
787 window: ServerProviderUsageWindow,
788 now: number,
789): number | null {
790 const elapsed = elapsedShare(window, now);
791 return elapsed === null ? null : Math.round((1 - elapsed) * 100);
792}
793
794export type LimitPace = "ahead" | "on" | "under";
795
796export function paceOf(window: ServerProviderUsageWindow, now: number): LimitPace | null {
797 const elapsed = elapsedShare(window, now);
798 return elapsed === null ? null : paceOfShares(window.usedPercent, elapsed);
799}
800
801function paceOfShares(usedPercent: number, elapsed: number): LimitPace {
802 const gap = usedPercent - elapsed * 100;
803 if (gap > 5) return "ahead";
804 if (gap < -5) return "under";
805 return "on";
806}
807
808/** One redeemable reset as clients offer it; `input` already names the chosen credit. */
809export interface ResetCreditChoice {
810 readonly key: string;
811 readonly summary: string;
812 readonly actionLabel: string;
813 readonly confirmDescription: string;
814 readonly availableCount: number;
815 readonly input: ProviderConsumeResetCreditInput;
816}
817
818export type ResetCountdown =
819 | { readonly kind: "now" }
820 | { readonly kind: "momentarily" }
821 | { readonly kind: "in"; readonly ms: number };
822
823export function resetCountdown(
824 window: ServerProviderUsageWindow,
825 now: number,
826): ResetCountdown | null {
827 const resetsAt = resetMillis(window);
828 if (resetsAt === null) return null;
829 if (resetsAt <= now) return { kind: "now" };
830 if (resetsAt - now < MINUTE) return { kind: "momentarily" };
831 return { kind: "in", ms: resetsAt - now };
832}
833
834export const USAGE_LIMITS_COMMAND = {
835 name: "usage-limits",
836 description: "Show this provider's usage limits",
837} satisfies ServerProviderSlashCommand;
838
839export function isUsageLimitsCommand(prompt: string): boolean {
840 return prompt.trim().toLowerCase() === "/usage-limits";
841}
842
843// A hub that could not be read may route any driver. An HTTP quota source never lists accounts
844// here, so its failure says nothing about which providers have limits.
845const unreadableHub = (source: UsageLimitSourceSnapshots[number]) =>
846 source.kind === "cliproxy" && source.error !== undefined && source.accounts.length === 0;
847
848export function hasProviderUsageLimits(
849 driver: ServerProvider["driver"],
850 providers: readonly ServerProvider[],
851 sources: UsageLimitSourceSnapshots,
852): boolean {
853 return (
854 providersWithLimits(providers).some((provider) => provider.driver === driver) ||
855 sources.some(
856 (source) =>
857 source.accounts.some((account) => account.driver === driver) || unreadableHub(source),
858 )
859 );
860}
861
862export function sameUsageLimitCommandCoverage(
863 previous: UsageLimitSourceSnapshots,
864 next: UsageLimitSourceSnapshots,
865): boolean {
866 const coverage = (sources: UsageLimitSourceSnapshots) =>
867 new Set(
868 sources.flatMap((source) =>
869 unreadableHub(source) ? ["*"] : source.accounts.map((account) => String(account.driver)),
870 ),
871 );
872 const before = coverage(previous);
873 const after = coverage(next);
874 return before.size === after.size && [...before].every((driver) => after.has(driver));
875}
876
877/** Advertise on workspace catalogs too, which replace the global command list. */
878export function withUsageLimitsCommands(
879 providers: readonly ServerProvider[],
880 sources: UsageLimitSourceSnapshots,
881): ServerProvider[] {
882 const supportedDrivers = new Set([
883 ...providersWithLimits(providers).map((provider) => provider.driver),
884 ...sources.flatMap((source) => source.accounts.map((account) => account.driver)),
885 ]);
886 const unreadableSource = sources.some(unreadableHub);
887 return providers.map((provider) => {
888 if (!unreadableSource && !supportedDrivers.has(provider.driver)) return provider;
889 const commands = (items: readonly ServerProviderSlashCommand[]) => [
890 ...items.filter((command) => command.name !== USAGE_LIMITS_COMMAND.name),
891 USAGE_LIMITS_COMMAND,
892 ];
893 return {
894 ...provider,
895 slashCommands: commands(provider.slashCommands),
896 ...(provider.workspaceSnapshots
897 ? {
898 workspaceSnapshots: provider.workspaceSnapshots.map((snapshot) => ({
899 ...snapshot,
900 slashCommands: commands(snapshot.slashCommands),
901 })),
902 }
903 : {}),
904 };
905 });
906}
907
908/** The hubs an instance sends its requests through: those whose address is its endpoint. */
909export function instanceHubs(
910 provider: ServerProvider,
911 sources: UsageLimitSourceSnapshots,
912): UsageLimitSourceSnapshots {
913 const endpoint = provider.auth.endpoint;
914 return endpoint === undefined ? [] : sources.filter((source) => source.origin === endpoint);
915}
916
917/** The hub accounts that serve a model: those that list it, else every account of the driver. */
918export function hubRoutes(
919 sources: UsageLimitSourceSnapshots,
920 driver: ServerProvider["driver"],
921 model: string | null,
922): (account: UsageLimitSourceAccount) => boolean {
923 // Claude Code's 1M-context suffix is not part of the model id a hub routes.
924 const full = model?.replace(/\[1m\]$/i, "");
925 // The hub routes a thinking suffix such as "gpt-5.2(high)" by its base model when one lists it.
926 const base = full?.replace(/\([^)]*\)$/, "");
927 const lists = (id: string | undefined) =>
928 sources.some((source) => source.accounts.some((account) => account.models?.includes(id ?? "")));
929 const slug = lists(base) ? base : full;
930 const listed = (account: UsageLimitSourceAccount) =>
931 slug !== undefined && account.models?.includes(slug) === true;
932 const serving = new Set(
933 sources.flatMap((source) => source.accounts.filter(listed).map((account) => account.driver)),
934 );
935 // Model ids such as "opus" are aliases no hub lists, so no listing falls back to the driver.
936 if (serving.size === 0)
937 return (account) => account.driver === driver && account.models?.length !== 0;
938 // An account whose model list was unreadable may serve the model too.
939 return (account) =>
940 account.models ? listed(account) : serving.has(account.driver) || account.driver === driver;
941}
942
943export function collectProviderUsageLimits(
944 instanceId: ProviderInstanceId,
945 providers: readonly ServerProvider[],
946 sources: UsageLimitSourceSnapshots,
947 now: number,
948 model: string | null = null,
949): UsageLimitsReport | null {
950 const selected = providers.find((provider) => provider.instanceId === instanceId);
951 if (!selected) return null;
952 // Only an instance sent to a hub is known to reach the accounts that hub routes its model to.
953 const hubs = instanceHubs(selected, sources);
954 const routes =
955 hubs.length > 0
956 ? hubRoutes(hubs, selected.driver, model)
957 : (account: UsageLimitSourceAccount) => account.driver === selected.driver;
958 const shownHubs = hubs.length > 0 ? hubs : sources;
959 const drivers = new Set(
960 shownHubs.flatMap((source) => source.accounts.filter(routes).map((account) => account.driver)),
961 );
962 if (drivers.size === 0) drivers.add(selected.driver);
963 if (![...drivers].some((driver) => hasProviderUsageLimits(driver, providers, sources))) {
964 return null;
965 }
966 const resolveKey = accountKeyResolver([
967 ...providers.filter((provider) => provider.enabled).map(nativeReport),
968 ...sources.flatMap((source) => source.accounts),
969 ]);
970 // Behind a hub, a local login counts only when it is one of the accounts the hub routes to.
971 const routedKeys =
972 hubs.length > 0
973 ? new Set(hubs.flatMap((source) => source.accounts.filter(routes).map(resolveKey)))
974 : null;
975 type NativeSnapshot = { provider: ServerProvider; limits: ServerProviderUsageLimits };
976 const nativeByAccount = new Map<
977 string,
978 { usage: NativeSnapshot; credits: NativeSnapshot | null }
979 >();
980 for (const provider of providersWithLimits(providers)) {
981 if (!drivers.has(provider.driver) || !provider.usageLimits) continue;
982 const accountKey = resolveKey(nativeReport(provider));
983 if (routedKeys && (accountKey === null || !routedKeys.has(accountKey))) continue;
984 const snapshot = { provider, limits: provider.usageLimits };
985 const key = accountKey ?? `instance:${provider.instanceId}`;
986 const previous = nativeByAccount.get(key);
987 const previousUsable = previous ? limitsNotice(previous.usage.limits) === null : false;
988 const usable = limitsNotice(snapshot.limits) === null;
989 const providerWins =
990 !previous ||
991 (usable && !previousUsable) ||
992 (usable === previousUsable &&
993 Date.parse(snapshot.limits.checkedAt) > Date.parse(previous.usage.limits.checkedAt));
994 const previousCredit = previous?.credits;
995 const credits =
996 snapshot.limits.resetCredits &&
997 (!previousCredit ||
998 Date.parse(snapshot.limits.checkedAt) > Date.parse(previousCredit.limits.checkedAt))
999 ? snapshot
1000 : (previousCredit ?? null);
1001 nativeByAccount.set(key, {
1002 usage: providerWins ? snapshot : previous.usage,
1003 credits,
1004 });
1005 }
1006 const native = [...nativeByAccount.values()];
1007 const nativeAccountKeys = new Set(
1008 native.flatMap(({ usage: { provider, limits } }) => {
1009 const key = resolveKey(nativeReport(provider));
1010 return key && limits.windows.length && !limits.unavailable ? [key] : [];
1011 }),
1012 );
1013 const accounts: Array<UsageLimitsReport["accounts"][number]> = [];
1014 const notices: string[] = [];
1015 for (const {
1016 usage: { provider, limits },
1017 credits,
1018 } of native) {
1019 const key = resolveKey(nativeReport(provider));
1020 // Only a hub this instance reaches may redeem a credit for its thread.
1021 const hubCredits = shownHubs
1022 .flatMap((source) => source.accounts.map((account) => ({ source, account })))
1023 .filter(
1024 ({ account }) =>
1025 key !== null &&
1026 resolveKey(account) === key &&
1027 account.usageLimits.resetCredits &&
1028 !limitsNotice(account.usageLimits),
1029 )
1030 .sort(
1031 (a, b) =>
1032 Date.parse(b.account.usageLimits.checkedAt) - Date.parse(a.account.usageLimits.checkedAt),
1033 )[0];
1034 const hubCreditId = hubCredits?.account.usageLimits.resetCredits?.nextCreditId;
1035 const showHubCredits =
1036 hubCredits &&
1037 (!credits ||
1038 Date.parse(hubCredits.account.usageLimits.checkedAt) >
1039 Date.parse(credits.limits.checkedAt));
1040 const shownCredits = showHubCredits
1041 ? hubCredits.account.usageLimits.resetCredits
1042 : credits?.limits.resetCredits;
1043 accounts.push({
1044 id: provider.instanceId,
1045 driver: provider.driver,
1046 label: `${provider.displayName?.trim() || String(provider.driver)} [${provider.instanceId}]`,
1047 ...(provider.auth.label ? { plan: provider.auth.label } : {}),
1048 instanceId: provider.instanceId,
1049 resetCreditInput:
1050 hubCreditId && hubCredits
1051 ? {
1052 sourceId: hubCredits.source.id,
1053 accountId: hubCredits.account.id,
1054 creditId: hubCreditId,
1055 }
1056 : { instanceId: credits?.provider.instanceId ?? provider.instanceId },
1057 ...(provider.displayName ? { displayName: provider.displayName } : {}),
1058 ...(provider.accentColor ? { accentColor: provider.accentColor } : {}),
1059 ...(provider.auth.email ? { email: provider.auth.email } : {}),
1060 limits: shownCredits ? { ...limits, resetCredits: shownCredits } : limits,
1061 });
1062 }
1063 for (const source of shownHubs) {
1064 const matching = source.accounts.filter(routes);
1065 for (const account of matching) {
1066 const key = resolveKey(account);
1067 if (key && nativeAccountKeys.has(key)) continue;
1068 accounts.push({
1069 id: `${source.id}:${account.id}`,
1070 driver: account.driver,
1071 label: `${source.label} · ${hubAccountName(account)}`,
1072 sourceLabel: "CLI Proxy",
1073 ...(account.usageLimits.resetCredits?.nextCreditId
1074 ? {
1075 resetCreditInput: {
1076 sourceId: source.id,
1077 accountId: account.id,
1078 creditId: account.usageLimits.resetCredits.nextCreditId,
1079 },
1080 }
1081 : {}),
1082 ...(account.plan ? { plan: account.plan } : {}),
1083 ...(account.email ? { email: account.email } : {}),
1084 limits: account.usageLimits,
1085 });
1086 }
1087 if (source.error && (matching.length > 0 || source.accounts.length === 0)) {
1088 notices.push(`${source.label}: ${source.error}`);
1089 }
1090 }
1091 return { createdAt: DateTime.formatIso(DateTime.makeUnsafe(now)), accounts, notices };
1092}