Open History to see the last commit
1/**
2 * Codex subscription usage. The `account/rateLimits/read` response and the
3 * `account/rateLimits/updated` notification carry the same snapshot shape, so
4 * one mapper serves the status probe and the turn-driven update; both emit
5 * windows with the same ids so they merge onto the same rows.
6 *
7 * @module provider/Layers/codexUsageLimits
8 */
9import type {
10 ProviderUsageLimitsUpdate,
11 ServerProviderResetCredits,
12 ServerProviderUsageLimits,
13 ServerProviderUsageWindow,
14} from "@t3tools/contracts";
15import * as DateTime from "effect/DateTime";
16import * as Option from "effect/Option";
17import type * as CodexErrors from "effect-codex-app-server/errors";
18
19import { clampPercent, makeUsageLimits } from "../providerUsageLimits.ts";
20
21interface CodexRateLimitWindow {
22 readonly usedPercent: number;
23 readonly resetsAt?: number | null;
24 readonly windowDurationMins?: number | null;
25}
26
27/** Structural view of the generated `RateLimitSnapshot`; both messages satisfy it. */
28export interface CodexRateLimitSnapshot {
29 readonly planType?: string | null;
30 readonly primary?: CodexRateLimitWindow | null;
31 readonly secondary?: CodexRateLimitWindow | null;
32}
33
34/** Structural view of the read response's `rateLimitResetCredits`. */
35export interface CodexResetCreditsSummary {
36 readonly availableCount: number;
37 readonly credits?: ReadonlyArray<{
38 readonly status: string;
39 readonly expiresAt?: number | null;
40 }> | null;
41}
42
43const SESSION_MINS = 5 * 60;
44const WEEK_MINS = 7 * 24 * 60;
45const MONTH_MINS = 30 * 24 * 60;
46
47function isoFromEpochSeconds(value: number | null | undefined): string | undefined {
48 if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) return undefined;
49 const dt = DateTime.make(value * 1000);
50 return Option.isSome(dt) ? DateTime.formatIso(dt.value) : undefined;
51}
52
53function kindForDuration(mins: number): ServerProviderUsageWindow["kind"] {
54 if (mins >= MONTH_MINS) return "monthly";
55 if (mins >= WEEK_MINS) return "weekly";
56 return "session";
57}
58
59function labelForKind(kind: ServerProviderUsageWindow["kind"]): string {
60 return kind === "session" ? "Session" : kind === "weekly" ? "Weekly" : "Monthly";
61}
62
63/**
64 * `primary` / `secondary` are positions, not durations. Codex usually sends
65 * `windowDurationMins`; when it does not, paid plans expose the 5-hour and
66 * weekly pair and Free/Go expose one monthly allowance.
67 */
68export function codexRateLimitsToWindows(
69 snapshot: CodexRateLimitSnapshot,
70): ReadonlyArray<ServerProviderUsageWindow> {
71 const isMonthlyPlan = snapshot.planType === "free" || snapshot.planType === "go";
72 const positions = [
73 ["primary", snapshot.primary, isMonthlyPlan ? MONTH_MINS : SESSION_MINS],
74 ["secondary", snapshot.secondary, WEEK_MINS],
75 ] as const;
76 const windows: ServerProviderUsageWindow[] = [];
77 for (const [id, window, fallbackMins] of positions) {
78 if (!window || !Number.isFinite(window.usedPercent)) continue;
79 const windowDurationMins =
80 typeof window.windowDurationMins === "number" ? window.windowDurationMins : fallbackMins;
81 const kind = kindForDuration(windowDurationMins);
82 const resetsAt = isoFromEpochSeconds(window.resetsAt);
83 windows.push({
84 id,
85 kind,
86 label: labelForKind(kind),
87 usedPercent: clampPercent(window.usedPercent),
88 windowDurationMins,
89 ...(resetsAt ? { resetsAt } : {}),
90 });
91 }
92 return windows;
93}
94
95export function codexResetCreditsToContract(
96 summary: CodexResetCreditsSummary | null | undefined,
97): ServerProviderResetCredits | undefined {
98 if (!summary) return undefined;
99 const expiries = (summary.credits ?? [])
100 .filter((credit) => credit.status === "available")
101 .map((credit) => credit.expiresAt)
102 .filter((value): value is number => typeof value === "number");
103 const nextExpiresAt =
104 expiries.length > 0 ? isoFromEpochSeconds(Math.min(...expiries)) : undefined;
105 return {
106 availableCount: Math.max(0, summary.availableCount),
107 ...(nextExpiresAt ? { nextExpiresAt } : {}),
108 };
109}
110
111export function codexRateLimitsToLimits(input: {
112 readonly snapshot: CodexRateLimitSnapshot;
113 readonly resetCredits?: CodexResetCreditsSummary | null | undefined;
114 readonly checkedAt: string;
115}): ServerProviderUsageLimits {
116 const resetCredits = codexResetCreditsToContract(input.resetCredits);
117 return {
118 ...makeUsageLimits({
119 checkedAt: input.checkedAt,
120 windows: codexRateLimitsToWindows(input.snapshot),
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
133/**
134 * A bounded, client-safe reason for a failed `account/rateLimits/read`. The
135 * raw error is for the log; only the category and, for a JSON-RPC failure,
136 * the code reach the Limits view.
137 */
138export function codexRateLimitsFailureMessage(error: CodexErrors.CodexAppServerError): string {
139 switch (error._tag) {
140 case "CodexAppServerRequestError":
141 return `Codex could not read usage (JSON-RPC ${error.code}).`;
142 case "CodexAppServerSpawnError":
143 return "Codex could not be started to read usage.";
144 case "CodexAppServerProcessExitedError":
145 return "Codex exited before it could report usage.";
146 default:
147 return "Codex did not answer the usage request.";
148 }
149}