@specode/pi-subscription-usage 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,131 @@
1
+ // Adapted from @narumitw/pi-usage@0.53.0 (MIT).
2
+ import {
3
+ readStoredCredential,
4
+ type ExtensionContext,
5
+ } from "@earendil-works/pi-coding-agent";
6
+ import { fingerprintResolvedAuth } from "./core.ts";
7
+ import {
8
+ normalizeCodexResetCreditsPayload,
9
+ parseCodexResetOutcome,
10
+ verifyCodexStoredOAuthCredential,
11
+ type CodexResetAvailability,
12
+ type CodexResetOption,
13
+ type CodexResetOutcome,
14
+ } from "./codex-reset-core.ts";
15
+ import {
16
+ adapterForProvider,
17
+ AUTH_FINGERPRINT_SALT,
18
+ fetchProviderJson,
19
+ resolveUsageAuth,
20
+ } from "./query.ts";
21
+ import type { ResolvedUsageAuth } from "./types.ts";
22
+
23
+ const RESET_CREDITS_URL =
24
+ "https://chatgpt.com/backend-api/wham/rate-limit-reset-credits";
25
+ const RESET_CONSUME_URL = `${RESET_CREDITS_URL}/consume`;
26
+
27
+ type StoredCredentialReader = (providerId: string) => unknown;
28
+
29
+ export async function resolveCodexResetAuth(
30
+ ctx: ExtensionContext,
31
+ salt: Uint8Array = AUTH_FINGERPRINT_SALT,
32
+ credentialReader: StoredCredentialReader = readStoredCredential,
33
+ ): Promise<ResolvedUsageAuth> {
34
+ const model = ctx.model;
35
+ if (model?.provider !== "openai-codex") {
36
+ throw new Error(
37
+ "Codex resets require the current model to use OpenAI Codex.",
38
+ );
39
+ }
40
+ const expectedModel = `${model.provider}/${model.id}`;
41
+ const adapter = adapterForProvider("openai-codex");
42
+ if (!adapter) throw new Error("OpenAI Codex usage support is unavailable.");
43
+ const auth = await resolveUsageAuth(ctx, adapter, salt);
44
+ if (`${ctx.model?.provider}/${ctx.model?.id}` !== expectedModel) {
45
+ throw new Error(
46
+ "The current model changed while resolving Codex reset authentication.",
47
+ );
48
+ }
49
+ if (!auth)
50
+ throw new Error("No runtime credential is configured for OpenAI Codex.");
51
+
52
+ const resolvedAccess =
53
+ bearerToken(headerValue(auth.headers, "Authorization")) ?? auth.apiKey;
54
+ if (!resolvedAccess)
55
+ throw new Error("OpenAI Codex OAuth credentials were incomplete.");
56
+ const accountId = verifyCodexStoredOAuthCredential(
57
+ resolvedAccess,
58
+ credentialReader("openai-codex"),
59
+ );
60
+ const authorization = `Bearer ${resolvedAccess}`;
61
+ const headers = {
62
+ Authorization: authorization,
63
+ "chatgpt-account-id": accountId,
64
+ };
65
+ return {
66
+ actualProviderId: "openai-codex",
67
+ apiKey: resolvedAccess,
68
+ headers,
69
+ fingerprint: fingerprintResolvedAuth({ headers }, salt),
70
+ secrets: [
71
+ ...new Set([...auth.secrets, resolvedAccess, authorization, accountId]),
72
+ ],
73
+ model: auth.model,
74
+ };
75
+ }
76
+
77
+ export async function listCodexResetCredits(
78
+ auth: ResolvedUsageAuth,
79
+ signal: AbortSignal,
80
+ timeoutMs: number,
81
+ ): Promise<CodexResetAvailability> {
82
+ return normalizeCodexResetCreditsPayload(
83
+ await fetchProviderJson(
84
+ RESET_CREDITS_URL,
85
+ auth,
86
+ signal,
87
+ timeoutMs,
88
+ "Codex reset endpoint",
89
+ ),
90
+ );
91
+ }
92
+
93
+ export async function consumeCodexResetCredit(
94
+ auth: ResolvedUsageAuth,
95
+ option: CodexResetOption,
96
+ redeemRequestId: string,
97
+ signal: AbortSignal,
98
+ timeoutMs: number,
99
+ ): Promise<CodexResetOutcome> {
100
+ if (!redeemRequestId)
101
+ throw new Error("Codex reset request ID must not be empty.");
102
+ return parseCodexResetOutcome(
103
+ await fetchProviderJson(
104
+ RESET_CONSUME_URL,
105
+ auth,
106
+ signal,
107
+ timeoutMs,
108
+ "Codex reset consume endpoint",
109
+ {
110
+ method: "POST",
111
+ body: {
112
+ redeem_request_id: redeemRequestId,
113
+ ...(option.creditId ? { credit_id: option.creditId } : {}),
114
+ },
115
+ },
116
+ ),
117
+ );
118
+ }
119
+
120
+ function bearerToken(authorization: string | undefined): string | undefined {
121
+ return /^Bearer\s+(.+)$/iu.exec(authorization ?? "")?.[1];
122
+ }
123
+
124
+ function headerValue(
125
+ headers: Record<string, string>,
126
+ name: string,
127
+ ): string | undefined {
128
+ return Object.entries(headers).find(
129
+ ([candidate]) => candidate.toLowerCase() === name.toLowerCase(),
130
+ )?.[1];
131
+ }
package/src/core.ts ADDED
@@ -0,0 +1,182 @@
1
+ // Adapted from @narumitw/pi-usage@0.53.0 (MIT).
2
+ import { createHmac } from "node:crypto";
3
+ import type { UsageReport } from "./types.ts";
4
+
5
+ export class UsageCache {
6
+ private readonly entries = new Map<
7
+ string,
8
+ { createdAt: number; report: UsageReport }
9
+ >();
10
+ private readonly ttlMs: number;
11
+ private readonly maxEntries: number;
12
+
13
+ constructor(ttlMs: number, maxEntries = 32) {
14
+ if (!Number.isFinite(ttlMs) || ttlMs <= 0) {
15
+ throw new Error("Cache TTL must be positive.");
16
+ }
17
+ if (!Number.isSafeInteger(maxEntries) || maxEntries < 1) {
18
+ throw new Error("Cache entry limit must be a positive integer.");
19
+ }
20
+ this.ttlMs = ttlMs;
21
+ this.maxEntries = maxEntries;
22
+ }
23
+
24
+ get(
25
+ providerId: string,
26
+ fingerprint: string,
27
+ now = Date.now(),
28
+ ): UsageReport | undefined {
29
+ this.sweepExpired(now);
30
+ return this.entries.get(cacheKey(providerId, fingerprint))?.report;
31
+ }
32
+
33
+ set(
34
+ providerId: string,
35
+ fingerprint: string,
36
+ report: UsageReport,
37
+ now = Date.now(),
38
+ ): void {
39
+ this.sweepExpired(now);
40
+ const key = cacheKey(providerId, fingerprint);
41
+ this.entries.delete(key);
42
+ while (this.entries.size >= this.maxEntries) {
43
+ const oldest = this.entries.keys().next().value;
44
+ if (oldest === undefined) break;
45
+ this.entries.delete(oldest);
46
+ }
47
+ this.entries.set(key, { createdAt: now, report });
48
+ }
49
+
50
+ clearProvider(providerId: string): void {
51
+ for (const key of this.entries.keys()) {
52
+ if (key.startsWith(`${providerId}:`)) this.entries.delete(key);
53
+ }
54
+ }
55
+
56
+ clear(): void {
57
+ this.entries.clear();
58
+ }
59
+
60
+ private sweepExpired(now: number): void {
61
+ for (const [key, entry] of this.entries) {
62
+ if (now - entry.createdAt >= this.ttlMs) this.entries.delete(key);
63
+ }
64
+ }
65
+ }
66
+
67
+ export function fingerprintResolvedAuth(
68
+ auth: { apiKey?: string; headers?: Record<string, string> },
69
+ salt: Uint8Array,
70
+ ): string {
71
+ const headers = Object.entries(auth.headers ?? {})
72
+ .map(([name, value]) => [name.toLowerCase(), value] as const)
73
+ .sort(([left], [right]) => left.localeCompare(right));
74
+ return createHmac("sha256", salt)
75
+ .update(JSON.stringify({ apiKey: auth.apiKey ?? "", headers }))
76
+ .digest("hex");
77
+ }
78
+
79
+ export async function awaitWithDeadline<T>(
80
+ operation: () => Promise<T>,
81
+ signal: AbortSignal,
82
+ timeoutMs: number,
83
+ description: string,
84
+ ): Promise<T> {
85
+ if (signal.aborted) throw abortError();
86
+ let timeout: ReturnType<typeof setTimeout> | undefined;
87
+ let abortListener: (() => void) | undefined;
88
+ try {
89
+ const result = Promise.resolve().then(() => {
90
+ if (signal.aborted) throw abortError();
91
+ return operation();
92
+ });
93
+ return await Promise.race([
94
+ result,
95
+ new Promise<never>((_resolve, reject) => {
96
+ timeout = setTimeout(() => {
97
+ reject(
98
+ Object.assign(
99
+ new Error(
100
+ `Timed out after ${Math.round(timeoutMs / 1_000)}s ${description}.`,
101
+ ),
102
+ { name: "TimeoutError" },
103
+ ),
104
+ );
105
+ }, timeoutMs);
106
+ abortListener = () => reject(abortError());
107
+ signal.addEventListener("abort", abortListener, { once: true });
108
+ }),
109
+ ]);
110
+ } finally {
111
+ if (timeout) clearTimeout(timeout);
112
+ if (abortListener) signal.removeEventListener("abort", abortListener);
113
+ }
114
+ }
115
+
116
+ export function sanitizeDisplayText(value: string, maxChars = 160): string {
117
+ const plain = value
118
+ .replace(/\x1b(?:\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1b\\)?)/gu, "")
119
+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/gu, "")
120
+ .replace(/[\t\r\n]+/gu, " ")
121
+ .replace(/\s+/gu, " ")
122
+ .trim();
123
+ return plain.length <= maxChars
124
+ ? plain
125
+ : `${plain.slice(0, Math.max(0, maxChars - 1))}…`;
126
+ }
127
+
128
+ export function redactUsageError(
129
+ value: string,
130
+ secrets: readonly string[] = [],
131
+ ): string {
132
+ let redacted = value;
133
+ for (const secret of [...new Set(secrets)]
134
+ .filter(Boolean)
135
+ .sort((a, b) => b.length - a.length)) {
136
+ redacted = redacted.replace(
137
+ new RegExp(escapeRegExp(secret), "gu"),
138
+ "<redacted>",
139
+ );
140
+ }
141
+ redacted = redacted
142
+ .replace(/Bearer\s+[A-Za-z0-9._~+/=-]+/giu, "Bearer <redacted>")
143
+ .replace(
144
+ /"(?:access_token|refresh_token|api_key)"\s*:\s*"[^"]+"/giu,
145
+ (match) => {
146
+ const separator = match.indexOf(":");
147
+ return `${match.slice(0, separator + 1)}"<redacted>"`;
148
+ },
149
+ );
150
+ return sanitizeDisplayText(redacted, 600);
151
+ }
152
+
153
+ export function errorMessage(error: unknown): string {
154
+ return sanitizeDisplayText(
155
+ error instanceof Error ? error.message : String(error),
156
+ 600,
157
+ );
158
+ }
159
+
160
+ export function abortError(): Error {
161
+ return Object.assign(new Error("Usage query aborted."), {
162
+ name: "AbortError",
163
+ });
164
+ }
165
+
166
+ export function isAbortError(error: unknown): boolean {
167
+ return error instanceof Error && error.name === "AbortError";
168
+ }
169
+
170
+ export function modelIdentity(
171
+ model: { provider: string; id: string } | undefined,
172
+ ): string | undefined {
173
+ return model ? `${model.provider}/${model.id}` : undefined;
174
+ }
175
+
176
+ function cacheKey(providerId: string, fingerprint: string): string {
177
+ return `${providerId}:${fingerprint}`;
178
+ }
179
+
180
+ function escapeRegExp(value: string): string {
181
+ return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
182
+ }
package/src/format.ts ADDED
@@ -0,0 +1,230 @@
1
+ // Formatting model adapted from @narumitw/pi-usage@0.53.0 (MIT).
2
+ import {
3
+ sortUsageBuckets,
4
+ usagePercentRemaining,
5
+ usageWindowLabel,
6
+ } from "./status.ts";
7
+ import type {
8
+ ProviderUsageState,
9
+ UsageBucket,
10
+ UsageMetric,
11
+ UsageReport,
12
+ } from "./types.ts";
13
+
14
+ export { formatUsageStatusline } from "./status.ts";
15
+
16
+ const BAR_SEGMENTS = 12;
17
+
18
+ interface PanelRow {
19
+ label: string;
20
+ detail: string;
21
+ }
22
+
23
+ interface PanelSection {
24
+ heading?: string;
25
+ rows: PanelRow[];
26
+ }
27
+
28
+ export function formatUsageReport(report: UsageReport): string {
29
+ const sections = bucketSections(report.buckets);
30
+ const accountRows: PanelRow[] = report.metrics.map((metric) => ({
31
+ label: metricLabel(metric),
32
+ detail: formatMetric(metric),
33
+ }));
34
+ for (const note of report.notes ?? []) accountRows.push(noteRow(note));
35
+ const allRows = [
36
+ ...sections.flatMap((section) => section.rows),
37
+ ...accountRows,
38
+ ];
39
+ const labelWidth = allRows.reduce(
40
+ (width, row) => Math.max(width, displayWidth(row.label)),
41
+ 0,
42
+ );
43
+ const grouped = sections.some((section) => Boolean(section.heading));
44
+ const lines = [report.providerName];
45
+ if (!grouped) {
46
+ const rows = [...sections.flatMap((section) => section.rows), ...accountRows];
47
+ lines.push(...formatPanelRows(rows, labelWidth, 2));
48
+ return lines.join("\n");
49
+ }
50
+ for (const section of sections) {
51
+ if (lines.length > 1) lines.push("");
52
+ if (section.heading) lines.push(` ${section.heading}:`);
53
+ lines.push(...formatPanelRows(section.rows, labelWidth, 4));
54
+ }
55
+ if (accountRows.length > 0) {
56
+ lines.push("", " Account:");
57
+ lines.push(...formatPanelRows(accountRows, labelWidth, 4));
58
+ }
59
+ return lines.join("\n");
60
+ }
61
+
62
+ export function formatProviderState(state: ProviderUsageState): string {
63
+ if (state.status === "ready") return formatUsageReport(state.report);
64
+ let status = "Query Failed";
65
+ if (state.status === "auth-unavailable") status = "Auth Unavailable";
66
+ else if (state.status === "unsupported") status = "Unsupported";
67
+ return `${state.providerName}\n ${status}: ${state.message}`;
68
+ }
69
+
70
+ function formatBucket(bucket: UsageBucket): string {
71
+ const remaining = usagePercentRemaining(bucket);
72
+ const reset = bucket.resetsAt
73
+ ? ` · resets ${formatReset(bucket.resetsAt)}`
74
+ : "";
75
+ if (remaining !== undefined) {
76
+ const filled = Math.round((remaining / 100) * BAR_SEGMENTS);
77
+ const bar = `${"█".repeat(filled)}${"░".repeat(BAR_SEGMENTS - filled)}`;
78
+ const percent = `${String(Math.round(remaining)).padStart(3)}%`;
79
+ if (
80
+ bucket.unit !== "percent" &&
81
+ bucket.limit !== undefined &&
82
+ bucket.limit !== 100 && // x/100 duplicates the percent exactly
83
+ bucket.remaining !== undefined
84
+ ) {
85
+ return `${bar} ${percent} left · ${formatNumber(bucket.remaining)}/${formatNumber(bucket.limit)}${reset}`;
86
+ }
87
+ return `${bar} ${percent} left${reset}`;
88
+ }
89
+ const indent = " ".repeat(BAR_SEGMENTS + 2);
90
+ if (bucket.remaining !== undefined) {
91
+ return `${indent}${formatValue(bucket.remaining, bucket.unit)} left${reset}`;
92
+ }
93
+ return `${indent}${formatValue(bucket.used ?? "n/a", bucket.unit)} used${reset}`;
94
+ }
95
+
96
+ function bucketSections(buckets: readonly UsageBucket[]): PanelSection[] {
97
+ if (!buckets.some((bucket) => bucket.groupId)) {
98
+ return [
99
+ {
100
+ rows: sortUsageBuckets(buckets).map((bucket) => ({
101
+ label: usageWindowLabel(bucket),
102
+ detail: formatBucket(bucket),
103
+ })),
104
+ },
105
+ ];
106
+ }
107
+ const groups = new Map<string, { heading: string; buckets: UsageBucket[] }>();
108
+ for (const bucket of buckets) {
109
+ const key = bucket.groupId ?? "other";
110
+ let group = groups.get(key);
111
+ if (!group) {
112
+ group = {
113
+ heading:
114
+ key === "codex"
115
+ ? "Shared Across Models"
116
+ : (bucket.groupLabel ?? bucket.groupId ?? "Other Quota"),
117
+ buckets: [],
118
+ };
119
+ groups.set(key, group);
120
+ }
121
+ group.buckets.push(bucket);
122
+ }
123
+ return [...groups.entries()]
124
+ .sort(([leftKey, left], [rightKey, right]) => {
125
+ if (leftKey === "codex") return -1;
126
+ if (rightKey === "codex") return 1;
127
+ return left.heading.localeCompare(right.heading);
128
+ })
129
+ .map(([, group]) => ({
130
+ heading: group.heading,
131
+ rows: sortUsageBuckets(group.buckets).map((bucket) => ({
132
+ label: usageWindowLabel(bucket),
133
+ detail: formatBucket(bucket),
134
+ })),
135
+ }));
136
+ }
137
+
138
+ function formatPanelRows(
139
+ rows: readonly PanelRow[],
140
+ labelWidth: number,
141
+ indent: number,
142
+ ): string[] {
143
+ const prefix = " ".repeat(indent);
144
+ return rows.map(
145
+ (row) => `${prefix}${padDisplayEnd(row.label, labelWidth)} ${row.detail}`,
146
+ );
147
+ }
148
+
149
+ function metricLabel(metric: UsageMetric): string {
150
+ if (metric.id === "reset-credits") return "Resets Left";
151
+ if (metric.id === "credits") return "Extra Credit";
152
+ if (metric.id === "included-used") return "Included Used";
153
+ if (metric.id === "included-limit") return "Included Total";
154
+ if (metric.id === "on-demand-used") return "On-Demand Used";
155
+ if (metric.id === "on-demand-cap") return "On-Demand Cap";
156
+ if (metric.id === "prepaid-balance") return "Prepaid Balance";
157
+ return metric.label;
158
+ }
159
+
160
+ function formatMetric(metric: UsageMetric): string {
161
+ if (metric.id === "reset-credits" && typeof metric.value === "number") {
162
+ return formatNumber(metric.value);
163
+ }
164
+ return formatValue(metric.value, metric.unit);
165
+ }
166
+
167
+ function noteRow(note: string): PanelRow {
168
+ if (note.startsWith("Plan: ")) {
169
+ return { label: "Plan", detail: note.slice("Plan: ".length) };
170
+ }
171
+ if (note === "On-demand billing: enabled") {
172
+ return { label: "On-Demand", detail: "on" };
173
+ }
174
+ if (note === "On-demand billing: disabled") {
175
+ return { label: "On-Demand", detail: "off" };
176
+ }
177
+ return { label: "Note", detail: note };
178
+ }
179
+
180
+ function formatValue(
181
+ value: number | string,
182
+ unit: UsageBucket["unit"] | undefined,
183
+ ): string {
184
+ if (unit === "usd" && typeof value === "number") return `$${value.toFixed(2)}`;
185
+ return typeof value === "number" ? formatNumber(value) : value;
186
+ }
187
+
188
+ function formatNumber(value: number): string {
189
+ return Number.isInteger(value) ? String(value) : value.toFixed(2);
190
+ }
191
+
192
+ function formatReset(epochSeconds: number): string {
193
+ const reset = new Date(epochSeconds * 1_000);
194
+ if (Number.isNaN(reset.getTime())) return "unknown";
195
+ const month = (reset.getMonth() + 1).toString().padStart(2, "0");
196
+ const day = reset.getDate().toString().padStart(2, "0");
197
+ const hour = reset.getHours().toString().padStart(2, "0");
198
+ const minute = reset.getMinutes().toString().padStart(2, "0");
199
+ return `${month}/${day} ${hour}:${minute}`;
200
+ }
201
+
202
+ // East Asian display width so CJK labels can be padded into a real grid.
203
+ function displayWidth(value: string): number {
204
+ let width = 0;
205
+ for (const char of value) {
206
+ width += isWideCodePoint(char.codePointAt(0) ?? 0) ? 2 : 1;
207
+ }
208
+ return width;
209
+ }
210
+
211
+ function isWideCodePoint(code: number): boolean {
212
+ return (
213
+ code >= 0x1100 &&
214
+ (code <= 0x115f ||
215
+ code === 0x2329 ||
216
+ code === 0x232a ||
217
+ (code >= 0x2e80 && code <= 0xa4cf && code !== 0x303f) ||
218
+ (code >= 0xac00 && code <= 0xd7a3) ||
219
+ (code >= 0xf900 && code <= 0xfaff) ||
220
+ (code >= 0xfe30 && code <= 0xfe6f) ||
221
+ (code >= 0xff00 && code <= 0xff60) ||
222
+ (code >= 0xffe0 && code <= 0xffe6) ||
223
+ (code >= 0x20000 && code <= 0x3fffd))
224
+ );
225
+ }
226
+
227
+ function padDisplayEnd(value: string, width: number): string {
228
+ const padding = width - displayWidth(value);
229
+ return padding > 0 ? value + " ".repeat(padding) : value;
230
+ }
@@ -0,0 +1,157 @@
1
+ // Adapted from @narumitw/pi-usage@0.53.0 (MIT).
2
+ import { sanitizeDisplayText } from "../core.ts";
3
+ import type { UsageBucket, UsageMetric, UsageReport } from "../types.ts";
4
+
5
+ export function normalizeCodexUsage(
6
+ payload: unknown,
7
+ capturedAt: number,
8
+ ): UsageReport {
9
+ const root = asObject(payload);
10
+ if (!root) throw new Error("Codex usage response was not an object.");
11
+ const buckets: UsageBucket[] = [];
12
+ normalizeRateLimitGroup(buckets, "codex", "Codex", root.rate_limit, false);
13
+ const additional = Array.isArray(root.additional_rate_limits)
14
+ ? root.additional_rate_limits
15
+ : [];
16
+ for (const item of additional) {
17
+ const value = asObject(item);
18
+ const id = asString(value?.metered_feature) ?? asString(value?.limit_name);
19
+ if (!value || !id) continue;
20
+ try {
21
+ normalizeRateLimitGroup(
22
+ buckets,
23
+ id,
24
+ asString(value.limit_name) ?? id,
25
+ value.rate_limit,
26
+ true,
27
+ );
28
+ } catch {
29
+ // Optional model-specific buckets must not hide primary usage.
30
+ }
31
+ }
32
+
33
+ const metrics: UsageMetric[] = [];
34
+ const credits = asObject(root.credits);
35
+ if (credits?.has_credits === true) {
36
+ if (credits.unlimited === true) {
37
+ metrics.push({ id: "credits", label: "Credits", value: "unlimited" });
38
+ } else {
39
+ const balance = asNumber(credits.balance);
40
+ metrics.push({
41
+ id: "credits",
42
+ label: "Credits",
43
+ value: balance ?? "available",
44
+ ...(balance === undefined ? {} : { unit: "count" as const }),
45
+ });
46
+ }
47
+ } else if (credits?.has_credits === false) {
48
+ metrics.push({ id: "credits", label: "Credits", value: "none" });
49
+ }
50
+ const resetCredits = asObject(root.rate_limit_reset_credits);
51
+ const resetCount = asNonnegativeInteger(resetCredits?.available_count);
52
+ if (resetCount !== undefined) {
53
+ metrics.push({
54
+ id: "reset-credits",
55
+ label: "Usage limit resets",
56
+ value: resetCount,
57
+ unit: "count",
58
+ });
59
+ }
60
+ if (buckets.length === 0 && metrics.length === 0) {
61
+ throw new Error("Codex usage endpoint returned no displayable usage data.");
62
+ }
63
+ const planType = asString(root.plan_type);
64
+ return {
65
+ providerId: "openai-codex",
66
+ providerName: "OpenAI Codex",
67
+ capturedAt,
68
+ source: "codex-pi-auth",
69
+ semantics: {
70
+ kind: "consumer-subscription",
71
+ label: "ChatGPT subscription limits",
72
+ },
73
+ buckets,
74
+ metrics,
75
+ ...(planType ? { notes: [`Plan: ${planType}`] } : {}),
76
+ };
77
+ }
78
+
79
+ function normalizeRateLimitGroup(
80
+ buckets: UsageBucket[],
81
+ groupId: string,
82
+ groupLabel: string,
83
+ raw: unknown,
84
+ optional: boolean,
85
+ ): void {
86
+ if (raw === undefined || raw === null) return;
87
+ const details = asObject(raw);
88
+ if (!details) {
89
+ if (optional) return;
90
+ throw new Error("Codex rate limit was not an object.");
91
+ }
92
+ addWindow(buckets, groupId, groupLabel, "primary", details.primary_window);
93
+ addWindow(buckets, groupId, groupLabel, "secondary", details.secondary_window);
94
+ }
95
+
96
+ function addWindow(
97
+ buckets: UsageBucket[],
98
+ groupId: string,
99
+ groupLabel: string,
100
+ position: "primary" | "secondary",
101
+ raw: unknown,
102
+ ): void {
103
+ if (raw === undefined || raw === null) return;
104
+ const value = asObject(raw);
105
+ if (!value) throw new Error("Codex rate-limit window was not an object.");
106
+ const used = asNumber(value.used_percent);
107
+ if (used === undefined) return;
108
+ const seconds = asNumber(value.limit_window_seconds);
109
+ const resetsAt = asNumber(value.reset_at);
110
+ buckets.push({
111
+ id: `${groupId}:${position}`,
112
+ label: position === "primary" ? "Primary limit" : "Secondary limit",
113
+ groupId,
114
+ groupLabel,
115
+ modelKeys: [groupId, groupLabel],
116
+ used,
117
+ remaining: 100 - clampPercent(used),
118
+ limit: 100,
119
+ unit: "percent",
120
+ ...(seconds !== undefined && seconds > 0
121
+ ? { windowMinutes: Math.ceil(seconds / 60) }
122
+ : {}),
123
+ ...(resetsAt === undefined ? {} : { resetsAt }),
124
+ });
125
+ }
126
+
127
+ function asObject(value: unknown): Record<string, unknown> | undefined {
128
+ return value && typeof value === "object" && !Array.isArray(value)
129
+ ? (value as Record<string, unknown>)
130
+ : undefined;
131
+ }
132
+
133
+ function asString(value: unknown): string | undefined {
134
+ return typeof value === "string"
135
+ ? sanitizeDisplayText(value, 160) || undefined
136
+ : undefined;
137
+ }
138
+
139
+ function asNumber(value: unknown): number | undefined {
140
+ if (typeof value === "number" && Number.isFinite(value)) return value;
141
+ if (typeof value === "string" && value.trim()) {
142
+ const parsed = Number(value);
143
+ return Number.isFinite(parsed) ? parsed : undefined;
144
+ }
145
+ return undefined;
146
+ }
147
+
148
+ function asNonnegativeInteger(value: unknown): number | undefined {
149
+ const parsed = asNumber(value);
150
+ return parsed !== undefined && Number.isSafeInteger(parsed) && parsed >= 0
151
+ ? parsed
152
+ : undefined;
153
+ }
154
+
155
+ function clampPercent(value: number): number {
156
+ return Math.min(100, Math.max(0, value));
157
+ }