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

codexUsageLimits.ts

118 lines4.2 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 ServerProviderUsageLimits,
12 ServerProviderUsageWindow,
13} from "@t3tools/contracts";
14import * as DateTime from "effect/DateTime";
15import * as Option from "effect/Option";
16import type * as CodexErrors from "effect-codex-app-server/errors";
17​
18import { clampPercent, makeUsageLimits } from "../providerUsageLimits.ts";
19​
20interface CodexRateLimitWindow {
21 readonly usedPercent: number;
22 readonly resetsAt?: number | null;
23 readonly windowDurationMins?: number | null;
25​
26/** Structural view of the generated `RateLimitSnapshot`; both messages satisfy it. */
27export interface CodexRateLimitSnapshot {
28 readonly planType?: string | null;
29 readonly primary?: CodexRateLimitWindow | null;
30 readonly secondary?: CodexRateLimitWindow | null;
32​
33const SESSION_MINS = 5 * 60;
34const WEEK_MINS = 7 * 24 * 60;
35const MONTH_MINS = 30 * 24 * 60;
36​
37function isoFromEpochSeconds(value: number | null | undefined): string | undefined {
38 if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) return undefined;
39 const dt = DateTime.make(value * 1000);
40 return Option.isSome(dt) ? DateTime.formatIso(dt.value) : undefined;
42​
43function kindForDuration(mins: number): ServerProviderUsageWindow["kind"] {
44 if (mins >= MONTH_MINS) return "monthly";
45 if (mins >= WEEK_MINS) return "weekly";
46 return "session";
48​
49function labelForKind(kind: ServerProviderUsageWindow["kind"]): string {
50 return kind === "session" ? "Session" : kind === "weekly" ? "Weekly" : "Monthly";
52​
53/**
54 * `primary` / `secondary` are positions, not durations. Codex usually sends
55 * `windowDurationMins`; when it does not, paid plans expose the 5-hour and
56 * weekly pair and Free/Go expose one monthly allowance.
57 */
58export function codexRateLimitsToWindows(
59 snapshot: CodexRateLimitSnapshot,
60): ReadonlyArray<ServerProviderUsageWindow> {
61 const isMonthlyPlan = snapshot.planType === "free" || snapshot.planType === "go";
62 const positions = [
63 ["primary", snapshot.primary, isMonthlyPlan ? MONTH_MINS : SESSION_MINS],
64 ["secondary", snapshot.secondary, WEEK_MINS],
65 ] as const;
66 const windows: ServerProviderUsageWindow[] = [];
67 for (const [id, window, fallbackMins] of positions) {
68 if (!window || !Number.isFinite(window.usedPercent)) continue;
69 const windowDurationMins =
70 typeof window.windowDurationMins === "number" ? window.windowDurationMins : fallbackMins;
71 const kind = kindForDuration(windowDurationMins);
72 const resetsAt = isoFromEpochSeconds(window.resetsAt);
73 windows.push({
74 id,
75 kind,
76 label: labelForKind(kind),
77 usedPercent: clampPercent(window.usedPercent),
78 windowDurationMins,
79 ...(resetsAt ? { resetsAt } : {}),
80 });
81 }
82 return windows;
84​
85export function codexRateLimitsToLimits(input: {
86 readonly snapshot: CodexRateLimitSnapshot;
87 readonly checkedAt: string;
88}): ServerProviderUsageLimits {
89 return makeUsageLimits({
90 checkedAt: input.checkedAt,
91 windows: codexRateLimitsToWindows(input.snapshot),
92 });
94​
95export function codexRateLimitsToUpdate(
96 snapshot: CodexRateLimitSnapshot,
97): ProviderUsageLimitsUpdate | undefined {
98 const windows = codexRateLimitsToWindows(snapshot);
99 return windows.length > 0 ? { windows } : undefined;
101​
102/**
103 * A bounded, client-safe reason for a failed `account/rateLimits/read`. The
104 * raw error is for the log; only the category and, for a JSON-RPC failure,
105 * the code reach the Limits view.
106 */
107export function codexRateLimitsFailureMessage(error: CodexErrors.CodexAppServerError): string {
108 switch (error._tag) {
109 case "CodexAppServerRequestError":
110 return `Codex could not read usage (JSON-RPC ${error.code}).`;
111 case "CodexAppServerSpawnError":
112 return "Codex could not be started to read usage.";
113 case "CodexAppServerProcessExitedError":
114 return "Codex exited before it could report usage.";
115 default:
116 return "Codex did not answer the usage request.";
117 }