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

usageLimitsCopy.ts

246 lines8.7 KB

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