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