Open History to see the last commit
1import type {
2 ProviderConsumeResetCreditInput,
3 ServerProviderResetCredits,
4 ServerProviderUsageLimits,
5 ServerProviderUsageWindow,
6} from "@t3tools/contracts";
7import { mFallback, msg, plural, part, type Msg } from "gt-i18n";
8import type { M } from "gt-i18n";
9
10import {
11 collectExternalUsageLinks as collectExternalUsageLinksWith,
12 cursorUsageWindowDetails as cursorUsageWindowDetailsBase,
13 type LimitPool,
14 type LimitPresentations,
15 providersWithLimits,
16 type ResetCreditChoice,
17 resetCountdown,
18 unshownFailedHubAccounts,
19} from "./usageLimits.ts";
20
21const MINUTE = 60_000;
22const HOUR = 60 * MINUTE;
23const DAY = 24 * HOUR;
24
25const CURSOR_USAGE_WINDOW_COPY: Readonly<
26 Record<string, { readonly label: string | Msg; readonly description: string }>
27> = {
28 totalPercentUsed: {
29 label: msg({ context: "usage limit covering the whole plan" })`Overall`,
30 description: msg("All usage on your plan this billing cycle."),
31 },
32 autoPercentUsed: {
33 label: msg("Cursor Models"),
34 description: msg("Grok, Composer, and Auto use this allowance."),
35 },
36 apiPercentUsed: {
37 label: msg("Other Models"),
38 description: msg("Usage allowance for third-party models such as Claude, GPT, and Gemini."),
39 },
40};
41
42/** @public */
43export function cursorUsageWindowDetails(id: string, pool: LimitPool, resolve: M = mFallback) {
44 const details = cursorUsageWindowDetailsBase(id, pool);
45 const copy = CURSOR_USAGE_WINDOW_COPY[id];
46 if (!details || !copy) return details;
47 return {
48 ...details,
49 label: details.label === null ? null : resolve(copy.label),
50 description: details.description === undefined ? undefined : resolve(copy.description),
51 };
52}
53
54/** @public */
55export function collectExternalUsageLinks(
56 presentations: LimitPresentations,
57 resolve: M = mFallback,
58) {
59 return collectExternalUsageLinksWith(presentations, (provider, environment) =>
60 resolve(msg`${{ provider }} on ${{ environment }}`),
61 );
62}
63
64/** @public */
65export function limitsNotice(
66 limits: ServerProviderUsageLimits,
67 resolve: M = mFallback,
68): string | null {
69 if (limits.needsUsageAccess) {
70 return resolve(msg("Allow usage access to show this agent's limits."));
71 }
72 if (limits.unavailable?.reason === "unsupported") {
73 return limits.unavailable.message ?? resolve(msg("This account has no subscription limits."));
74 }
75 if (limits.unavailable?.reason === "probeFailed") {
76 return limits.unavailable.message ?? resolve(msg("Could not read limits."));
77 }
78 return limits.windows.length === 0 ? resolve(msg("No limits reported.")) : null;
79}
80
81/** @public */
82export function collectLimitNotices(
83 presentations: LimitPresentations,
84 resolve: M = mFallback,
85): readonly string[] {
86 const label = (environmentLabel: string, subject: string) =>
87 presentations.size > 1 ? `${environmentLabel} · ${subject}` : subject;
88 const notices = new Set<string>();
89 // A failed hub read needs no notice when another report already shows the account's row.
90 const failedAccounts = unshownFailedHubAccounts(presentations);
91 for (const presentation of presentations.values()) {
92 const environmentLabel = presentation.entry.target.label;
93 for (const provider of providersWithLimits(presentation.serverConfig?.providers ?? [])) {
94 const limits = provider.usageLimits;
95 // A bare unsupported means the account has no limits; an external usage link shows its message.
96 if (
97 limits?.unavailable?.reason === "unsupported" &&
98 (!limits.unavailable.message || limits.externalUsage)
99 ) {
100 continue;
101 }
102 const notice = limits ? limitsNotice(limits, resolve) : null;
103 const name = provider.displayName?.trim() || String(provider.driver);
104 if (notice) notices.add(`${label(environmentLabel, name)}: ${notice}`);
105 }
106 for (const source of presentation.serverConfig?.usageLimitSources ?? []) {
107 if (source.error) {
108 notices.add(`${label(environmentLabel, source.label)}: ${source.error}`);
109 } else if (source.accounts.length === 0 && source.unreadProviders?.length) {
110 notices.add(
111 resolve(
112 msg`${{ source: label(environmentLabel, source.label) }}: No Codex, Claude, or Grok accounts. Skipped ${{ providers: source.unreadProviders.join(", ") }}.`,
113 ),
114 );
115 } else if (
116 (source.kind === "http" ? (source.quotaAccounts?.length ?? 0) : source.accounts.length) ===
117 0
118 ) {
119 notices.add(
120 resolve(msg`${{ source: label(environmentLabel, source.label) }}: No accounts reported.`),
121 );
122 }
123 for (const account of source.accounts) {
124 const name = failedAccounts.get(account);
125 if (name === undefined) continue;
126 const notice = limitsNotice(account.usageLimits, resolve);
127 notices.add(`${label(environmentLabel, source.label)} · ${name}: ${notice}`);
128 }
129 }
130 }
131 return [...notices];
132}
133
134/** @public */
135export function formatDuration(ms: number, resolve: M = mFallback): string {
136 const remaining = Math.max(0, ms);
137 const days = Math.floor(remaining / DAY);
138 const hours = Math.floor((remaining % DAY) / HOUR);
139 const minutes = Math.floor((remaining % HOUR) / MINUTE);
140 if (days > 0) return resolve(msg`${{ days }}d ${{ hours }}h`);
141 if (hours > 0) return resolve(msg`${{ hours }}h ${{ minutes }}m`);
142 return resolve(msg`${{ minutes }}m`);
143}
144
145/** @public */
146export function resetCreditChoices(
147 credits: ServerProviderResetCredits,
148 input: ProviderConsumeResetCreditInput,
149 now: number,
150 compact = false,
151 resolve: M = mFallback,
152): ReadonlyArray<ResetCreditChoice> {
153 const expiresIn = (at: string | undefined) =>
154 at ? formatDuration(Date.parse(at) - now, resolve) : null;
155 if (credits.options && "instanceId" in input) {
156 return credits.options.map((option) => {
157 const expires = expiresIn(option.expiresAt);
158 const values = { label: option.label, count: option.availableCount };
159 return {
160 key: option.creditId,
161 summary: expires
162 ? resolve(
163 msg`${{ label: values.label }} · ${{ count: values.count }} left · expires in ${{ expires }}`,
164 )
165 : resolve(msg`${{ label: values.label }} · ${{ count: values.count }} left`),
166 actionLabel: resolve(msg({ context: "button that redeems a reset credit" })`Use`),
167 confirmDescription: resolve(
168 msg`${{ label: option.label }}: ${{ description: option.description }} This cannot be undone.`,
169 ),
170 availableCount: option.availableCount,
171 input: { ...input, creditId: option.creditId },
172 };
173 });
174 }
175 const count = credits.availableCount;
176 const expires = expiresIn(credits.nextExpiresAt);
177 return [
178 {
179 key: "next",
180 summary:
181 count === 0
182 ? resolve(msg("No reset credits banked"))
183 : compact
184 ? expires
185 ? resolve(msg`${{ count }} banked · expires in ${{ expires }}`)
186 : resolve(msg`${{ count }} banked`)
187 : expires
188 ? resolve(
189 msg`${plural(
190 { count },
191 {
192 one: part`${{ count }} reset credit banked · next expires in ${{ expires }}`,
193 other: part`${{ count }} reset credits banked · next expires in ${{ expires }}`,
194 },
195 )}`,
196 )
197 : resolve(
198 msg`${plural(
199 { count },
200 {
201 one: part`${{ count }} reset credit banked`,
202 other: part`${{ count }} reset credits banked`,
203 },
204 )}`,
205 ),
206 actionLabel: resolve(msg("Use reset")),
207 confirmDescription: resolve(
208 msg(
209 "This redeems one credit on your account and clears the current rate-limit windows. It cannot be undone.",
210 ),
211 ),
212 availableCount: count,
213 input,
214 },
215 ];
216}
217
218/**
219 * `full` reads "resets in 2h 5m", `in` reads "in 2h 5m", `refill` reads "↻ 2h 5m".
220 * @public
221 */
222export function formatResetsIn(
223 window: ServerProviderUsageWindow,
224 now: number,
225 resolve: M = mFallback,
226 style: "full" | "in" | "refill" = "full",
227): string | null {
228 const countdown = resetCountdown(window, now);
229 if (countdown === null) return null;
230 if (countdown.kind === "now") return resolve(msg("resets now"));
231 if (countdown.kind === "momentarily") return resolve(msg("Resets momentarily"));
232 const duration = formatDuration(countdown.ms, resolve);
233 if (style === "in") {
234 return resolve(msg({ context: "time until a usage window resets" })`in ${{ duration }}`);
235 }
236 if (style === "refill") return resolve(msg`↻ ${{ duration }}`);
237 return resolve(msg`resets in ${{ duration }}`);
238}