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

codexUsageLimits.ts

243 lines9.3 KB

1import type {
2 ProviderUsageLimitsUpdate,
3 ServerProviderResetCredits,
4 ServerProviderUsageLimits,
5 ServerProviderUsageWindow,
6} from "@t3tools/contracts";
7import * as DateTime from "effect/DateTime";
8import * as Option from "effect/Option";
9import type * as CodexErrors from "effect-codex-app-server/errors";
10​
11import { clampPercent, makeUsageLimits } from "@t3tools/provider-core/server/usageLimits";
12​
13interface CodexRateLimitWindow {
14 readonly usedPercent: number;
15 readonly resetsAt?: number | null;
16 readonly windowDurationMins?: number | null;
18​
19export interface CodexRateLimitSnapshot {
20 readonly limitId?: string | null;
21 readonly planType?: string | null;
22 readonly rateLimitReachedType?: string | null;
23 readonly primary?: CodexRateLimitWindow | null;
24 readonly secondary?: CodexRateLimitWindow | null;
25 readonly individualLimit?: {
26 readonly remainingPercent: number;
27 readonly resetsAt: number;
28 } | null;
30​
31export interface CodexResetCreditsSummary {
32 readonly availableCount: number;
33 readonly credits?: ReadonlyArray<{
34 readonly status: string;
35 readonly expiresAt?: number | null;
36 }> | null;
38​
39const SESSION_MINS = 5 * 60;
40const WEEK_MINS = 7 * 24 * 60;
41const MONTH_MINS = 30 * 24 * 60;
42​
43function isoFromEpochSeconds(value: number | null | undefined): string | undefined {
44 if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) return undefined;
45 const dt = DateTime.make(value * 1000);
46 return Option.isSome(dt) ? DateTime.formatIso(dt.value) : undefined;
48​
49function kindForDuration(mins: number): ServerProviderUsageWindow["kind"] {
50 if (mins >= MONTH_MINS) return "monthly";
51 if (mins >= WEEK_MINS) return "weekly";
52 return "session";
54​
55function labelForKind(kind: ServerProviderUsageWindow["kind"]): string {
56 return kind === "session" ? "Session" : kind === "weekly" ? "Weekly" : "Monthly";
58​
59/**
60 * `primary` / `secondary` are positions, not durations. Codex usually sends
61 * `windowDurationMins`; when it does not, paid plans expose the 5-hour and
62 * weekly pair and Free/Go expose one monthly allowance.
63 */
64function codexRateLimitsToWindows(
65 snapshot: CodexRateLimitSnapshot,
66): ReadonlyArray<ServerProviderUsageWindow> {
67 // Show the main allowance only. Model-specific notifications (such as Spark)
68 // must not replace its primary/secondary rows. Older CLIs omit the limit id.
69 if (snapshot.limitId && snapshot.limitId !== "codex") return [];
70 const isMonthlyPlan = snapshot.planType === "free" || snapshot.planType === "go";
71 const positions = [
72 ["primary", snapshot.primary, isMonthlyPlan ? MONTH_MINS : SESSION_MINS],
73 ["secondary", snapshot.secondary, WEEK_MINS],
74 ] as const;
75 const windows: ServerProviderUsageWindow[] = [];
76 for (const [id, window, fallbackMins] of positions) {
77 if (!window || !Number.isFinite(window.usedPercent)) continue;
78 const windowDurationMins =
79 typeof window.windowDurationMins === "number" ? window.windowDurationMins : fallbackMins;
80 const kind = kindForDuration(windowDurationMins);
81 const resetsAt = isoFromEpochSeconds(window.resetsAt);
82 windows.push({
83 id,
84 kind,
85 label: labelForKind(kind),
86 usedPercent: clampPercent(window.usedPercent),
87 windowDurationMins,
88 ...(resetsAt ? { resetsAt } : {}),
89 });
90 }
91 const individualLimit = snapshot.individualLimit;
92 if (individualLimit && Number.isFinite(individualLimit.remainingPercent)) {
93 const resetsAt = isoFromEpochSeconds(individualLimit.resetsAt);
94 windows.push({
95 id: "individual",
96 kind: "monthly",
97 label: "Monthly credit limit",
98 usedPercent: clampPercent(100 - individualLimit.remainingPercent),
99 ...(resetsAt ? { resetsAt } : {}),
100 });
101 }
102 return windows;
104​
105export function codexResetCreditsToContract(
106 summary: CodexResetCreditsSummary | null | undefined,
107): ServerProviderResetCredits | undefined {
108 if (!summary) return undefined;
109 const expiries = (summary.credits ?? [])
110 .filter((credit) => credit.status === "available")
111 .map((credit) => credit.expiresAt)
112 .filter((value): value is number => typeof value === "number");
113 const nextExpiresAt =
114 expiries.length > 0 ? isoFromEpochSeconds(Math.min(...expiries)) : undefined;
115 return {
116 availableCount: Math.max(0, summary.availableCount),
117 ...(nextExpiresAt ? { nextExpiresAt } : {}),
118 };
120​
121export function codexRateLimitsToLimits(input: {
122 readonly snapshot: CodexRateLimitSnapshot;
123 readonly rateLimitsByLimitId?:
124 | Readonly<Record<string, CodexRateLimitSnapshot>>
125 | null
126 | undefined;
127 readonly resetCredits?: CodexResetCreditsSummary | null | undefined;
128 readonly checkedAt: string;
129}): ServerProviderUsageLimits {
130 const resetCredits = codexResetCreditsToContract(input.resetCredits);
131 const windows = codexRateLimitsToWindows(input.rateLimitsByLimitId?.codex ?? input.snapshot);
132 return {
133 ...makeUsageLimits({
134 checkedAt: input.checkedAt,
135 windows,
136 }),
137 ...(resetCredits ? { resetCredits } : {}),
138 };
140​
141export function codexRateLimitsToUpdate(
142 snapshot: CodexRateLimitSnapshot,
143): ProviderUsageLimitsUpdate | undefined {
144 const windows = codexRateLimitsToWindows(snapshot);
145 return windows.length > 0 ? { windows } : undefined;
147​
148export function codexRateLimitsFailureMessage(error: CodexErrors.CodexAppServerError): string {
149 switch (error._tag) {
150 case "CodexAppServerRequestError":
151 return `Codex could not read usage (JSON-RPC ${error.code}).`;
152 case "CodexAppServerSpawnError":
153 return "Codex could not be started to read usage.";
154 case "CodexAppServerProcessExitedError":
155 return "Codex exited before it could report usage.";
156 default:
157 return "Codex did not answer the usage request.";
158 }
160​
161/**
162 * Codex sends `account/rateLimits/updated` as a partial view of the snapshot: a
163 * field the update omits keeps the value observed earlier in the session, so a
164 * later notification that only names the limit it reached must not drop the
165 * windows an earlier one carried.
166 */
167export function mergeCodexRateLimits(
168 previous: CodexRateLimitSnapshot | undefined,
169 update: CodexRateLimitSnapshot,
170): CodexRateLimitSnapshot | undefined {
171 // Model-specific snapshots (such as Spark) describe a different allowance
172 // and must not overwrite the main one, the same rule the usage rows apply.
173 if (update.limitId && update.limitId !== "codex") return previous;
174 if (!previous) return update;
175 return {
176 ...previous,
177 ...(update.limitId !== undefined ? { limitId: update.limitId } : {}),
178 ...(update.planType !== undefined ? { planType: update.planType } : {}),
179 ...(update.rateLimitReachedType !== undefined
180 ? { rateLimitReachedType: update.rateLimitReachedType }
181 : {}),
182 ...(update.primary !== undefined ? { primary: update.primary } : {}),
183 ...(update.secondary !== undefined ? { secondary: update.secondary } : {}),
184 ...(update.individualLimit !== undefined ? { individualLimit: update.individualLimit } : {}),
185 };
187​
188function formatCodexUsageLimitWait(waitMs: number): string {
189 const totalMinutes = Math.ceil(waitMs / 60_000);
190 const days = Math.floor(totalMinutes / (24 * 60));
191 const hours = Math.floor((totalMinutes % (24 * 60)) / 60);
192 const minutes = totalMinutes % 60;
193 if (days > 0) return hours === 0 ? `${days}d` : `${days}d ${hours}h`;
194 if (hours === 0) return `${totalMinutes}m`;
195 return minutes === 0 ? `${hours}h` : `${hours}h ${minutes}m`;
197​
198function codexUsageLimitNextStep(rateLimitReachedType: string | null | undefined): string {
199 switch (rateLimitReachedType) {
200 case "workspace_owner_credits_depleted":
201 case "workspace_member_credits_depleted":
202 return " The workspace has no credits to continue sooner: ask your workspace owner to add credits, or send the message again once the limit resets.";
203 case "workspace_owner_usage_limit_reached":
204 case "workspace_member_usage_limit_reached":
205 return " The workspace spend limit is reached: ask your workspace owner to raise it, or send the message again once the limit resets.";
206 default:
207 return " Send the message again once the limit resets.";
208 }
210​
211export function codexUsageLimitMessage(
212 snapshot: CodexRateLimitSnapshot | undefined,
213 atIso: string,
214): string {
215 const atMs = Date.parse(atIso);
216 const windows = snapshot && Number.isFinite(atMs) ? codexRateLimitsToWindows(snapshot) : [];
217 let reset = "";
218 let latestResetMs = Number.NEGATIVE_INFINITY;
219 for (const window of windows) {
220 if (window.usedPercent < 100 || !window.resetsAt) continue;
221 const resetMs = Date.parse(window.resetsAt);
222 if (!Number.isFinite(resetMs) || resetMs <= atMs || resetMs <= latestResetMs) continue;
223 latestResetMs = resetMs;
224 reset = ` The ${window.kind} limit resets in ${formatCodexUsageLimitWait(resetMs - atMs)}.`;
225 }
226 return `Codex usage limit reached.${reset}${codexUsageLimitNextStep(snapshot?.rateLimitReachedType)}`;
228​
229/** All exhausted windows must reset before a continuation can run. */
230export function codexUsageLimitResetAt(
231 snapshot: CodexRateLimitSnapshot | undefined,
232): string | null {
233 if (!snapshot) return null;
234 const windows = codexRateLimitsToWindows(snapshot).filter((window) => window.usedPercent >= 100);
235 if (windows.length === 0 || windows.some((window) => !window.resetsAt)) return null;
236 return windows.reduce<string | null>(
237 (latest, window) =>
238 latest === null || Date.parse(window.resetsAt!) > Date.parse(latest)
239 ? window.resetsAt!
240 : latest,
241 null,
242 );