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

usageLimits.ts

967 lines35.7 KB

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