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

codexUsageLimits.ts

159 lines5.8 KB

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;
26​
27/** Structural view of the generated `RateLimitSnapshot`; both messages satisfy it. */
28export interface CodexRateLimitSnapshot {
29 readonly limitId?: string | null;
30 readonly planType?: string | null;
31 readonly primary?: CodexRateLimitWindow | null;
32 readonly secondary?: CodexRateLimitWindow | null;
34​
35/** Structural view of the read response's `rateLimitResetCredits`. */
36export interface CodexResetCreditsSummary {
37 readonly availableCount: number;
38 readonly credits?: ReadonlyArray<{
39 readonly status: string;
40 readonly expiresAt?: number | null;
41 }> | null;
43​
44const SESSION_MINS = 5 * 60;
45const WEEK_MINS = 7 * 24 * 60;
46const MONTH_MINS = 30 * 24 * 60;
47​
48function isoFromEpochSeconds(value: number | null | undefined): string | undefined {
49 if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) return undefined;
50 const dt = DateTime.make(value * 1000);
51 return Option.isSome(dt) ? DateTime.formatIso(dt.value) : undefined;
53​
54function kindForDuration(mins: number): ServerProviderUsageWindow["kind"] {
55 if (mins >= MONTH_MINS) return "monthly";
56 if (mins >= WEEK_MINS) return "weekly";
57 return "session";
59​
60function labelForKind(kind: ServerProviderUsageWindow["kind"]): string {
61 return kind === "session" ? "Session" : kind === "weekly" ? "Weekly" : "Monthly";
63​
64/**
65 * `primary` / `secondary` are positions, not durations. Codex usually sends
66 * `windowDurationMins`; when it does not, paid plans expose the 5-hour and
67 * weekly pair and Free/Go expose one monthly allowance.
68 */
69export function codexRateLimitsToWindows(
70 snapshot: CodexRateLimitSnapshot,
71): ReadonlyArray<ServerProviderUsageWindow> {
72 // Show the main allowance only. Model-specific notifications (such as Spark)
73 // must not replace its primary/secondary rows. Older CLIs omit the limit id.
74 if (snapshot.limitId && snapshot.limitId !== "codex") return [];
75 const isMonthlyPlan = snapshot.planType === "free" || snapshot.planType === "go";
76 const positions = [
77 ["primary", snapshot.primary, isMonthlyPlan ? MONTH_MINS : SESSION_MINS],
78 ["secondary", snapshot.secondary, WEEK_MINS],
79 ] as const;
80 const windows: ServerProviderUsageWindow[] = [];
81 for (const [id, window, fallbackMins] of positions) {
82 if (!window || !Number.isFinite(window.usedPercent)) continue;
83 const windowDurationMins =
84 typeof window.windowDurationMins === "number" ? window.windowDurationMins : fallbackMins;
85 const kind = kindForDuration(windowDurationMins);
86 const resetsAt = isoFromEpochSeconds(window.resetsAt);
87 windows.push({
88 id,
89 kind,
90 label: labelForKind(kind),
91 usedPercent: clampPercent(window.usedPercent),
92 windowDurationMins,
93 ...(resetsAt ? { resetsAt } : {}),
94 });
95 }
96 return windows;
98​
99export function codexResetCreditsToContract(
100 summary: CodexResetCreditsSummary | null | undefined,
101): ServerProviderResetCredits | undefined {
102 if (!summary) return undefined;
103 const expiries = (summary.credits ?? [])
104 .filter((credit) => credit.status === "available")
105 .map((credit) => credit.expiresAt)
106 .filter((value): value is number => typeof value === "number");
107 const nextExpiresAt =
108 expiries.length > 0 ? isoFromEpochSeconds(Math.min(...expiries)) : undefined;
109 return {
110 availableCount: Math.max(0, summary.availableCount),
111 ...(nextExpiresAt ? { nextExpiresAt } : {}),
112 };
114​
115export function codexRateLimitsToLimits(input: {
116 readonly snapshot: CodexRateLimitSnapshot;
117 readonly rateLimitsByLimitId?:
118 | Readonly<Record<string, CodexRateLimitSnapshot>>
119 | null
120 | undefined;
121 readonly resetCredits?: CodexResetCreditsSummary | null | undefined;
122 readonly checkedAt: string;
123}): ServerProviderUsageLimits {
124 const resetCredits = codexResetCreditsToContract(input.resetCredits);
125 // Select the main bucket explicitly; the legacy snapshot can name another limit.
126 const windows = codexRateLimitsToWindows(input.rateLimitsByLimitId?.codex ?? input.snapshot);
127 return {
128 ...makeUsageLimits({
129 checkedAt: input.checkedAt,
130 windows,
131 }),
132 ...(resetCredits ? { resetCredits } : {}),
133 };
135​
136export function codexRateLimitsToUpdate(
137 snapshot: CodexRateLimitSnapshot,
138): ProviderUsageLimitsUpdate | undefined {
139 const windows = codexRateLimitsToWindows(snapshot);
140 return windows.length > 0 ? { windows } : undefined;
142​
143/**
144 * A bounded, client-safe reason for a failed `account/rateLimits/read`. The
145 * raw error is for the log; only the category and, for a JSON-RPC failure,
146 * the code reach the Limits view.
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 }