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

usageLimits.ts

1,007 lines37.4 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 ServerProviderResetCredits,
15 type ServerProviderUsageLimits,
16 type ServerProviderUsageWindow,
17 type UsageLimitSourceSnapshots,
18} from "@t3tools/contracts";
19​
20import * as DateTime from "effect/DateTime";
21​
22const MINUTE = 60_000;
23const HOUR = 60 * MINUTE;
24const DAY = 24 * HOUR;
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​
161function providersWithLimits(providers: readonly ServerProvider[]): readonly ServerProvider[] {
162 return providers.filter(
163 (provider) =>
164 provider.enabled &&
165 provider.installed &&
166 isProviderAvailable(provider) &&
167 provider.usageLimits !== undefined,
168 );
170​
171export type LimitPresentations = ReadonlyMap<
172 EnvironmentId,
173 {
174 readonly entry: { readonly target: { readonly label: string } };
175 readonly serverConfig: {
176 readonly providers: readonly ServerProvider[];
177 readonly usageLimitSources?: UsageLimitSourceSnapshots | undefined;
178 } | null;
179 }
180>;
181​
182export function collectExternalUsageLinks(presentations: LimitPresentations) {
183 const links = new Map<
184 string,
185 {
186 readonly label: string;
187 readonly url: string;
188 readonly message: string | undefined;
189 readonly accounts: readonly string[];
190 }
191 >();
192 for (const presentation of presentations.values()) {
193 for (const provider of providersWithLimits(presentation.serverConfig?.providers ?? [])) {
194 const external = provider.usageLimits?.externalUsage;
195 if (external && provider.auth.status === "authenticated") {
196 const account = `${provider.displayName ?? provider.instanceId} on ${presentation.entry.target.label}`;
197 links.set(external.url, {
198 ...external,
199 message: provider.usageLimits?.unavailable?.message,
200 accounts: [...new Set([...(links.get(external.url)?.accounts ?? []), account])],
201 });
202 }
203 }
204 }
205 return [...links.values()];
207​
208function accountKey(
209 driver: ServerProvider["driver"],
210 email: string | undefined,
211 limits?: ServerProviderUsageLimits,
212): string | null {
213 const normalizedEmail = email?.trim().toLowerCase();
214 if (normalizedEmail) return `${driver}:${normalizedEmail}`;
215 return limits?.credentialFingerprint
216 ? `${driver}:credential:${limits.credentialFingerprint}`
217 : null;
219​
220interface AccountReport {
221 readonly driver: ServerProvider["driver"];
222 readonly email?: string | undefined;
223 readonly workspaceId?: string | undefined;
224 readonly usageLimits?: ServerProviderUsageLimits | undefined;
226​
227const nativeReport = (provider: ServerProvider): AccountReport => ({
228 driver: provider.driver,
229 email: provider.auth.email,
230 workspaceId: provider.auth.workspaceId,
231 usageLimits: provider.usageLimits,
232});
233​
234// Include every enabled login, even unreadable workspaces.
235function accountKeyResolver(reports: Iterable<AccountReport>) {
236 const workspaces = new Map<string, Set<string>>();
237 for (const report of reports) {
238 const key = accountKey(report.driver, report.email, report.usageLimits);
239 if (key && report.workspaceId) {
240 workspaces.set(key, (workspaces.get(key) ?? new Set()).add(report.workspaceId));
241 }
242 }
243 return (report: AccountReport): string | null => {
244 const key = accountKey(report.driver, report.email, report.usageLimits);
245 if (!key) return null;
246 if (report.workspaceId) return `${key}:${report.workspaceId}`;
247 const known = workspaces.get(key);
248 if (!known) return key;
249 return known.size === 1 ? `${key}:${[...known][0]}` : null;
250 };
252​
253const hubAccountName = (account: { readonly id: string }) => account.id.replace(/\.json$/i, "");
254​
255export interface LimitAccount {
256 readonly key: string;
257 readonly driver: ServerProvider["driver"];
258 readonly displayName: string | null;
259 readonly email: string | undefined;
260 readonly plan: string | undefined;
261 readonly accentColor: string | undefined;
262 readonly environments: ReadonlyArray<{
263 readonly environmentId: EnvironmentId;
264 readonly label: string;
265 }>;
266 readonly sourceLabel: string | null;
267 readonly redeem: {
268 readonly environmentId: EnvironmentId;
269 readonly input: ProviderConsumeResetCreditInput;
270 } | null;
271 readonly limits: ServerProviderUsageLimits;
273​
274export function collectLimitAccounts(presentations: LimitPresentations): readonly LimitAccount[] {
275 const accounts = new Map<string, LimitAccount>();
276 const creditSources = new Map<string, LimitAccount>();
277 const hubRedeems = new Map<string, LimitAccount>();
278 const planSources = new Map<string, LimitAccount>();
279 const merge = (key: string, next: LimitAccount) => {
280 // Prefer hub redemption to clear its routing cooldown too; displayed balance still follows the freshest read.
281 const previousHub = hubRedeems.get(key);
282 if (
283 next.redeem &&
284 "sourceId" in next.redeem.input &&
285 (!previousHub || Date.parse(next.limits.checkedAt) > Date.parse(previousHub.limits.checkedAt))
286 ) {
287 hubRedeems.set(key, next);
288 }
289 const previousCredit = creditSources.get(key);
290 if (
291 next.limits.resetCredits &&
292 (!previousCredit ||
293 Date.parse(next.limits.checkedAt) > Date.parse(previousCredit.limits.checkedAt))
294 ) {
295 creditSources.set(key, next);
296 }
297 const previousPlan = planSources.get(key);
298 if (
299 next.plan &&
300 (!previousPlan ||
301 Date.parse(next.limits.checkedAt) > Date.parse(previousPlan.limits.checkedAt))
302 ) {
303 planSources.set(key, next);
304 }
305 const previous = accounts.get(key);
306 if (!previous) {
307 accounts.set(key, next);
308 return;
309 }
310 const fresher = Date.parse(next.limits.checkedAt) > Date.parse(previous.limits.checkedAt);
311 const environments = [
312 ...previous.environments,
313 ...next.environments.filter(
314 (candidate) =>
315 !previous.environments.some((seen) => seen.environmentId === candidate.environmentId),
316 ),
317 ];
318 const winner = fresher ? next : previous;
319 const creditSource = creditSources.get(key);
320 // A hub e-mail names the account better than the driver's default instance name.
321 const hubEmail = [previous, next].some(
322 (account) => account.environments.length === 0 && account.email,
323 );
324 const displayName = previous.displayName ?? next.displayName;
325 accounts.set(key, {
326 ...previous,
327 displayName:
328 hubEmail &&
329 displayName?.toLowerCase() === PROVIDER_DISPLAY_NAMES[previous.driver]?.toLowerCase()
330 ? null
331 : displayName,
332 plan: planSources.get(key)?.plan ?? previous.plan ?? next.plan,
333 accentColor: previous.accentColor ?? next.accentColor,
334 environments,
335 sourceLabel: environments.length > 0 ? null : (previous.sourceLabel ?? next.sourceLabel),
336 redeem:
337 hubRedeems.get(key)?.redeem ??
338 (creditSource ? creditSource.redeem : (winner.redeem ?? previous.redeem ?? next.redeem)),
339 limits: {
340 ...winner.limits,
341 ...(creditSource?.limits.resetCredits
342 ? { resetCredits: creditSource.limits.resetCredits }
343 : { resetCredits: undefined }),
344 },
345 });
346 };
347 const resolveKey = accountKeyResolver(
348 [...presentations.values()].flatMap((presentation) => [
349 ...(presentation.serverConfig?.providers ?? [])
350 .filter((provider) => provider.enabled)
351 .map(nativeReport),
352 ...(presentation.serverConfig?.usageLimitSources ?? []).flatMap((source) => source.accounts),
353 ]),
354 );
355 for (const [environmentId, presentation] of presentations) {
356 const label = presentation.entry.target.label;
357 for (const provider of providersWithLimits(presentation.serverConfig?.providers ?? [])) {
358 if (!provider.usageLimits || limitsNotice(provider.usageLimits) !== null) continue;
359 merge(resolveKey(nativeReport(provider)) ?? `${environmentId}:${provider.instanceId}`, {
360 key: `${environmentId}:${provider.instanceId}`,
361 driver: provider.driver,
362 displayName: provider.displayName?.trim() || null,
363 email: provider.auth.email,
364 plan: provider.auth.label,
365 accentColor: provider.accentColor,
366 environments: [{ environmentId, label }],
367 sourceLabel: null,
368 redeem: { environmentId, input: { instanceId: provider.instanceId } },
369 limits: provider.usageLimits,
370 });
371 }
372 }
373 const labelEnvironment = presentations.size > 1;
374 for (const [environmentId, presentation] of presentations) {
375 for (const source of presentation.serverConfig?.usageLimitSources ?? []) {
376 const sourceLabel = labelEnvironment
377 ? `${presentation.entry.target.label} · ${source.label}`
378 : source.label;
379 for (const account of source.accounts) {
380 if (limitsNotice(account.usageLimits) !== null) continue;
381 const key = `${source.id}:${account.id}${account.workspaceId ? `:${account.workspaceId}` : ""}`;
382 merge(resolveKey(account) ?? key, {
383 key,
384 driver: account.driver,
385 displayName: account.email ? null : hubAccountName(account),
386 email: account.email,
387 plan: account.plan,
388 accentColor: undefined,
389 environments: [],
390 sourceLabel,
391 redeem: account.usageLimits.resetCredits?.nextCreditId
392 ? {
393 environmentId,
394 input: {
395 sourceId: source.id,
396 accountId: account.id,
397 creditId: account.usageLimits.resetCredits.nextCreditId,
398 },
399 }
400 : null,
401 limits: account.usageLimits,
402 });
403 }
404 }
405 }
406 return [...accounts.values()];
408​
409export function collectLimitNotices(presentations: LimitPresentations): readonly string[] {
410 const label = (environmentLabel: string, subject: string) =>
411 presentations.size > 1 ? `${environmentLabel} · ${subject}` : subject;
412 const notices = new Set<string>();
413 for (const presentation of presentations.values()) {
414 const environmentLabel = presentation.entry.target.label;
415 for (const provider of providersWithLimits(presentation.serverConfig?.providers ?? [])) {
416 if (provider.usageLimits?.unavailable?.reason === "unsupported") continue;
417 const notice = provider.usageLimits ? limitsNotice(provider.usageLimits) : null;
418 const name = provider.displayName?.trim() || String(provider.driver);
419 if (notice) notices.add(`${label(environmentLabel, name)}: ${notice}`);
420 }
421 for (const source of presentation.serverConfig?.usageLimitSources ?? []) {
422 if (source.error) {
423 notices.add(`${label(environmentLabel, source.label)}: ${source.error}`);
424 } else if (source.accounts.length === 0) {
425 notices.add(`${label(environmentLabel, source.label)}: No accounts reported.`);
426 }
427 }
428 }
429 return [...notices];
431​
432export interface LimitPoolMember {
433 readonly account: LimitAccount;
434 readonly window: ServerProviderUsageWindow;
435 readonly refillPercent: number;
437​
438export interface LimitPoolWindow {
439 readonly id: string;
440 readonly kind: ServerProviderUsageWindow["kind"];
441 readonly label: string;
442 readonly members: readonly LimitPoolMember[];
443 readonly columns: ReadonlyArray<
444 LimitPoolMember | { readonly account: LimitAccount; readonly window: null }
445 >;
446 readonly remainingPercent: number;
447 readonly usedPercent: number;
448 readonly pace: LimitPace | null;
449 readonly resets: ReadonlyArray<{
450 readonly member: LimitPoolMember;
451 readonly at: number;
452 readonly restoresPercent: number;
453 }>;
455​
456export interface LimitPool {
457 readonly driver: ServerProvider["driver"];
458 readonly accounts: readonly LimitAccount[];
459 readonly windows: readonly LimitPoolWindow[];
461​
462function hasDuplicateCursorTotal(pool: LimitPool): boolean {
463 if (pool.windows.length !== 2) return false;
464 const total = pool.windows.find((window) => window.id === "totalPercentUsed");
465 const auto = pool.windows.find((window) => window.id === "autoPercentUsed");
466 return (
467 total !== undefined &&
468 auto !== undefined &&
469 total.members.length === auto.members.length &&
470 total.members.every(({ account, window }) =>
471 account.limits.windows.some(
472 (candidate) =>
473 candidate.id === auto.id &&
474 candidate.kind === auto.kind &&
475 candidate.usedPercent === window.usedPercent &&
476 candidate.resetsAt === window.resetsAt,
477 ),
478 )
479 );
481​
482export function displayLimitWindows(pool: LimitPool) {
483 if (pool.driver === "antigravity") {
484 return [...pool.windows].sort(
485 (left, right) =>
486 Number(!left.id.startsWith("gemini-")) - Number(!right.id.startsWith("gemini-")) ||
487 left.id
488 .replace(/-(5h|weekly|quota)$/, "")
489 .localeCompare(right.id.replace(/-(5h|weekly|quota)$/, "")) ||
490 WINDOW_KIND_ORDER[left.kind] - WINDOW_KIND_ORDER[right.kind],
491 );
492 }
493 if (pool.driver !== "cursor") return pool.windows;
494 const hasAuto = pool.windows.some((window) => window.id === "autoPercentUsed");
495 const hasApi = pool.windows.some((window) => window.id === "apiPercentUsed");
496 const hideTotal = (hasAuto && hasApi) || hasDuplicateCursorTotal(pool);
497 return pool.windows
498 .filter((window) => !hideTotal || window.id !== "totalPercentUsed")
499 .sort((left, right) => cursorUsageWindowRank(left.id) - cursorUsageWindowRank(right.id));
501​
502const WINDOW_KIND_ORDER: Record<ServerProviderUsageWindow["kind"], number> = {
503 session: 0,
504 weekly: 1,
505 monthly: 2,
506 other: 3,
507};
508​
509export function collectLimitPools(
510 accounts: readonly LimitAccount[],
511 now: number,
512): readonly LimitPool[] {
513 const byDriver = new Map<ServerProvider["driver"], LimitAccount[]>();
514 for (const account of accounts) {
515 const list = byDriver.get(account.driver);
516 if (list) list.push(account);
517 else byDriver.set(account.driver, [account]);
518 }
519 return [...byDriver].map(([driver, members]) => {
520 const orderWindow = members
521 .flatMap((account) => account.limits.windows)
522 .sort((left, right) => WINDOW_KIND_ORDER[left.kind] - WINDOW_KIND_ORDER[right.kind])[0];
523 const orderReset = (account: LimitAccount) => {
524 const window = account.limits.windows.find(
525 (window) => orderWindow && poolKey(driver, window) === poolKey(driver, orderWindow),
526 );
527 return (
528 (window ? resetMillis(poolMember(account, window, now).window) : null) ??
529 Number.POSITIVE_INFINITY
530 );
531 };
532 const sorted = [...members].sort(
533 (left, right) =>
534 orderReset(left) - orderReset(right) ||
535 accountSortName(left).localeCompare(accountSortName(right)) ||
536 left.key.localeCompare(right.key),
537 );
538 return { driver, accounts: sorted, windows: poolWindows(sorted, now) };
539 });
541​
542function accountSortName(account: LimitAccount): string {
543 return (account.displayName ?? account.email ?? account.key).toLowerCase();
545​
546const CODEX_PLAN_CAPACITY: Record<string, number> = {
547 "ChatGPT Plus Subscription": 1,
548 "ChatGPT Pro 100 Subscription": 5,
549 "ChatGPT Pro 200 Subscription": 20,
550};
551// Claude's published plan multipliers describe the session allowance only.
552const CLAUDE_SESSION_CAPACITY: Record<string, number> = { Pro: 1, Max: 5, Ultra: 20 };
553​
554function planCapacity(account: LimitAccount, kind: ServerProviderUsageWindow["kind"]) {
555 if (!account.plan) return undefined;
556 if (account.driver === "codex" && (kind === "session" || kind === "weekly")) {
557 return CODEX_PLAN_CAPACITY[account.plan];
558 }
559 if (account.driver === "claudeAgent" && kind === "session") {
560 return CLAUDE_SESSION_CAPACITY[account.plan];
561 }
562 return undefined;
564​
565// Codex ids name slots, so pool by kind; other drivers' ids identify distinct allowances.
566function poolKey(driver: ServerProvider["driver"], window: ServerProviderUsageWindow): string {
567 return driver === "codex" ? window.kind : `${window.kind}:${window.id}`;
569​
570function poolMember(account: LimitAccount, reported: ServerProviderUsageWindow, now: number) {
571 const spentWeekly =
572 reported.kind === "session"
573 ? account.limits.windows.find(
574 (window) =>
575 window.usedPercent >= 100 &&
576 (account.driver === "claudeAgent"
577 ? window.id === "seven_day"
578 : account.driver === "codex" && window.kind === "weekly"),
579 )
580 : undefined;
581 if (!spentWeekly) return { account, window: reported, refillPercent: reported.usedPercent };
582​
583 const weeklyReset = resetMillis(spentWeekly);
584 const sessionReset = resetMillis(reported);
585 const cutoff = Math.max(now, Date.parse(account.limits.checkedAt));
586 let resetsAt: string | undefined;
587 let refillPercent = 0;
588 // A stale or missing clock cannot tell us when blocked quota becomes usable.
589 if (
590 weeklyReset !== null &&
591 sessionReset !== null &&
592 weeklyReset > cutoff &&
593 sessionReset > cutoff
594 ) {
595 if (sessionReset <= weeklyReset) {
596 resetsAt = spentWeekly.resetsAt;
597 refillPercent = 100;
598 } else if (reported.usedPercent >= 100) {
599 resetsAt = reported.resetsAt;
600 refillPercent = 100;
601 } else {
602 resetsAt = spentWeekly.resetsAt;
603 refillPercent = 100 - Math.max(0, Math.min(100, reported.usedPercent));
604 }
605 }
606 return {
607 account,
608 // Suppression is not session spending, so it has no session pace clock.
609 window: { ...reported, usedPercent: 100, resetsAt, windowDurationMins: undefined },
610 refillPercent,
611 };
613​
614function poolWindows(accounts: readonly LimitAccount[], now: number): readonly LimitPoolWindow[] {
615 const byKey = new Map<string, LimitPoolMember[]>();
616 for (const account of accounts) {
617 for (const reported of account.limits.windows) {
618 const member = poolMember(account, reported, now);
619 const { window } = member;
620 const pooled = poolKey(account.driver, window);
621 const key = byKey.get(pooled)?.some((member) => member.account === account)
622 ? `${window.kind}:${window.id}`
623 : pooled;
624 const list = byKey.get(key);
625 if (list) list.push(member);
626 else byKey.set(key, [member]);
627 }
628 }
629 const pools = [...byKey].map(([key, members]): LimitPoolWindow => {
630 const memberByAccount = new Map(members.map((member) => [member.account.key, member]));
631 const first = members[0]!.window;
632 const id = members[0]!.account.driver === "codex" ? key : first.id;
633 // One unknown plan makes the pool incomparable by plan, so every member then counts once.
634 const capacities = members.map((m) => planCapacity(m.account, first.kind));
635 const weights = capacities.every((capacity) => capacity !== undefined)
636 ? capacities
637 : members.map(() => 1);
638 const weightOf = new Map(members.map((m, index) => [m, weights[index]!]));
639 const totalWeight = weights.reduce((sum, weight) => sum + weight, 0);
640 const usedPercent =
641 members.reduce((sum, m) => sum + m.window.usedPercent * weightOf.get(m)!, 0) / totalWeight;
642 // Judge pace only for windows with reset clocks; others add spend without elapsed time.
643 const timed = members.flatMap((m) => {
644 const share = elapsedShare(m.window, now);
645 return share === null
646 ? []
647 : [{ used: m.window.usedPercent, elapsed: share, weight: weightOf.get(m)! }];
648 });
649 const timedWeight = timed.reduce((sum, t) => sum + t.weight, 0);
650 const timedUsed = timed.reduce((sum, t) => sum + t.used * t.weight, 0) / timedWeight;
651 const meanElapsed =
652 timed.length > 0
653 ? timed.reduce((sum, t) => sum + t.elapsed * t.weight, 0) / timedWeight
654 : null;
655 const resets = members
656 .flatMap((member) => {
657 const at = resetMillis(member.window);
658 return at === null
659 ? []
660 : [
661 {
662 member,
663 at,
664 restoresPercent: Math.round(
665 (member.refillPercent * weightOf.get(member)!) / totalWeight,
666 ),
667 },
668 ];
669 })
670 .sort((left, right) => left.at - right.at);
671 return {
672 id,
673 kind: first.kind,
674 label: first.label,
675 members,
676 columns: accounts.map(
677 (account) => memberByAccount.get(account.key) ?? { account, window: null },
678 ),
679 usedPercent: Math.round(usedPercent),
680 remainingPercent: Math.round(100 - usedPercent),
681 pace: meanElapsed === null ? null : paceOfShares(timedUsed, meanElapsed),
682 resets,
683 };
684 });
685 return pools.sort((left, right) => WINDOW_KIND_ORDER[left.kind] - WINDOW_KIND_ORDER[right.kind]);
687​
688export function limitsNotice(limits: ServerProviderUsageLimits): string | null {
689 if (limits.unavailable?.reason === "unsupported") {
690 return limits.unavailable.message ?? "This account has no subscription limits.";
691 }
692 if (limits.unavailable?.reason === "probeFailed") {
693 return limits.unavailable.message ?? "Could not read limits.";
694 }
695 return limits.windows.length === 0 ? "No limits reported." : null;
697​
698export function remainingPercent(window: ServerProviderUsageWindow): number {
699 return Math.round(100 - Math.max(0, Math.min(100, window.usedPercent)));
701​
702function resetMillis(window: ServerProviderUsageWindow): number | null {
703 if (window.resetsAt === undefined) return null;
704 const at = Date.parse(window.resetsAt);
705 return Number.isFinite(at) ? at : null;
707​
708export function elapsedShare(window: ServerProviderUsageWindow, now: number): number | null {
709 const resetsAt = resetMillis(window);
710 if (resetsAt === null || window.windowDurationMins === undefined) return null;
711 const length = window.windowDurationMins * MINUTE;
712 if (length <= 0) return null;
713 return Math.max(0, Math.min(1, (length - (resetsAt - now)) / length));
715​
716// Bars show quota remaining, so even pace tracks time remaining.
717export function paceRemainingPercent(
718 window: ServerProviderUsageWindow,
719 now: number,
720): number | null {
721 const elapsed = elapsedShare(window, now);
722 return elapsed === null ? null : Math.round((1 - elapsed) * 100);
724​
725export type LimitPace = "ahead" | "on" | "under";
726​
727export function paceOf(window: ServerProviderUsageWindow, now: number): LimitPace | null {
728 const elapsed = elapsedShare(window, now);
729 return elapsed === null ? null : paceOfShares(window.usedPercent, elapsed);
731​
732function paceOfShares(usedPercent: number, elapsed: number): LimitPace {
733 const gap = usedPercent - elapsed * 100;
734 if (gap > 5) return "ahead";
735 if (gap < -5) return "under";
736 return "on";
738​
739export function formatDuration(ms: number): string {
740 const remaining = Math.max(0, ms);
741 const days = Math.floor(remaining / DAY);
742 const hours = Math.floor((remaining % DAY) / HOUR);
743 const minutes = Math.floor((remaining % HOUR) / MINUTE);
744 if (days > 0) return `${days}d ${hours}h`;
745 if (hours > 0) return `${hours}h ${minutes}m`;
746 return `${minutes}m`;
748​
749/** One redeemable reset as clients offer it; `input` already names the chosen credit. */
750export interface ResetCreditChoice {
751 readonly key: string;
752 readonly summary: string;
753 readonly actionLabel: string;
754 readonly confirmDescription: string;
755 readonly availableCount: number;
756 readonly input: ProviderConsumeResetCreditInput;
758​
759export function resetCreditChoices(
760 credits: ServerProviderResetCredits,
761 input: ProviderConsumeResetCreditInput,
762 now: number,
763 compact = false,
764): ReadonlyArray<ResetCreditChoice> {
765 const expiresIn = (at: string | undefined) => (at ? formatDuration(Date.parse(at) - now) : null);
766 if (credits.options && "instanceId" in input) {
767 return credits.options.map((option) => {
768 const expires = expiresIn(option.expiresAt);
769 return {
770 key: option.creditId,
771 summary: `${option.label} · ${option.availableCount} left${expires ? ` · expires in ${expires}` : ""}`,
772 actionLabel: "Use",
773 confirmDescription: `${option.label}: ${option.description} This cannot be undone.`,
774 availableCount: option.availableCount,
775 input: { ...input, creditId: option.creditId },
776 };
777 });
778 }
779 const count = credits.availableCount;
780 const expires = expiresIn(credits.nextExpiresAt);
781 return [
782 {
783 key: "next",
784 summary:
785 count === 0
786 ? "No reset credits banked"
787 : compact
788 ? `${count} banked${expires ? ` · expires in ${expires}` : ""}`
789 : `${count} ${count === 1 ? "reset credit" : "reset credits"} banked${expires ? ` · next expires in ${expires}` : ""}`,
790 actionLabel: "Use reset",
791 confirmDescription:
792 "This redeems one credit on your account and clears the current rate-limit windows. It cannot be undone.",
793 availableCount: count,
794 input,
795 },
796 ];
798​
799export function formatResetsIn(window: ServerProviderUsageWindow, now: number): string | null {
800 const resetsAt = resetMillis(window);
801 if (resetsAt === null) return null;
802 if (resetsAt <= now) return "resets now";
803 if (resetsAt - now < MINUTE) return "Resets momentarily";
804 return `resets in ${formatDuration(resetsAt - now)}`;
806​
807export const USAGE_LIMITS_COMMAND = {
808 name: "usage-limits",
809 description: "Show this provider's usage limits",
810} satisfies ServerProviderSlashCommand;
811​
812export function isUsageLimitsCommand(prompt: string): boolean {
813 return prompt.trim().toLowerCase() === "/usage-limits";
815​
816export function hasProviderUsageLimits(
817 driver: ServerProvider["driver"],
818 providers: readonly ServerProvider[],
819 sources: UsageLimitSourceSnapshots,
820): boolean {
821 return (
822 providersWithLimits(providers).some((provider) => provider.driver === driver) ||
823 sources.some(
824 (source) =>
825 source.accounts.some((account) => account.driver === driver) ||
826 (source.error !== undefined && source.accounts.length === 0),
827 )
828 );
830​
831export function sameUsageLimitCommandCoverage(
832 previous: UsageLimitSourceSnapshots,
833 next: UsageLimitSourceSnapshots,
834): boolean {
835 const coverage = (sources: UsageLimitSourceSnapshots) =>
836 new Set(
837 sources.flatMap((source) =>
838 source.error !== undefined && source.accounts.length === 0
839 ? ["*"]
840 : source.accounts.map((account) => String(account.driver)),
841 ),
842 );
843 const before = coverage(previous);
844 const after = coverage(next);
845 return before.size === after.size && [...before].every((driver) => after.has(driver));
847​
848/** Advertise on workspace catalogs too, which replace the global command list. */
849export function withUsageLimitsCommands(
850 providers: readonly ServerProvider[],
851 sources: UsageLimitSourceSnapshots,
852): ServerProvider[] {
853 const supportedDrivers = new Set([
854 ...providersWithLimits(providers).map((provider) => provider.driver),
855 ...sources.flatMap((source) => source.accounts.map((account) => account.driver)),
856 ]);
857 const unreadableSource = sources.some(
858 (source) => source.error !== undefined && source.accounts.length === 0,
859 );
860 return providers.map((provider) => {
861 if (!unreadableSource && !supportedDrivers.has(provider.driver)) return provider;
862 const commands = (items: readonly ServerProviderSlashCommand[]) => [
863 ...items.filter((command) => command.name !== USAGE_LIMITS_COMMAND.name),
864 USAGE_LIMITS_COMMAND,
865 ];
866 return {
867 ...provider,
868 slashCommands: commands(provider.slashCommands),
869 ...(provider.workspaceSnapshots
870 ? {
871 workspaceSnapshots: provider.workspaceSnapshots.map((snapshot) => ({
872 ...snapshot,
873 slashCommands: commands(snapshot.slashCommands),
874 })),
875 }
876 : {}),
877 };
878 });
880​
881export function collectProviderUsageLimits(
882 instanceId: ProviderInstanceId,
883 providers: readonly ServerProvider[],
884 sources: UsageLimitSourceSnapshots,
885 now: number,
886): UsageLimitsReport | null {
887 const selected = providers.find((provider) => provider.instanceId === instanceId);
888 if (!selected || !hasProviderUsageLimits(selected.driver, providers, sources)) return null;
889 const resolveKey = accountKeyResolver([
890 ...providers.filter((provider) => provider.enabled).map(nativeReport),
891 ...sources.flatMap((source) => source.accounts),
892 ]);
893 type NativeSnapshot = { provider: ServerProvider; limits: ServerProviderUsageLimits };
894 const nativeByAccount = new Map<
895 string,
896 { usage: NativeSnapshot; credits: NativeSnapshot | null }
897 >();
898 for (const provider of providersWithLimits(providers)) {
899 if (provider.driver !== selected.driver || !provider.usageLimits) continue;
900 const snapshot = { provider, limits: provider.usageLimits };
901 const key = resolveKey(nativeReport(provider)) ?? `instance:${provider.instanceId}`;
902 const previous = nativeByAccount.get(key);
903 const previousUsable = previous ? limitsNotice(previous.usage.limits) === null : false;
904 const usable = limitsNotice(snapshot.limits) === null;
905 const providerWins =
906 !previous ||
907 (usable && !previousUsable) ||
908 (usable === previousUsable &&
909 Date.parse(snapshot.limits.checkedAt) > Date.parse(previous.usage.limits.checkedAt));
910 const previousCredit = previous?.credits;
911 const credits =
912 snapshot.limits.resetCredits &&
913 (!previousCredit ||
914 Date.parse(snapshot.limits.checkedAt) > Date.parse(previousCredit.limits.checkedAt))
915 ? snapshot
916 : (previousCredit ?? null);
917 nativeByAccount.set(key, {
918 usage: providerWins ? snapshot : previous.usage,
919 credits,
920 });
921 }
922 const native = [...nativeByAccount.values()];
923 const nativeAccountKeys = new Set(
924 native.flatMap(({ usage: { provider, limits } }) => {
925 const key = resolveKey(nativeReport(provider));
926 return key && limits.windows.length && !limits.unavailable ? [key] : [];
927 }),
928 );
929 const accounts: Array<UsageLimitsReport["accounts"][number]> = [];
930 const notices: string[] = [];
931 for (const {
932 usage: { provider, limits },
933 credits,
934 } of native) {
935 const key = resolveKey(nativeReport(provider));
936 const hubCredits = sources
937 .flatMap((source) => source.accounts.map((account) => ({ source, account })))
938 .filter(
939 ({ account }) =>
940 key !== null &&
941 resolveKey(account) === key &&
942 account.usageLimits.resetCredits &&
943 !limitsNotice(account.usageLimits),
944 )
945 .sort(
946 (a, b) =>
947 Date.parse(b.account.usageLimits.checkedAt) - Date.parse(a.account.usageLimits.checkedAt),
948 )[0];
949 const hubCreditId = hubCredits?.account.usageLimits.resetCredits?.nextCreditId;
950 const showHubCredits =
951 hubCredits &&
952 (!credits ||
953 Date.parse(hubCredits.account.usageLimits.checkedAt) >
954 Date.parse(credits.limits.checkedAt));
955 const shownCredits = showHubCredits
956 ? hubCredits.account.usageLimits.resetCredits
957 : credits?.limits.resetCredits;
958 accounts.push({
959 id: provider.instanceId,
960 driver: provider.driver,
961 label: `${provider.displayName?.trim() || String(provider.driver)} [${provider.instanceId}]`,
962 ...(provider.auth.label ? { plan: provider.auth.label } : {}),
963 instanceId: provider.instanceId,
964 resetCreditInput:
965 hubCreditId && hubCredits
966 ? {
967 sourceId: hubCredits.source.id,
968 accountId: hubCredits.account.id,
969 creditId: hubCreditId,
970 }
971 : { instanceId: credits?.provider.instanceId ?? provider.instanceId },
972 ...(provider.displayName ? { displayName: provider.displayName } : {}),
973 ...(provider.accentColor ? { accentColor: provider.accentColor } : {}),
974 ...(provider.auth.email ? { email: provider.auth.email } : {}),
975 limits: shownCredits ? { ...limits, resetCredits: shownCredits } : limits,
976 });
977 }
978 for (const source of sources) {
979 const matching = source.accounts.filter((account) => account.driver === selected.driver);
980 for (const account of matching) {
981 const key = resolveKey(account);
982 if (key && nativeAccountKeys.has(key)) continue;
983 accounts.push({
984 id: `${source.id}:${account.id}`,
985 driver: account.driver,
986 label: `${source.label} · ${hubAccountName(account)}`,
987 sourceLabel: "CLI Proxy",
988 ...(account.usageLimits.resetCredits?.nextCreditId
989 ? {
990 resetCreditInput: {
991 sourceId: source.id,
992 accountId: account.id,
993 creditId: account.usageLimits.resetCredits.nextCreditId,
994 },
995 }
996 : {}),
997 ...(account.plan ? { plan: account.plan } : {}),
998 ...(account.email ? { email: account.email } : {}),
999 limits: account.usageLimits,
1000 });
1002 if (source.error && (matching.length > 0 || source.accounts.length === 0)) {
1003 notices.push(`${source.label}: ${source.error}`);
1006 return { createdAt: DateTime.formatIso(DateTime.makeUnsafe(now)), accounts, notices };