@llblab/pi-codex-usage 0.11.0 → 0.12.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.
- package/AGENTS.md +7 -4
- package/BACKLOG.md +2 -1
- package/CHANGELOG.md +7 -0
- package/README.md +48 -3
- package/index.ts +8 -1807
- package/lib/extension.ts +25 -0
- package/lib/fast.ts +23 -0
- package/lib/query.ts +368 -0
- package/lib/status-format.ts +347 -0
- package/lib/status.ts +435 -0
- package/lib/telegram.ts +45 -0
- package/lib/usage-store.ts +229 -0
- package/lib/usage.ts +425 -0
- package/package.json +11 -6
package/index.ts
CHANGED
|
@@ -1,1807 +1,8 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
type ExtensionAPI,
|
|
10
|
-
type ExtensionContext,
|
|
11
|
-
getAgentDir,
|
|
12
|
-
} from "@earendil-works/pi-coding-agent";
|
|
13
|
-
|
|
14
|
-
const CODEX_PROVIDER_ID = "openai-codex";
|
|
15
|
-
const CODEX_USAGE_EXTENSION_ID = "@llblab/pi-codex-usage";
|
|
16
|
-
const CODEX_USAGE_URL = "https://chatgpt.com/backend-api/wham/usage";
|
|
17
|
-
const DEFAULT_TIMEOUT_MS = 15_000;
|
|
18
|
-
const SECOND_MS = 1000;
|
|
19
|
-
const MINUTE_MS = 60 * SECOND_MS;
|
|
20
|
-
const HOUR_MS = 60 * MINUTE_MS;
|
|
21
|
-
const HOUR_TENTH_MS = 6 * MINUTE_MS;
|
|
22
|
-
const DAY_MS = 24 * HOUR_MS;
|
|
23
|
-
const DAY_TENTH_MS = 144 * MINUTE_MS;
|
|
24
|
-
/** How often an instance re-reads the shared file to redraw fresh data. */
|
|
25
|
-
const MAX_TICK_MS = 30 * SECOND_MS;
|
|
26
|
-
const MIN_TICK_MS = SECOND_MS;
|
|
27
|
-
const TAKEOVER_JITTER_MS = 2 * SECOND_MS;
|
|
28
|
-
/** A report older than this is no longer shown as current. */
|
|
29
|
-
const STALE_REPORT_MAX_AGE_MS = HOUR_MS;
|
|
30
|
-
const PROVISIONAL_RETRY_MS = SECOND_MS;
|
|
31
|
-
const FULL_AVAILABILITY_CONFIRMATION_MS = 15 * SECOND_MS;
|
|
32
|
-
const LOADING_FRAME_MS = 30;
|
|
33
|
-
const REDRAW_BLINK_MS = 150;
|
|
34
|
-
const STATUS_KEY = "aa-codex-usage";
|
|
35
|
-
const MAX_ERROR_BODY_CHARS = 600;
|
|
36
|
-
const DEFAULT_STATUS_LABEL_TEXT = "codex";
|
|
37
|
-
const CODEX_USAGE_LIMIT_ID = "codex";
|
|
38
|
-
const DUAL_BAR_WIDTH = 10;
|
|
39
|
-
const TELEGRAM_STATUS_IMPORT_SPECIFIERS = [
|
|
40
|
-
"@llblab/pi-telegram/status",
|
|
41
|
-
new URL("../pi-telegram/api/status.ts", import.meta.url).href,
|
|
42
|
-
];
|
|
43
|
-
const DUAL_BAR_CHARS = [
|
|
44
|
-
"⠀",
|
|
45
|
-
"▘",
|
|
46
|
-
"▝",
|
|
47
|
-
"▀",
|
|
48
|
-
"▖",
|
|
49
|
-
"▌",
|
|
50
|
-
"▞",
|
|
51
|
-
"▛",
|
|
52
|
-
"▗",
|
|
53
|
-
"▚",
|
|
54
|
-
"▐",
|
|
55
|
-
"▜",
|
|
56
|
-
"▄",
|
|
57
|
-
"▙",
|
|
58
|
-
"▟",
|
|
59
|
-
"█",
|
|
60
|
-
];
|
|
61
|
-
|
|
62
|
-
type UsageSource = "pi-auth" | "codex-app-server";
|
|
63
|
-
type TimeoutHandle = ReturnType<typeof setTimeout> & { unref?: () => void };
|
|
64
|
-
type PiModel = NonNullable<ExtensionContext["model"]>;
|
|
65
|
-
export type CodexUsageModel = Pick<PiModel, "id" | "name" | "provider">;
|
|
66
|
-
type CodexUsageTelegramStatusModel = Pick<PiModel, "id" | "name" | "provider">;
|
|
67
|
-
type TelegramStatusLineProviderResult =
|
|
68
|
-
{ label: string; value: string } | undefined;
|
|
69
|
-
type TelegramStatusLineProvider = (ctx: {
|
|
70
|
-
activeModel?: CodexUsageTelegramStatusModel;
|
|
71
|
-
}) => TelegramStatusLineProviderResult;
|
|
72
|
-
type TelegramStatusLineModule = {
|
|
73
|
-
registerTelegramStatusLineProvider?: (
|
|
74
|
-
provider: TelegramStatusLineProvider,
|
|
75
|
-
options: { id: string },
|
|
76
|
-
) => () => void;
|
|
77
|
-
};
|
|
78
|
-
|
|
79
|
-
type QueryUsageOptions = {
|
|
80
|
-
timeoutMs: number;
|
|
81
|
-
};
|
|
82
|
-
|
|
83
|
-
type QueryUsageResult =
|
|
84
|
-
| { ok: true; report: CodexUsageReport }
|
|
85
|
-
| { ok: false; errors: UsageQueryError[] };
|
|
86
|
-
|
|
87
|
-
type CodexSharedState = SharedState<CodexUsageReport>;
|
|
88
|
-
|
|
89
|
-
export type UsageQueryError = {
|
|
90
|
-
source: UsageSource;
|
|
91
|
-
message: string;
|
|
92
|
-
cause?: unknown;
|
|
93
|
-
};
|
|
94
|
-
|
|
95
|
-
export type CodexUsageReport = {
|
|
96
|
-
snapshots: NormalizedRateLimitSnapshot[];
|
|
97
|
-
credits?: NormalizedCreditUsage;
|
|
98
|
-
};
|
|
99
|
-
|
|
100
|
-
export type NormalizedCreditUsage = {
|
|
101
|
-
remainingPercent: number;
|
|
102
|
-
resetAt?: number;
|
|
103
|
-
};
|
|
104
|
-
|
|
105
|
-
export type NormalizedRateLimitSnapshot = {
|
|
106
|
-
limitId: string;
|
|
107
|
-
primary?: NormalizedRateLimitWindow;
|
|
108
|
-
secondary?: NormalizedRateLimitWindow;
|
|
109
|
-
};
|
|
110
|
-
|
|
111
|
-
export type NormalizedRateLimitWindow = {
|
|
112
|
-
usedPercent: number;
|
|
113
|
-
resetAt?: number;
|
|
114
|
-
};
|
|
115
|
-
|
|
116
|
-
type RateLimitStatusPayload = {
|
|
117
|
-
rate_limit?: unknown;
|
|
118
|
-
additional_rate_limits?: unknown;
|
|
119
|
-
credits?: unknown;
|
|
120
|
-
spend_control?: unknown;
|
|
121
|
-
};
|
|
122
|
-
|
|
123
|
-
type BackendRateLimitDetails = {
|
|
124
|
-
primary_window?: unknown;
|
|
125
|
-
secondary_window?: unknown;
|
|
126
|
-
};
|
|
127
|
-
|
|
128
|
-
type BackendWindowSnapshot = {
|
|
129
|
-
used_percent?: unknown;
|
|
130
|
-
reset_at?: unknown;
|
|
131
|
-
resets_at?: unknown;
|
|
132
|
-
reset_time?: unknown;
|
|
133
|
-
end_time?: unknown;
|
|
134
|
-
ends_at?: unknown;
|
|
135
|
-
expires_at?: unknown;
|
|
136
|
-
reset_after_seconds?: unknown;
|
|
137
|
-
};
|
|
138
|
-
|
|
139
|
-
type AppServerRateLimitResponse = {
|
|
140
|
-
rateLimits?: unknown;
|
|
141
|
-
};
|
|
142
|
-
|
|
143
|
-
type AppServerRateLimitSnapshot = {
|
|
144
|
-
limitId?: unknown;
|
|
145
|
-
primary?: unknown;
|
|
146
|
-
secondary?: unknown;
|
|
147
|
-
};
|
|
148
|
-
|
|
149
|
-
type AppServerWindowSnapshot = {
|
|
150
|
-
usedPercent?: unknown;
|
|
151
|
-
resetAt?: unknown;
|
|
152
|
-
resetsAt?: unknown;
|
|
153
|
-
resetTime?: unknown;
|
|
154
|
-
endTime?: unknown;
|
|
155
|
-
endsAt?: unknown;
|
|
156
|
-
expiresAt?: unknown;
|
|
157
|
-
resetAfterSeconds?: unknown;
|
|
158
|
-
};
|
|
159
|
-
|
|
160
|
-
type RpcResponse = {
|
|
161
|
-
id?: unknown;
|
|
162
|
-
result?: unknown;
|
|
163
|
-
error?: { message?: unknown; code?: unknown };
|
|
164
|
-
};
|
|
165
|
-
|
|
166
|
-
type PendingRpc = {
|
|
167
|
-
resolve: (value: unknown) => void;
|
|
168
|
-
reject: (error: Error) => void;
|
|
169
|
-
};
|
|
170
|
-
|
|
171
|
-
// --- Shared Refresh ---
|
|
172
|
-
|
|
173
|
-
/**
|
|
174
|
-
* Cross-instance coordination for quota polling. Every Pi instance reads one
|
|
175
|
-
* JSON file; a single "leader"
|
|
176
|
-
* refreshes it every `LEADER_INTERVAL_MS`. Any other instance may take over once
|
|
177
|
-
* the file is `TAKEOVER_AFTER_MS` old: it first claims leadership (owner and
|
|
178
|
-
* timestamp) so nobody else is due, then fetches, then stamps the result. The
|
|
179
|
-
* file is the only authority for requests and fenced publication. Writes are
|
|
180
|
-
* atomic renames; short critical sections use an OS-backed SQLite mutex.
|
|
181
|
-
*/
|
|
182
|
-
|
|
183
|
-
export const LEADER_INTERVAL_MS = 60_000;
|
|
184
|
-
/** The leader is considered gone after missing its slot by 30 seconds. */
|
|
185
|
-
export const TAKEOVER_AFTER_MS = LEADER_INTERVAL_MS + 30_000;
|
|
186
|
-
/** Minimum pause between two fetch attempts of the same instance. */
|
|
187
|
-
export const MIN_ATTEMPT_GAP_MS = 60_000;
|
|
188
|
-
|
|
189
|
-
const STATE_FILE = "usage.json";
|
|
190
|
-
const LOCK_FILE = "mutex.sqlite";
|
|
191
|
-
|
|
192
|
-
export type SharedState<Report = unknown> = {
|
|
193
|
-
report?: Report;
|
|
194
|
-
/** When `report` was last fetched successfully. */
|
|
195
|
-
updatedAt?: number;
|
|
196
|
-
/**
|
|
197
|
-
* When the leader last touched the file: written when it claims a refresh,
|
|
198
|
-
* before fetching, and again when the fetch finishes.
|
|
199
|
-
*/
|
|
200
|
-
claimedAt?: number;
|
|
201
|
-
/** Instance id of the current leader (the last instance to claim). */
|
|
202
|
-
owner?: string;
|
|
203
|
-
/** Unique generation for this refresh, including renewals by the same owner. */
|
|
204
|
-
claimId?: string;
|
|
205
|
-
/** Last failure message; cleared by the next success. */
|
|
206
|
-
error?: string;
|
|
207
|
-
/** The failure means "no quota available" (n/a), not a runtime error. */
|
|
208
|
-
unavailable?: boolean;
|
|
209
|
-
failures?: number;
|
|
210
|
-
/** No instance should fetch before this time. */
|
|
211
|
-
retryNotBefore?: number;
|
|
212
|
-
};
|
|
213
|
-
|
|
214
|
-
export function readState<Report>(
|
|
215
|
-
dir: string,
|
|
216
|
-
): SharedState<Report> | undefined {
|
|
217
|
-
try {
|
|
218
|
-
const parsed = JSON.parse(
|
|
219
|
-
readFileSync(join(dir, STATE_FILE), "utf8"),
|
|
220
|
-
) as unknown;
|
|
221
|
-
return parsed && typeof parsed === "object" && !Array.isArray(parsed)
|
|
222
|
-
? (parsed as SharedState<Report>)
|
|
223
|
-
: undefined;
|
|
224
|
-
} catch {
|
|
225
|
-
return undefined;
|
|
226
|
-
}
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
export function writeState<Report>(
|
|
230
|
-
dir: string,
|
|
231
|
-
state: SharedState<Report>,
|
|
232
|
-
): boolean {
|
|
233
|
-
try {
|
|
234
|
-
mkdirSync(dir, { recursive: true });
|
|
235
|
-
const temp = join(dir, `${STATE_FILE}.${process.pid}.tmp`);
|
|
236
|
-
writeFileSync(temp, JSON.stringify(state), { mode: 0o600 });
|
|
237
|
-
renameSync(temp, join(dir, STATE_FILE));
|
|
238
|
-
return true;
|
|
239
|
-
} catch {
|
|
240
|
-
return false;
|
|
241
|
-
}
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
export type RefreshClaim = { owner: string; claimId: string };
|
|
245
|
-
|
|
246
|
-
export type RefreshOutcome<Report> =
|
|
247
|
-
| { ok: true; report: Report }
|
|
248
|
-
| {
|
|
249
|
-
ok: false;
|
|
250
|
-
error: string;
|
|
251
|
-
unavailable?: boolean;
|
|
252
|
-
rateLimited: boolean;
|
|
253
|
-
retryAfterMs?: number;
|
|
254
|
-
};
|
|
255
|
-
|
|
256
|
-
/** Read, decide and claim under the lock; never authorize an unwritten claim. */
|
|
257
|
-
export function claimRefresh(
|
|
258
|
-
dir: string,
|
|
259
|
-
owner: string,
|
|
260
|
-
now?: number,
|
|
261
|
-
): RefreshClaim | undefined {
|
|
262
|
-
const release = tryAcquireLock(dir);
|
|
263
|
-
if (!release) return undefined;
|
|
264
|
-
try {
|
|
265
|
-
const current = readState(dir);
|
|
266
|
-
const at = now ?? Date.now();
|
|
267
|
-
if (!isRefreshDue(current, owner, at)) return undefined;
|
|
268
|
-
const claim = { owner, claimId: randomUUID() };
|
|
269
|
-
return writeState(dir, { ...current, ...claim, claimedAt: at })
|
|
270
|
-
? claim
|
|
271
|
-
: undefined;
|
|
272
|
-
} finally {
|
|
273
|
-
release();
|
|
274
|
-
}
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
function matchesClaim(
|
|
278
|
-
state: SharedState | undefined,
|
|
279
|
-
claim: RefreshClaim,
|
|
280
|
-
now: number,
|
|
281
|
-
): boolean {
|
|
282
|
-
return (
|
|
283
|
-
state?.owner === claim.owner &&
|
|
284
|
-
state.claimId === claim.claimId &&
|
|
285
|
-
typeof state.claimedAt === "number" &&
|
|
286
|
-
now - state.claimedAt < TAKEOVER_AFTER_MS
|
|
287
|
-
);
|
|
288
|
-
}
|
|
289
|
-
|
|
290
|
-
/** Each admission check reads the file, not a remembered leadership flag. */
|
|
291
|
-
export function ownsRefreshClaim(
|
|
292
|
-
dir: string,
|
|
293
|
-
claim: RefreshClaim,
|
|
294
|
-
now?: number,
|
|
295
|
-
): boolean {
|
|
296
|
-
const current = readState(dir);
|
|
297
|
-
return matchesClaim(current, claim, now ?? Date.now());
|
|
298
|
-
}
|
|
299
|
-
|
|
300
|
-
/** A late success OR failure must not overwrite a successor's state. */
|
|
301
|
-
export function publishRefresh<Report>(
|
|
302
|
-
dir: string,
|
|
303
|
-
claim: RefreshClaim,
|
|
304
|
-
outcome: RefreshOutcome<Report>,
|
|
305
|
-
now?: number,
|
|
306
|
-
): boolean {
|
|
307
|
-
const release = tryAcquireLock(dir);
|
|
308
|
-
if (!release) return false;
|
|
309
|
-
try {
|
|
310
|
-
const current = readState<Report>(dir);
|
|
311
|
-
const at = now ?? Date.now();
|
|
312
|
-
if (!matchesClaim(current, claim, at)) return false;
|
|
313
|
-
if (outcome.ok) {
|
|
314
|
-
return writeState(dir, {
|
|
315
|
-
...claim,
|
|
316
|
-
claimedAt: at,
|
|
317
|
-
updatedAt: at,
|
|
318
|
-
report: outcome.report,
|
|
319
|
-
});
|
|
320
|
-
}
|
|
321
|
-
const failures = (current?.failures ?? 0) + 1;
|
|
322
|
-
return writeState(dir, {
|
|
323
|
-
...current,
|
|
324
|
-
...claim,
|
|
325
|
-
claimedAt: at,
|
|
326
|
-
error: outcome.error,
|
|
327
|
-
unavailable: outcome.unavailable,
|
|
328
|
-
failures,
|
|
329
|
-
retryNotBefore: at + failureBackoffMs(failures, outcome),
|
|
330
|
-
});
|
|
331
|
-
} finally {
|
|
332
|
-
release();
|
|
333
|
-
}
|
|
334
|
-
}
|
|
335
|
-
|
|
336
|
-
/** Earliest time at which `owner` should try to refresh the state. */
|
|
337
|
-
export function nextRefreshAt(
|
|
338
|
-
state: SharedState<unknown> | undefined,
|
|
339
|
-
owner: string,
|
|
340
|
-
now: number,
|
|
341
|
-
): number {
|
|
342
|
-
const hold = state?.retryNotBefore ?? 0;
|
|
343
|
-
const touchedAt = Math.max(
|
|
344
|
-
state?.updatedAt ?? -Infinity,
|
|
345
|
-
state?.claimedAt ?? -Infinity,
|
|
346
|
-
);
|
|
347
|
-
if (touchedAt === -Infinity) return Math.max(now, hold);
|
|
348
|
-
const interval =
|
|
349
|
-
state?.owner === owner ? LEADER_INTERVAL_MS : TAKEOVER_AFTER_MS;
|
|
350
|
-
return Math.max(touchedAt + interval, hold);
|
|
351
|
-
}
|
|
352
|
-
|
|
353
|
-
export function isRefreshDue(
|
|
354
|
-
state: SharedState<unknown> | undefined,
|
|
355
|
-
owner: string,
|
|
356
|
-
now: number,
|
|
357
|
-
): boolean {
|
|
358
|
-
return nextRefreshAt(state, owner, now) <= now;
|
|
359
|
-
}
|
|
360
|
-
|
|
361
|
-
/** Exponential failure backoff; HTTP 429 gets a longer base and cap. */
|
|
362
|
-
export function failureBackoffMs(
|
|
363
|
-
failures: number,
|
|
364
|
-
options: { rateLimited: boolean; retryAfterMs?: number },
|
|
365
|
-
): number {
|
|
366
|
-
const base = options.rateLimited ? 5 * 60_000 : 60_000;
|
|
367
|
-
const cap = options.rateLimited ? 30 * 60_000 : 5 * 60_000;
|
|
368
|
-
const exponential = Math.min(cap, base * 2 ** Math.max(0, failures - 1));
|
|
369
|
-
return Math.max(options.retryAfterMs ?? 0, exponential);
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
/**
|
|
373
|
-
* An empty SQLite transaction is a non-waiting, OS-backed mutex, not storage
|
|
374
|
-
* for quota or leadership. Close or process death releases it; a paused live
|
|
375
|
-
* holder cannot be evicted. Never unlink/replace mutex.sqlite while in use.
|
|
376
|
-
*/
|
|
377
|
-
export function tryAcquireLock(dir: string): (() => void) | undefined {
|
|
378
|
-
let database: DatabaseSync | undefined;
|
|
379
|
-
try {
|
|
380
|
-
mkdirSync(dir, { recursive: true });
|
|
381
|
-
database = new DatabaseSync(join(dir, LOCK_FILE));
|
|
382
|
-
// Contention must not wait on Pi's TUI thread; PRAGMA also works on Node 22.
|
|
383
|
-
database.exec("PRAGMA busy_timeout = 0; BEGIN EXCLUSIVE");
|
|
384
|
-
} catch {
|
|
385
|
-
database?.close();
|
|
386
|
-
return undefined;
|
|
387
|
-
}
|
|
388
|
-
return () => {
|
|
389
|
-
const held = database;
|
|
390
|
-
database = undefined;
|
|
391
|
-
held?.close();
|
|
392
|
-
};
|
|
393
|
-
}
|
|
394
|
-
|
|
395
|
-
export default function codexUsage(pi: ExtensionAPI) {
|
|
396
|
-
const instanceId = `${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
|
|
397
|
-
const stateDir = join(getAgentDir(), "tmp", "pi-codex-usage");
|
|
398
|
-
let lastAttemptAt = 0;
|
|
399
|
-
let inFlightRefresh: Promise<void> | undefined;
|
|
400
|
-
let shown: { key?: string; report?: CodexUsageReport; updatedAt?: number } = {};
|
|
401
|
-
let statuslineBlinkTimer: TimeoutHandle | undefined;
|
|
402
|
-
let statuslineCountdownTimer: TimeoutHandle | undefined;
|
|
403
|
-
let statuslineLoadingTimer: TimeoutHandle | undefined;
|
|
404
|
-
let statuslineRefreshTimer: TimeoutHandle | undefined;
|
|
405
|
-
let statuslineLoadingFrame = 0;
|
|
406
|
-
let statuslineRequestId = 0;
|
|
407
|
-
let unregisterTelegramStatusLine: (() => void) | undefined;
|
|
408
|
-
let telegramStatusLineRegistration: Promise<void> | undefined;
|
|
409
|
-
|
|
410
|
-
const loadState = () => readState<CodexUsageReport>(stateDir);
|
|
411
|
-
|
|
412
|
-
const ensureTelegramStatusLineRegistered = () => {
|
|
413
|
-
if (unregisterTelegramStatusLine || telegramStatusLineRegistration) return;
|
|
414
|
-
telegramStatusLineRegistration = registerCodexUsageTelegramStatusLine(
|
|
415
|
-
({ activeModel }) => {
|
|
416
|
-
if (!isOpenAICodexModel(activeModel)) return undefined;
|
|
417
|
-
if (!shown.report) return undefined;
|
|
418
|
-
const value = formatCodexUsageStatusValue(shown.report, activeModel);
|
|
419
|
-
return value
|
|
420
|
-
? { label: DEFAULT_STATUS_LABEL_TEXT, value }
|
|
421
|
-
: undefined;
|
|
422
|
-
},
|
|
423
|
-
)
|
|
424
|
-
.then((unregister) => {
|
|
425
|
-
unregisterTelegramStatusLine = unregister;
|
|
426
|
-
})
|
|
427
|
-
.finally(() => {
|
|
428
|
-
telegramStatusLineRegistration = undefined;
|
|
429
|
-
});
|
|
430
|
-
};
|
|
431
|
-
|
|
432
|
-
const clearStatuslineTimers = () => {
|
|
433
|
-
if (statuslineBlinkTimer) clearTimeout(statuslineBlinkTimer);
|
|
434
|
-
if (statuslineCountdownTimer) clearTimeout(statuslineCountdownTimer);
|
|
435
|
-
if (statuslineLoadingTimer) clearTimeout(statuslineLoadingTimer);
|
|
436
|
-
if (statuslineRefreshTimer) clearTimeout(statuslineRefreshTimer);
|
|
437
|
-
statuslineBlinkTimer = undefined;
|
|
438
|
-
statuslineCountdownTimer = undefined;
|
|
439
|
-
statuslineLoadingTimer = undefined;
|
|
440
|
-
statuslineRefreshTimer = undefined;
|
|
441
|
-
};
|
|
442
|
-
|
|
443
|
-
const stopStatuslineLoading = () => {
|
|
444
|
-
if (statuslineLoadingTimer) clearTimeout(statuslineLoadingTimer);
|
|
445
|
-
statuslineLoadingTimer = undefined;
|
|
446
|
-
};
|
|
447
|
-
|
|
448
|
-
const startStatuslineLoading = (
|
|
449
|
-
ctx: ExtensionContext,
|
|
450
|
-
model: CodexUsageModel | undefined,
|
|
451
|
-
) => {
|
|
452
|
-
if (statuslineLoadingTimer) return;
|
|
453
|
-
statuslineLoadingFrame = Math.random() < 0.5 ? 0 : DUAL_BAR_WIDTH * 2 - 1;
|
|
454
|
-
const drawNextFrame = () => {
|
|
455
|
-
try {
|
|
456
|
-
ctx.ui.setStatus(
|
|
457
|
-
STATUS_KEY,
|
|
458
|
-
formatStatuslineLoading(ctx, statuslineLoadingFrame, model),
|
|
459
|
-
);
|
|
460
|
-
statuslineLoadingFrame += 1;
|
|
461
|
-
statuslineLoadingTimer = setTimeout(
|
|
462
|
-
drawNextFrame,
|
|
463
|
-
LOADING_FRAME_MS,
|
|
464
|
-
) as TimeoutHandle;
|
|
465
|
-
statuslineLoadingTimer.unref?.();
|
|
466
|
-
} catch (error) {
|
|
467
|
-
statuslineLoadingTimer = undefined;
|
|
468
|
-
handleTimerError(error);
|
|
469
|
-
}
|
|
470
|
-
};
|
|
471
|
-
drawNextFrame();
|
|
472
|
-
};
|
|
473
|
-
|
|
474
|
-
const clearUsageStatusline = (ctx: ExtensionContext) => {
|
|
475
|
-
statuslineRequestId += 1;
|
|
476
|
-
clearStatuslineTimers();
|
|
477
|
-
shown = {};
|
|
478
|
-
ctx.ui.setStatus(STATUS_KEY, undefined);
|
|
479
|
-
};
|
|
480
|
-
|
|
481
|
-
const scheduleStatuslineRefresh = (ctx: ExtensionContext, delayMs: number) => {
|
|
482
|
-
if (statuslineRefreshTimer) clearTimeout(statuslineRefreshTimer);
|
|
483
|
-
statuslineRefreshTimer = setTimeout(() => {
|
|
484
|
-
void refreshCurrentCodexUsageStatusline(ctx, false).catch(
|
|
485
|
-
handleAsyncTimerError,
|
|
486
|
-
);
|
|
487
|
-
}, delayMs) as TimeoutHandle;
|
|
488
|
-
statuslineRefreshTimer.unref?.();
|
|
489
|
-
};
|
|
490
|
-
|
|
491
|
-
const scheduleStatuslineCountdown = (
|
|
492
|
-
ctx: ExtensionContext,
|
|
493
|
-
report: CodexUsageReport,
|
|
494
|
-
model: CodexUsageModel | undefined,
|
|
495
|
-
) => {
|
|
496
|
-
if (statuslineCountdownTimer) clearTimeout(statuslineCountdownTimer);
|
|
497
|
-
const delayMs = nextResetCountdownDelayMs(report, Date.now(), model);
|
|
498
|
-
if (delayMs === undefined) {
|
|
499
|
-
statuslineCountdownTimer = undefined;
|
|
500
|
-
return;
|
|
501
|
-
}
|
|
502
|
-
statuslineCountdownTimer = setTimeout(() => {
|
|
503
|
-
try {
|
|
504
|
-
if (isOpenAICodexModel(ctx.model)) {
|
|
505
|
-
ctx.ui.setStatus(
|
|
506
|
-
STATUS_KEY,
|
|
507
|
-
formatCodexUsageStatusline(report, ctx, model),
|
|
508
|
-
);
|
|
509
|
-
scheduleStatuslineCountdown(ctx, report, model);
|
|
510
|
-
}
|
|
511
|
-
} catch (error) {
|
|
512
|
-
handleTimerError(error);
|
|
513
|
-
}
|
|
514
|
-
}, delayMs) as TimeoutHandle;
|
|
515
|
-
statuslineCountdownTimer.unref?.();
|
|
516
|
-
};
|
|
517
|
-
|
|
518
|
-
const setUsageStatusline = (
|
|
519
|
-
ctx: ExtensionContext,
|
|
520
|
-
report: CodexUsageReport,
|
|
521
|
-
options: { blink: boolean; model: CodexUsageModel | undefined },
|
|
522
|
-
) => {
|
|
523
|
-
if (statuslineBlinkTimer) clearTimeout(statuslineBlinkTimer);
|
|
524
|
-
if (statuslineCountdownTimer) clearTimeout(statuslineCountdownTimer);
|
|
525
|
-
stopStatuslineLoading();
|
|
526
|
-
statuslineBlinkTimer = undefined;
|
|
527
|
-
statuslineCountdownTimer = undefined;
|
|
528
|
-
const text = formatCodexUsageStatusline(report, ctx, options.model);
|
|
529
|
-
if (options.blink) {
|
|
530
|
-
ctx.ui.setStatus(
|
|
531
|
-
STATUS_KEY,
|
|
532
|
-
formatStatuslineLoading(ctx, statuslineLoadingFrame, options.model),
|
|
533
|
-
);
|
|
534
|
-
statuslineBlinkTimer = setTimeout(() => {
|
|
535
|
-
try {
|
|
536
|
-
ctx.ui.setStatus(STATUS_KEY, text);
|
|
537
|
-
scheduleStatuslineCountdown(ctx, report, options.model);
|
|
538
|
-
statuslineBlinkTimer = undefined;
|
|
539
|
-
} catch (error) {
|
|
540
|
-
handleTimerError(error);
|
|
541
|
-
}
|
|
542
|
-
}, REDRAW_BLINK_MS) as TimeoutHandle;
|
|
543
|
-
statuslineBlinkTimer.unref?.();
|
|
544
|
-
} else {
|
|
545
|
-
ctx.ui.setStatus(STATUS_KEY, text);
|
|
546
|
-
scheduleStatuslineCountdown(ctx, report, options.model);
|
|
547
|
-
}
|
|
548
|
-
};
|
|
549
|
-
|
|
550
|
-
/** Draws the shared state; skips redraws when nothing changed. */
|
|
551
|
-
const renderState = (
|
|
552
|
-
ctx: ExtensionContext,
|
|
553
|
-
state: CodexSharedState | undefined,
|
|
554
|
-
model: CodexUsageModel | undefined,
|
|
555
|
-
force: boolean,
|
|
556
|
-
) => {
|
|
557
|
-
// Cached display data is not permission to query when the file is unreadable.
|
|
558
|
-
if (!state && shown.report && Date.now() - (shown.updatedAt ?? 0) < STALE_REPORT_MAX_AGE_MS) {
|
|
559
|
-
if (force) setUsageStatusline(ctx, shown.report, { blink: false, model });
|
|
560
|
-
return;
|
|
561
|
-
}
|
|
562
|
-
const usable =
|
|
563
|
-
state?.report &&
|
|
564
|
-
state.updatedAt !== undefined &&
|
|
565
|
-
Date.now() - state.updatedAt < STALE_REPORT_MAX_AGE_MS &&
|
|
566
|
-
canReuseCachedReport(state.report, model)
|
|
567
|
-
? state.report
|
|
568
|
-
: undefined;
|
|
569
|
-
if (usable) {
|
|
570
|
-
const key = `report:${state?.updatedAt}`;
|
|
571
|
-
if (!force && shown.key === key) return;
|
|
572
|
-
const blink = shown.report
|
|
573
|
-
? formatReportBar(shown.report, model) !== formatReportBar(usable, model)
|
|
574
|
-
: false;
|
|
575
|
-
shown = { key, report: usable, updatedAt: state?.updatedAt };
|
|
576
|
-
setUsageStatusline(ctx, usable, { blink, model });
|
|
577
|
-
} else if (state?.error) {
|
|
578
|
-
const key = `error:${state.error}`;
|
|
579
|
-
if (!force && shown.key === key) return;
|
|
580
|
-
shown = { key };
|
|
581
|
-
clearStatuslineTimers();
|
|
582
|
-
ctx.ui.setStatus(
|
|
583
|
-
STATUS_KEY,
|
|
584
|
-
formatStatuslineProblem(ctx, state.unavailable === true, model),
|
|
585
|
-
);
|
|
586
|
-
} else {
|
|
587
|
-
shown = { key: "loading" };
|
|
588
|
-
startStatuslineLoading(ctx, model);
|
|
589
|
-
}
|
|
590
|
-
};
|
|
591
|
-
|
|
592
|
-
/**
|
|
593
|
-
* When this instance is due (leader after 1 minute, anyone after 90 seconds) it
|
|
594
|
-
* claims leadership under the lock (owner and timestamp, so no other
|
|
595
|
-
* instance is due), then fetches, then stamps the outcome. Failures are
|
|
596
|
-
* published with a backoff so other instances do not pile on.
|
|
597
|
-
*/
|
|
598
|
-
const refreshSharedState = (
|
|
599
|
-
ctx: ExtensionContext,
|
|
600
|
-
model: CodexUsageModel | undefined,
|
|
601
|
-
) => {
|
|
602
|
-
if (inFlightRefresh) return inFlightRefresh;
|
|
603
|
-
const promise = (async () => {
|
|
604
|
-
const claim = claimRefresh(stateDir, instanceId);
|
|
605
|
-
if (!claim) return;
|
|
606
|
-
lastAttemptAt = Date.now();
|
|
607
|
-
const result = await queryConfirmedUsage(
|
|
608
|
-
ctx,
|
|
609
|
-
model,
|
|
610
|
-
loadState()?.report,
|
|
611
|
-
() => ownsRefreshClaim(stateDir, claim),
|
|
612
|
-
);
|
|
613
|
-
if (!result) return;
|
|
614
|
-
if (result.ok) {
|
|
615
|
-
publishRefresh(stateDir, claim, result);
|
|
616
|
-
return;
|
|
617
|
-
}
|
|
618
|
-
if (result.errors.some((error) => isStaleExtensionContextError(error.cause)))
|
|
619
|
-
return;
|
|
620
|
-
publishRefresh(stateDir, claim, {
|
|
621
|
-
ok: false,
|
|
622
|
-
error: result.errors.map((error) => error.message).join("; "),
|
|
623
|
-
unavailable: isUsageUnavailable(result.errors),
|
|
624
|
-
rateLimited: result.errors.some((error) =>
|
|
625
|
-
error.message.includes("returned 429"),
|
|
626
|
-
),
|
|
627
|
-
});
|
|
628
|
-
})().finally(() => {
|
|
629
|
-
if (inFlightRefresh === promise) inFlightRefresh = undefined;
|
|
630
|
-
});
|
|
631
|
-
inFlightRefresh = promise;
|
|
632
|
-
return promise;
|
|
633
|
-
};
|
|
634
|
-
|
|
635
|
-
/**
|
|
636
|
-
* Queries the usage. A first report claiming every window is completely
|
|
637
|
-
* unused is provisional (providers can briefly emit zeroed windows while
|
|
638
|
-
* initializing), so the claiming leader re-queries it every second for up to
|
|
639
|
-
* 15 seconds before publishing.
|
|
640
|
-
*/
|
|
641
|
-
const queryConfirmedUsage = async (
|
|
642
|
-
ctx: ExtensionContext,
|
|
643
|
-
model: CodexUsageModel | undefined,
|
|
644
|
-
previous: CodexUsageReport | undefined,
|
|
645
|
-
mayQuery: () => boolean,
|
|
646
|
-
): Promise<QueryUsageResult | undefined> => {
|
|
647
|
-
const startedAt = Date.now();
|
|
648
|
-
let result = await queryUsage(
|
|
649
|
-
ctx,
|
|
650
|
-
{ timeoutMs: DEFAULT_TIMEOUT_MS },
|
|
651
|
-
model,
|
|
652
|
-
mayQuery,
|
|
653
|
-
);
|
|
654
|
-
if (previous && isFullyAvailableReport(previous, model)) return result;
|
|
655
|
-
while (
|
|
656
|
-
result?.ok &&
|
|
657
|
-
isFullyAvailableReport(result.report, model) &&
|
|
658
|
-
Date.now() - startedAt < FULL_AVAILABILITY_CONFIRMATION_MS
|
|
659
|
-
) {
|
|
660
|
-
await new Promise((resolve) => setTimeout(resolve, PROVISIONAL_RETRY_MS));
|
|
661
|
-
const retry = await queryUsage(
|
|
662
|
-
ctx,
|
|
663
|
-
{ timeoutMs: DEFAULT_TIMEOUT_MS },
|
|
664
|
-
model,
|
|
665
|
-
mayQuery,
|
|
666
|
-
);
|
|
667
|
-
if (!retry) return undefined;
|
|
668
|
-
if (!retry.ok) break;
|
|
669
|
-
result = retry;
|
|
670
|
-
}
|
|
671
|
-
return result;
|
|
672
|
-
};
|
|
673
|
-
|
|
674
|
-
const nextTickDelayMs = (state: CodexSharedState | undefined) => {
|
|
675
|
-
// Nothing to show yet (e.g. a claimed fetch is in flight): poll quickly.
|
|
676
|
-
if (shown.key === "loading") return MIN_TICK_MS;
|
|
677
|
-
const now = Date.now();
|
|
678
|
-
const dueAt = Math.max(
|
|
679
|
-
nextRefreshAt(state, instanceId, now),
|
|
680
|
-
lastAttemptAt + MIN_ATTEMPT_GAP_MS,
|
|
681
|
-
);
|
|
682
|
-
const jitter =
|
|
683
|
-
state?.owner === instanceId ? 0 : Math.random() * TAKEOVER_JITTER_MS;
|
|
684
|
-
return Math.min(MAX_TICK_MS, Math.max(MIN_TICK_MS, dueAt - now + jitter));
|
|
685
|
-
};
|
|
686
|
-
|
|
687
|
-
const refreshCurrentCodexUsageStatusline = async (
|
|
688
|
-
ctx: ExtensionContext,
|
|
689
|
-
forceRender: boolean,
|
|
690
|
-
model?: CodexUsageModel,
|
|
691
|
-
) => {
|
|
692
|
-
try {
|
|
693
|
-
const activeModel = model ?? ctx.model;
|
|
694
|
-
if (!isOpenAICodexModel(activeModel)) {
|
|
695
|
-
clearUsageStatusline(ctx);
|
|
696
|
-
return;
|
|
697
|
-
}
|
|
698
|
-
|
|
699
|
-
const requestId = statuslineRequestId + 1;
|
|
700
|
-
statuslineRequestId = requestId;
|
|
701
|
-
let state = loadState();
|
|
702
|
-
renderState(ctx, state, activeModel, forceRender);
|
|
703
|
-
|
|
704
|
-
const now = Date.now();
|
|
705
|
-
if (
|
|
706
|
-
isRefreshDue(state, instanceId, now) &&
|
|
707
|
-
now - lastAttemptAt >= MIN_ATTEMPT_GAP_MS
|
|
708
|
-
) {
|
|
709
|
-
await refreshSharedState(ctx, activeModel);
|
|
710
|
-
if (requestId !== statuslineRequestId) return;
|
|
711
|
-
if (!isOpenAICodexModel(ctx.model)) {
|
|
712
|
-
clearUsageStatusline(ctx);
|
|
713
|
-
return;
|
|
714
|
-
}
|
|
715
|
-
state = loadState();
|
|
716
|
-
renderState(ctx, state, activeModel, false);
|
|
717
|
-
}
|
|
718
|
-
scheduleStatuslineRefresh(ctx, nextTickDelayMs(state));
|
|
719
|
-
} catch (error) {
|
|
720
|
-
if (isStaleExtensionContextError(error)) {
|
|
721
|
-
clearStatuslineTimers();
|
|
722
|
-
return;
|
|
723
|
-
}
|
|
724
|
-
throw error;
|
|
725
|
-
}
|
|
726
|
-
};
|
|
727
|
-
|
|
728
|
-
ensureTelegramStatusLineRegistered();
|
|
729
|
-
|
|
730
|
-
pi.on("session_start", (_event, ctx) => {
|
|
731
|
-
ensureTelegramStatusLineRegistered();
|
|
732
|
-
if (isOpenAICodexModel(ctx.model))
|
|
733
|
-
void refreshCurrentCodexUsageStatusline(ctx, true).catch(
|
|
734
|
-
handleAsyncTimerError,
|
|
735
|
-
);
|
|
736
|
-
else clearUsageStatusline(ctx);
|
|
737
|
-
});
|
|
738
|
-
|
|
739
|
-
pi.on("session_tree", (_event, ctx) => {
|
|
740
|
-
if (isOpenAICodexModel(ctx.model))
|
|
741
|
-
void refreshCurrentCodexUsageStatusline(ctx, true).catch(
|
|
742
|
-
handleAsyncTimerError,
|
|
743
|
-
);
|
|
744
|
-
else clearUsageStatusline(ctx);
|
|
745
|
-
});
|
|
746
|
-
|
|
747
|
-
pi.on("model_select", (event, ctx) => {
|
|
748
|
-
if (isOpenAICodexModel(event.model)) {
|
|
749
|
-
void refreshCurrentCodexUsageStatusline(ctx, true, event.model).catch(
|
|
750
|
-
handleAsyncTimerError,
|
|
751
|
-
);
|
|
752
|
-
} else {
|
|
753
|
-
clearUsageStatusline(ctx);
|
|
754
|
-
}
|
|
755
|
-
});
|
|
756
|
-
|
|
757
|
-
pi.on("session_shutdown", (_event, ctx) => {
|
|
758
|
-
clearUsageStatusline(ctx);
|
|
759
|
-
unregisterTelegramStatusLine?.();
|
|
760
|
-
unregisterTelegramStatusLine = undefined;
|
|
761
|
-
});
|
|
762
|
-
}
|
|
763
|
-
|
|
764
|
-
function handleAsyncTimerError(error: unknown): void {
|
|
765
|
-
handleTimerError(error);
|
|
766
|
-
}
|
|
767
|
-
|
|
768
|
-
function handleTimerError(error: unknown): void {
|
|
769
|
-
if (isStaleExtensionContextError(error)) return;
|
|
770
|
-
throw error;
|
|
771
|
-
}
|
|
772
|
-
|
|
773
|
-
export function isStaleExtensionContextError(error: unknown): boolean {
|
|
774
|
-
return error instanceof Error && error.message.includes("ctx is stale");
|
|
775
|
-
}
|
|
776
|
-
|
|
777
|
-
function isOpenAICodexModel(
|
|
778
|
-
model: Pick<PiModel, "provider"> | undefined,
|
|
779
|
-
): boolean {
|
|
780
|
-
return model?.provider === CODEX_PROVIDER_ID;
|
|
781
|
-
}
|
|
782
|
-
|
|
783
|
-
async function importTelegramStatusLineModule(): Promise<
|
|
784
|
-
TelegramStatusLineModule | undefined
|
|
785
|
-
> {
|
|
786
|
-
for (const specifier of TELEGRAM_STATUS_IMPORT_SPECIFIERS) {
|
|
787
|
-
try {
|
|
788
|
-
const imported = (await import(specifier)) as TelegramStatusLineModule;
|
|
789
|
-
if (typeof imported.registerTelegramStatusLineProvider === "function") {
|
|
790
|
-
return imported;
|
|
791
|
-
}
|
|
792
|
-
} catch {
|
|
793
|
-
// pi-telegram is optional; absence just disables the Telegram status line.
|
|
794
|
-
}
|
|
795
|
-
}
|
|
796
|
-
return undefined;
|
|
797
|
-
}
|
|
798
|
-
|
|
799
|
-
async function registerCodexUsageTelegramStatusLine(
|
|
800
|
-
provider: TelegramStatusLineProvider,
|
|
801
|
-
): Promise<(() => void) | undefined> {
|
|
802
|
-
const telegramStatus = await importTelegramStatusLineModule();
|
|
803
|
-
return telegramStatus?.registerTelegramStatusLineProvider?.(provider, {
|
|
804
|
-
id: CODEX_USAGE_EXTENSION_ID,
|
|
805
|
-
});
|
|
806
|
-
}
|
|
807
|
-
|
|
808
|
-
async function queryUsage(
|
|
809
|
-
ctx: ExtensionContext,
|
|
810
|
-
options: Pick<QueryUsageOptions, "timeoutMs">,
|
|
811
|
-
model: CodexUsageModel | undefined,
|
|
812
|
-
mayQuery: () => boolean,
|
|
813
|
-
): Promise<QueryUsageResult | undefined> {
|
|
814
|
-
const errors: UsageQueryError[] = [];
|
|
815
|
-
const sources = ["pi-auth", "codex-app-server"] as const;
|
|
816
|
-
|
|
817
|
-
for (const source of sources) {
|
|
818
|
-
if (!mayQuery()) return undefined;
|
|
819
|
-
try {
|
|
820
|
-
const report =
|
|
821
|
-
source === "pi-auth"
|
|
822
|
-
? await queryViaPiAuth(ctx, options.timeoutMs, mayQuery)
|
|
823
|
-
: await queryViaCodexAppServer(options.timeoutMs, mayQuery);
|
|
824
|
-
if (!report) return undefined;
|
|
825
|
-
if (
|
|
826
|
-
selectUsageSnapshot(report, CODEX_USAGE_LIMIT_ID) ||
|
|
827
|
-
report.credits
|
|
828
|
-
) {
|
|
829
|
-
return { ok: true, report };
|
|
830
|
-
}
|
|
831
|
-
errors.push({
|
|
832
|
-
source,
|
|
833
|
-
message: `${source} returned no displayable codex rate-limit windows`,
|
|
834
|
-
});
|
|
835
|
-
} catch (cause) {
|
|
836
|
-
errors.push({ source, message: errorMessage(cause), cause });
|
|
837
|
-
}
|
|
838
|
-
}
|
|
839
|
-
|
|
840
|
-
return { ok: false, errors };
|
|
841
|
-
}
|
|
842
|
-
|
|
843
|
-
async function queryViaPiAuth(
|
|
844
|
-
ctx: ExtensionContext,
|
|
845
|
-
timeoutMs: number,
|
|
846
|
-
mayQuery: () => boolean,
|
|
847
|
-
): Promise<CodexUsageReport | undefined> {
|
|
848
|
-
const auth = await resolvePiCodexAuth(ctx);
|
|
849
|
-
if (!auth) {
|
|
850
|
-
throw new Error(
|
|
851
|
-
"No Pi OpenAI Codex subscription auth was available. Use a Pi OpenAI Codex model or run /login for OpenAI ChatGPT Plus/Pro (Codex).",
|
|
852
|
-
);
|
|
853
|
-
}
|
|
854
|
-
|
|
855
|
-
if (!mayQuery()) return undefined;
|
|
856
|
-
const response = await fetchWithTimeout(
|
|
857
|
-
CODEX_USAGE_URL,
|
|
858
|
-
{ headers: auth.headers },
|
|
859
|
-
timeoutMs,
|
|
860
|
-
);
|
|
861
|
-
const text = await response.text();
|
|
862
|
-
if (!response.ok) {
|
|
863
|
-
throw new Error(
|
|
864
|
-
`Codex usage endpoint returned ${response.status} ${response.statusText}: ${redactErrorBody(text)}`,
|
|
865
|
-
);
|
|
866
|
-
}
|
|
867
|
-
|
|
868
|
-
const payload = parseJsonObject(text, "Codex usage endpoint response");
|
|
869
|
-
return normalizeBackendPayload(
|
|
870
|
-
payload as RateLimitStatusPayload,
|
|
871
|
-
Date.now(),
|
|
872
|
-
"pi-auth",
|
|
873
|
-
);
|
|
874
|
-
}
|
|
875
|
-
|
|
876
|
-
async function resolvePiCodexAuth(
|
|
877
|
-
ctx: ExtensionContext,
|
|
878
|
-
): Promise<{ headers: Record<string, string> } | undefined> {
|
|
879
|
-
const models = codexAuthCandidateModels(ctx);
|
|
880
|
-
const errors: string[] = [];
|
|
881
|
-
|
|
882
|
-
for (const model of models) {
|
|
883
|
-
const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
|
|
884
|
-
if (!auth.ok) {
|
|
885
|
-
errors.push(auth.error);
|
|
886
|
-
continue;
|
|
887
|
-
}
|
|
888
|
-
|
|
889
|
-
const headers: Record<string, string> = {};
|
|
890
|
-
for (const [name, value] of Object.entries(auth.headers ?? {})) {
|
|
891
|
-
if (value !== null) headers[name] = value;
|
|
892
|
-
}
|
|
893
|
-
if (!hasHeader(headers, "Authorization") && auth.apiKey) {
|
|
894
|
-
headers.Authorization = `Bearer ${auth.apiKey}`;
|
|
895
|
-
}
|
|
896
|
-
if (!hasHeader(headers, "User-Agent")) {
|
|
897
|
-
headers["User-Agent"] = "pi-codex-usage";
|
|
898
|
-
}
|
|
899
|
-
if (hasHeader(headers, "Authorization")) {
|
|
900
|
-
return { headers };
|
|
901
|
-
}
|
|
902
|
-
}
|
|
903
|
-
|
|
904
|
-
if (errors.length > 0) {
|
|
905
|
-
throw new Error(errors.join("; "));
|
|
906
|
-
}
|
|
907
|
-
return undefined;
|
|
908
|
-
}
|
|
909
|
-
|
|
910
|
-
function codexAuthCandidateModels(ctx: ExtensionContext): PiModel[] {
|
|
911
|
-
const candidates: PiModel[] = [];
|
|
912
|
-
const seen = new Set<string>();
|
|
913
|
-
const add = (model: PiModel | undefined) => {
|
|
914
|
-
if (!model || model.provider !== CODEX_PROVIDER_ID) return;
|
|
915
|
-
const key = `${model.provider}/${model.id}`;
|
|
916
|
-
if (seen.has(key)) return;
|
|
917
|
-
seen.add(key);
|
|
918
|
-
candidates.push(model);
|
|
919
|
-
};
|
|
920
|
-
|
|
921
|
-
add(ctx.model);
|
|
922
|
-
for (const model of ctx.modelRegistry.getAvailable()) add(model);
|
|
923
|
-
for (const model of ctx.modelRegistry.getAll()) add(model);
|
|
924
|
-
return candidates;
|
|
925
|
-
}
|
|
926
|
-
|
|
927
|
-
async function fetchWithTimeout(
|
|
928
|
-
url: string,
|
|
929
|
-
init: RequestInit,
|
|
930
|
-
timeoutMs: number,
|
|
931
|
-
): Promise<Response> {
|
|
932
|
-
const controller = new AbortController();
|
|
933
|
-
const timeout = setTimeout(() => controller.abort(), timeoutMs);
|
|
934
|
-
try {
|
|
935
|
-
return await fetch(url, { ...init, signal: controller.signal });
|
|
936
|
-
} catch (error) {
|
|
937
|
-
if (controller.signal.aborted) {
|
|
938
|
-
throw new Error(
|
|
939
|
-
`Timed out after ${Math.round(timeoutMs / 1000)}s while fetching Codex usage.`,
|
|
940
|
-
);
|
|
941
|
-
}
|
|
942
|
-
throw error;
|
|
943
|
-
} finally {
|
|
944
|
-
clearTimeout(timeout);
|
|
945
|
-
}
|
|
946
|
-
}
|
|
947
|
-
|
|
948
|
-
async function queryViaCodexAppServer(
|
|
949
|
-
timeoutMs: number,
|
|
950
|
-
mayQuery: () => boolean,
|
|
951
|
-
): Promise<CodexUsageReport | undefined> {
|
|
952
|
-
const client = new CodexAppServerClient(timeoutMs);
|
|
953
|
-
try {
|
|
954
|
-
await client.start();
|
|
955
|
-
if (!mayQuery()) return undefined;
|
|
956
|
-
await client.request("initialize", {
|
|
957
|
-
clientInfo: {
|
|
958
|
-
name: "pi_codex_usage",
|
|
959
|
-
title: "Pi Codex Usage",
|
|
960
|
-
version: "0.1.0",
|
|
961
|
-
},
|
|
962
|
-
capabilities: {
|
|
963
|
-
experimentalApi: false,
|
|
964
|
-
requestAttestation: false,
|
|
965
|
-
optOutNotificationMethods: [],
|
|
966
|
-
},
|
|
967
|
-
});
|
|
968
|
-
client.notify("initialized");
|
|
969
|
-
if (!mayQuery()) return undefined;
|
|
970
|
-
const result = await client.request("account/rateLimits/read", undefined);
|
|
971
|
-
return normalizeAppServerResponse(
|
|
972
|
-
assertObject(
|
|
973
|
-
result,
|
|
974
|
-
"account/rateLimits/read result",
|
|
975
|
-
) as AppServerRateLimitResponse,
|
|
976
|
-
Date.now(),
|
|
977
|
-
);
|
|
978
|
-
} finally {
|
|
979
|
-
client.dispose();
|
|
980
|
-
}
|
|
981
|
-
}
|
|
982
|
-
|
|
983
|
-
class CodexAppServerClient {
|
|
984
|
-
private child?: ChildProcessWithoutNullStreams;
|
|
985
|
-
private nextId = 1;
|
|
986
|
-
private stderr = "";
|
|
987
|
-
private readonly pending = new Map<number, PendingRpc>();
|
|
988
|
-
private startPromise?: Promise<void>;
|
|
989
|
-
private exitError?: Error;
|
|
990
|
-
private readonly timeoutMs: number;
|
|
991
|
-
|
|
992
|
-
constructor(timeoutMs: number) {
|
|
993
|
-
this.timeoutMs = timeoutMs;
|
|
994
|
-
}
|
|
995
|
-
|
|
996
|
-
start(): Promise<void> {
|
|
997
|
-
if (this.startPromise) return this.startPromise;
|
|
998
|
-
|
|
999
|
-
this.startPromise = new Promise((resolve, reject) => {
|
|
1000
|
-
const child = spawn("codex", ["app-server", "--listen", "stdio://"], {
|
|
1001
|
-
stdio: ["pipe", "pipe", "pipe"],
|
|
1002
|
-
});
|
|
1003
|
-
this.child = child;
|
|
1004
|
-
|
|
1005
|
-
const startupTimeout = setTimeout(() => {
|
|
1006
|
-
reject(
|
|
1007
|
-
new Error(
|
|
1008
|
-
`Timed out after ${Math.round(this.timeoutMs / 1000)}s starting codex app-server.`,
|
|
1009
|
-
),
|
|
1010
|
-
);
|
|
1011
|
-
}, this.timeoutMs);
|
|
1012
|
-
|
|
1013
|
-
child.once("spawn", () => {
|
|
1014
|
-
clearTimeout(startupTimeout);
|
|
1015
|
-
resolve();
|
|
1016
|
-
});
|
|
1017
|
-
|
|
1018
|
-
child.once("error", (error) => {
|
|
1019
|
-
clearTimeout(startupTimeout);
|
|
1020
|
-
reject(new Error(`Failed to start codex app-server: ${error.message}`));
|
|
1021
|
-
this.rejectAll(error);
|
|
1022
|
-
});
|
|
1023
|
-
|
|
1024
|
-
child.once("exit", (code, signal) => {
|
|
1025
|
-
const suffix = this.stderr
|
|
1026
|
-
? ` stderr: ${redactErrorBody(this.stderr)}`
|
|
1027
|
-
: "";
|
|
1028
|
-
this.exitError = new Error(
|
|
1029
|
-
`codex app-server exited before completing the request (code ${code ?? "unknown"}, signal ${signal ?? "none"}).${suffix}`,
|
|
1030
|
-
);
|
|
1031
|
-
this.rejectAll(this.exitError);
|
|
1032
|
-
});
|
|
1033
|
-
|
|
1034
|
-
child.stderr.setEncoding("utf8");
|
|
1035
|
-
child.stderr.on("data", (chunk: string) => {
|
|
1036
|
-
this.stderr = truncateEnd(this.stderr + chunk, MAX_ERROR_BODY_CHARS);
|
|
1037
|
-
});
|
|
1038
|
-
|
|
1039
|
-
const lines = createInterface({ input: child.stdout });
|
|
1040
|
-
lines.on("line", (line) => this.handleLine(line));
|
|
1041
|
-
});
|
|
1042
|
-
|
|
1043
|
-
return this.startPromise;
|
|
1044
|
-
}
|
|
1045
|
-
|
|
1046
|
-
request(method: string, params: unknown): Promise<unknown> {
|
|
1047
|
-
const child = this.child;
|
|
1048
|
-
if (!child?.stdin.writable) {
|
|
1049
|
-
throw new Error("codex app-server is not running.");
|
|
1050
|
-
}
|
|
1051
|
-
if (this.exitError) throw this.exitError;
|
|
1052
|
-
|
|
1053
|
-
const id = this.nextId++;
|
|
1054
|
-
const payload =
|
|
1055
|
-
params === undefined ? { method, id } : { method, id, params };
|
|
1056
|
-
const response = new Promise<unknown>((resolve, reject) => {
|
|
1057
|
-
const timeout = setTimeout(() => {
|
|
1058
|
-
this.pending.delete(id);
|
|
1059
|
-
reject(
|
|
1060
|
-
new Error(
|
|
1061
|
-
`Timed out after ${Math.round(this.timeoutMs / 1000)}s waiting for ${method}.`,
|
|
1062
|
-
),
|
|
1063
|
-
);
|
|
1064
|
-
}, this.timeoutMs);
|
|
1065
|
-
|
|
1066
|
-
this.pending.set(id, {
|
|
1067
|
-
resolve: (value) => {
|
|
1068
|
-
clearTimeout(timeout);
|
|
1069
|
-
resolve(value);
|
|
1070
|
-
},
|
|
1071
|
-
reject: (error) => {
|
|
1072
|
-
clearTimeout(timeout);
|
|
1073
|
-
reject(error);
|
|
1074
|
-
},
|
|
1075
|
-
});
|
|
1076
|
-
});
|
|
1077
|
-
|
|
1078
|
-
child.stdin.write(`${JSON.stringify(payload)}\n`);
|
|
1079
|
-
return response;
|
|
1080
|
-
}
|
|
1081
|
-
|
|
1082
|
-
notify(method: string): void {
|
|
1083
|
-
const child = this.child;
|
|
1084
|
-
if (!child?.stdin.writable) return;
|
|
1085
|
-
child.stdin.write(`${JSON.stringify({ method })}\n`);
|
|
1086
|
-
}
|
|
1087
|
-
|
|
1088
|
-
dispose(): void {
|
|
1089
|
-
for (const [id, pending] of this.pending) {
|
|
1090
|
-
pending.reject(new Error(`codex app-server request ${id} cancelled.`));
|
|
1091
|
-
}
|
|
1092
|
-
this.pending.clear();
|
|
1093
|
-
|
|
1094
|
-
const child = this.child;
|
|
1095
|
-
if (!child) return;
|
|
1096
|
-
child.stdin.end();
|
|
1097
|
-
if (!child.killed) child.kill();
|
|
1098
|
-
this.child = undefined;
|
|
1099
|
-
}
|
|
1100
|
-
|
|
1101
|
-
private handleLine(line: string): void {
|
|
1102
|
-
let parsed: RpcResponse;
|
|
1103
|
-
try {
|
|
1104
|
-
parsed = JSON.parse(line) as RpcResponse;
|
|
1105
|
-
} catch {
|
|
1106
|
-
return;
|
|
1107
|
-
}
|
|
1108
|
-
|
|
1109
|
-
if (typeof parsed.id !== "number") return;
|
|
1110
|
-
const pending = this.pending.get(parsed.id);
|
|
1111
|
-
if (!pending) return;
|
|
1112
|
-
this.pending.delete(parsed.id);
|
|
1113
|
-
|
|
1114
|
-
if (parsed.error) {
|
|
1115
|
-
const message =
|
|
1116
|
-
typeof parsed.error.message === "string"
|
|
1117
|
-
? parsed.error.message
|
|
1118
|
-
: "unknown error";
|
|
1119
|
-
pending.reject(new Error(`codex app-server request failed: ${message}`));
|
|
1120
|
-
return;
|
|
1121
|
-
}
|
|
1122
|
-
|
|
1123
|
-
pending.resolve(parsed.result);
|
|
1124
|
-
}
|
|
1125
|
-
|
|
1126
|
-
private rejectAll(error: Error): void {
|
|
1127
|
-
for (const pending of this.pending.values()) pending.reject(error);
|
|
1128
|
-
this.pending.clear();
|
|
1129
|
-
}
|
|
1130
|
-
}
|
|
1131
|
-
|
|
1132
|
-
export function normalizeBackendPayload(
|
|
1133
|
-
payload: RateLimitStatusPayload,
|
|
1134
|
-
_capturedAt: number,
|
|
1135
|
-
_source: UsageSource,
|
|
1136
|
-
): CodexUsageReport {
|
|
1137
|
-
const snapshots: NormalizedRateLimitSnapshot[] = [];
|
|
1138
|
-
const primarySnapshot = normalizeBackendSnapshot(
|
|
1139
|
-
CODEX_USAGE_LIMIT_ID,
|
|
1140
|
-
payload.rate_limit,
|
|
1141
|
-
_capturedAt,
|
|
1142
|
-
);
|
|
1143
|
-
if (primarySnapshot) snapshots.push(primarySnapshot);
|
|
1144
|
-
|
|
1145
|
-
const credits = normalizeBackendCredits(payload, _capturedAt);
|
|
1146
|
-
if (snapshots.length === 0 && !credits) {
|
|
1147
|
-
throw new Error(
|
|
1148
|
-
"Codex usage endpoint returned no displayable rate-limit windows or credits.",
|
|
1149
|
-
);
|
|
1150
|
-
}
|
|
1151
|
-
return credits ? { snapshots, credits } : { snapshots };
|
|
1152
|
-
}
|
|
1153
|
-
|
|
1154
|
-
function normalizeBackendCredits(
|
|
1155
|
-
payload: RateLimitStatusPayload,
|
|
1156
|
-
capturedAt: number,
|
|
1157
|
-
): NormalizedCreditUsage | undefined {
|
|
1158
|
-
const spendControl = payload.spend_control as
|
|
1159
|
-
| Record<string, unknown>
|
|
1160
|
-
| undefined;
|
|
1161
|
-
const individualLimit = spendControl?.individual_limit as
|
|
1162
|
-
| Record<string, unknown>
|
|
1163
|
-
| undefined;
|
|
1164
|
-
const credits = payload.credits as Record<string, unknown> | undefined;
|
|
1165
|
-
const limit = asNumber(individualLimit?.limit);
|
|
1166
|
-
const used = asNumber(individualLimit?.used);
|
|
1167
|
-
const remaining = asNumber(individualLimit?.remaining);
|
|
1168
|
-
const resetAt = asResetTime(
|
|
1169
|
-
[
|
|
1170
|
-
individualLimit?.reset_at,
|
|
1171
|
-
individualLimit?.resets_at,
|
|
1172
|
-
individualLimit?.reset_time,
|
|
1173
|
-
spendControl?.reset_at,
|
|
1174
|
-
spendControl?.resets_at,
|
|
1175
|
-
credits?.reset_at,
|
|
1176
|
-
credits?.resets_at,
|
|
1177
|
-
],
|
|
1178
|
-
individualLimit?.reset_after_seconds ?? spendControl?.reset_after_seconds,
|
|
1179
|
-
capturedAt,
|
|
1180
|
-
);
|
|
1181
|
-
if (
|
|
1182
|
-
limit === undefined ||
|
|
1183
|
-
used === undefined ||
|
|
1184
|
-
remaining === undefined ||
|
|
1185
|
-
limit <= 0
|
|
1186
|
-
)
|
|
1187
|
-
return undefined;
|
|
1188
|
-
const remainingPercent = Math.min(
|
|
1189
|
-
100,
|
|
1190
|
-
Math.max(0, (remaining / limit) * 100),
|
|
1191
|
-
);
|
|
1192
|
-
return resetAt === undefined
|
|
1193
|
-
? { remainingPercent }
|
|
1194
|
-
: { remainingPercent, resetAt };
|
|
1195
|
-
}
|
|
1196
|
-
|
|
1197
|
-
function normalizeBackendSnapshot(
|
|
1198
|
-
limitId: string,
|
|
1199
|
-
rateLimit: unknown,
|
|
1200
|
-
capturedAt: number,
|
|
1201
|
-
): NormalizedRateLimitSnapshot | undefined {
|
|
1202
|
-
if (rateLimit === null || rateLimit === undefined) return undefined;
|
|
1203
|
-
const details = assertObject(
|
|
1204
|
-
rateLimit,
|
|
1205
|
-
"rate limit",
|
|
1206
|
-
) as BackendRateLimitDetails;
|
|
1207
|
-
const primary = normalizeBackendWindow(details.primary_window, capturedAt);
|
|
1208
|
-
const secondary = normalizeBackendWindow(
|
|
1209
|
-
details.secondary_window,
|
|
1210
|
-
capturedAt,
|
|
1211
|
-
);
|
|
1212
|
-
if (!primary && !secondary) return undefined;
|
|
1213
|
-
return { limitId, primary, secondary };
|
|
1214
|
-
}
|
|
1215
|
-
|
|
1216
|
-
function normalizeBackendWindow(
|
|
1217
|
-
value: unknown,
|
|
1218
|
-
capturedAt: number,
|
|
1219
|
-
): NormalizedRateLimitWindow | undefined {
|
|
1220
|
-
if (value === null || value === undefined) return undefined;
|
|
1221
|
-
const window = assertObject(
|
|
1222
|
-
value,
|
|
1223
|
-
"rate-limit window",
|
|
1224
|
-
) as BackendWindowSnapshot;
|
|
1225
|
-
const usedPercent = asNumber(window.used_percent);
|
|
1226
|
-
if (usedPercent === undefined) return undefined;
|
|
1227
|
-
const resetAt = asResetTime(
|
|
1228
|
-
[
|
|
1229
|
-
window.reset_at,
|
|
1230
|
-
window.resets_at,
|
|
1231
|
-
window.reset_time,
|
|
1232
|
-
window.end_time,
|
|
1233
|
-
window.ends_at,
|
|
1234
|
-
window.expires_at,
|
|
1235
|
-
],
|
|
1236
|
-
window.reset_after_seconds,
|
|
1237
|
-
capturedAt,
|
|
1238
|
-
);
|
|
1239
|
-
return resetAt === undefined ? { usedPercent } : { usedPercent, resetAt };
|
|
1240
|
-
}
|
|
1241
|
-
|
|
1242
|
-
export function normalizeAppServerResponse(
|
|
1243
|
-
response: AppServerRateLimitResponse,
|
|
1244
|
-
_capturedAt: number,
|
|
1245
|
-
): CodexUsageReport {
|
|
1246
|
-
const snapshots: NormalizedRateLimitSnapshot[] = [];
|
|
1247
|
-
const addSnapshot = (raw: unknown, fallbackId: string) => {
|
|
1248
|
-
const snapshot = normalizeAppServerSnapshot(raw, fallbackId, _capturedAt);
|
|
1249
|
-
if (!snapshot) return;
|
|
1250
|
-
const existingIndex = snapshots.findIndex(
|
|
1251
|
-
(item) => item.limitId === snapshot.limitId,
|
|
1252
|
-
);
|
|
1253
|
-
if (existingIndex >= 0)
|
|
1254
|
-
snapshots[existingIndex] = mergeSnapshot(
|
|
1255
|
-
snapshots[existingIndex],
|
|
1256
|
-
snapshot,
|
|
1257
|
-
);
|
|
1258
|
-
else snapshots.push(snapshot);
|
|
1259
|
-
};
|
|
1260
|
-
|
|
1261
|
-
if (Array.isArray(response.rateLimits)) {
|
|
1262
|
-
for (const item of response.rateLimits) addSnapshot(item, "codex");
|
|
1263
|
-
} else {
|
|
1264
|
-
addSnapshot(response.rateLimits, "codex");
|
|
1265
|
-
}
|
|
1266
|
-
if (snapshots.length === 0) {
|
|
1267
|
-
throw new Error(
|
|
1268
|
-
"codex app-server returned no displayable rate-limit windows.",
|
|
1269
|
-
);
|
|
1270
|
-
}
|
|
1271
|
-
|
|
1272
|
-
return { snapshots };
|
|
1273
|
-
}
|
|
1274
|
-
|
|
1275
|
-
function normalizeAppServerSnapshot(
|
|
1276
|
-
raw: unknown,
|
|
1277
|
-
fallbackId: string,
|
|
1278
|
-
capturedAt: number,
|
|
1279
|
-
): NormalizedRateLimitSnapshot | undefined {
|
|
1280
|
-
if (raw === null || raw === undefined) return undefined;
|
|
1281
|
-
const snapshot = assertObject(
|
|
1282
|
-
raw,
|
|
1283
|
-
"app-server rate-limit snapshot",
|
|
1284
|
-
) as AppServerRateLimitSnapshot;
|
|
1285
|
-
const limitId = asString(snapshot.limitId) ?? fallbackId;
|
|
1286
|
-
if (normalizedUsageKey(limitId) !== CODEX_USAGE_LIMIT_ID) return undefined;
|
|
1287
|
-
const primary = normalizeAppServerWindow(snapshot.primary, capturedAt);
|
|
1288
|
-
const secondary = normalizeAppServerWindow(snapshot.secondary, capturedAt);
|
|
1289
|
-
if (!primary && !secondary) return undefined;
|
|
1290
|
-
return { limitId, primary, secondary };
|
|
1291
|
-
}
|
|
1292
|
-
|
|
1293
|
-
function normalizeAppServerWindow(
|
|
1294
|
-
value: unknown,
|
|
1295
|
-
capturedAt: number,
|
|
1296
|
-
): NormalizedRateLimitWindow | undefined {
|
|
1297
|
-
if (value === null || value === undefined) return undefined;
|
|
1298
|
-
const window = assertObject(
|
|
1299
|
-
value,
|
|
1300
|
-
"app-server rate-limit window",
|
|
1301
|
-
) as AppServerWindowSnapshot;
|
|
1302
|
-
const usedPercent = asNumber(window.usedPercent);
|
|
1303
|
-
if (usedPercent === undefined) return undefined;
|
|
1304
|
-
const resetAt = asResetTime(
|
|
1305
|
-
[
|
|
1306
|
-
window.resetAt,
|
|
1307
|
-
window.resetsAt,
|
|
1308
|
-
window.resetTime,
|
|
1309
|
-
window.endTime,
|
|
1310
|
-
window.endsAt,
|
|
1311
|
-
window.expiresAt,
|
|
1312
|
-
],
|
|
1313
|
-
window.resetAfterSeconds,
|
|
1314
|
-
capturedAt,
|
|
1315
|
-
);
|
|
1316
|
-
return resetAt === undefined ? { usedPercent } : { usedPercent, resetAt };
|
|
1317
|
-
}
|
|
1318
|
-
|
|
1319
|
-
function mergeSnapshot(
|
|
1320
|
-
left: NormalizedRateLimitSnapshot,
|
|
1321
|
-
right: NormalizedRateLimitSnapshot,
|
|
1322
|
-
): NormalizedRateLimitSnapshot {
|
|
1323
|
-
return {
|
|
1324
|
-
limitId: right.limitId || left.limitId,
|
|
1325
|
-
primary: right.primary ?? left.primary,
|
|
1326
|
-
secondary: right.secondary ?? left.secondary,
|
|
1327
|
-
};
|
|
1328
|
-
}
|
|
1329
|
-
|
|
1330
|
-
export function formatCodexUsageStatusline(
|
|
1331
|
-
report: CodexUsageReport,
|
|
1332
|
-
ctx: ExtensionContext,
|
|
1333
|
-
model?: CodexUsageModel,
|
|
1334
|
-
): string {
|
|
1335
|
-
const value = formatCodexUsageStatusValue(report, model);
|
|
1336
|
-
if (!value) return formatStatuslineText(ctx, "n/a", model);
|
|
1337
|
-
const snapshot = selectActiveUsageSnapshot(report, model);
|
|
1338
|
-
if (!snapshot?.primary || !snapshot.secondary)
|
|
1339
|
-
return formatStatuslineText(ctx, value, model);
|
|
1340
|
-
const [bar, countdown] = value.split(" ", 2);
|
|
1341
|
-
const barText = formatStatuslineBarText(
|
|
1342
|
-
ctx,
|
|
1343
|
-
bar ?? "",
|
|
1344
|
-
hasExhaustedQuotaWindow(report, model) ? "toolErrorBg" : "userMessageBg",
|
|
1345
|
-
model,
|
|
1346
|
-
);
|
|
1347
|
-
return countdown
|
|
1348
|
-
? `${barText} ${ctx.ui.theme.fg("dim", countdown)}`
|
|
1349
|
-
: barText;
|
|
1350
|
-
}
|
|
1351
|
-
|
|
1352
|
-
export function formatCodexUsageBar(
|
|
1353
|
-
report: CodexUsageReport,
|
|
1354
|
-
): string | undefined {
|
|
1355
|
-
return formatReportBar(report);
|
|
1356
|
-
}
|
|
1357
|
-
|
|
1358
|
-
export function formatCodexUsageStatusValue(
|
|
1359
|
-
report: CodexUsageReport,
|
|
1360
|
-
modelOrNow?: CodexUsageModel | number,
|
|
1361
|
-
now = Date.now(),
|
|
1362
|
-
): string | undefined {
|
|
1363
|
-
const model = typeof modelOrNow === "number" ? undefined : modelOrNow;
|
|
1364
|
-
const capturedNow = typeof modelOrNow === "number" ? modelOrNow : now;
|
|
1365
|
-
const snapshot = selectActiveUsageSnapshot(report, model);
|
|
1366
|
-
if (!snapshot || (!snapshot.primary && !snapshot.secondary)) {
|
|
1367
|
-
return formatCreditUsage(report.credits, capturedNow);
|
|
1368
|
-
}
|
|
1369
|
-
if (!snapshot.primary || !snapshot.secondary) {
|
|
1370
|
-
const window = snapshot.primary ?? snapshot.secondary;
|
|
1371
|
-
if (!window) return undefined;
|
|
1372
|
-
const percentage = `${Math.round(remainingPercent(window))}%`;
|
|
1373
|
-
const countdown = window.resetAt
|
|
1374
|
-
? formatResetCountdown(window.resetAt, capturedNow)
|
|
1375
|
-
: undefined;
|
|
1376
|
-
return countdown ? `${percentage} ${countdown}` : percentage;
|
|
1377
|
-
}
|
|
1378
|
-
const bar = formatDualLimitBar(snapshot.primary, snapshot.secondary);
|
|
1379
|
-
if (isQuotaWindowExhausted(snapshot.primary) && snapshot.primary?.resetAt) {
|
|
1380
|
-
const primaryCountdown = formatResetCountdown(
|
|
1381
|
-
snapshot.primary.resetAt,
|
|
1382
|
-
capturedNow,
|
|
1383
|
-
);
|
|
1384
|
-
const weeklyCountdown = snapshot.secondary?.resetAt
|
|
1385
|
-
? formatResetCountdown(snapshot.secondary.resetAt, capturedNow)
|
|
1386
|
-
: undefined;
|
|
1387
|
-
return weeklyCountdown
|
|
1388
|
-
? `${bar} ${primaryCountdown}/${weeklyCountdown}`
|
|
1389
|
-
: `${bar} ${primaryCountdown}`;
|
|
1390
|
-
}
|
|
1391
|
-
const countdown = formatWeeklyResetCountdown(report, model, capturedNow);
|
|
1392
|
-
return countdown ? `${bar} ${countdown}` : bar;
|
|
1393
|
-
}
|
|
1394
|
-
|
|
1395
|
-
function formatCreditUsage(
|
|
1396
|
-
credits: NormalizedCreditUsage | undefined,
|
|
1397
|
-
now: number,
|
|
1398
|
-
): string | undefined {
|
|
1399
|
-
if (!credits) return undefined;
|
|
1400
|
-
const percentage = `${Math.round(credits.remainingPercent)}%`;
|
|
1401
|
-
return credits.resetAt
|
|
1402
|
-
? `${percentage} ${formatResetCountdown(credits.resetAt, now)}`
|
|
1403
|
-
: percentage;
|
|
1404
|
-
}
|
|
1405
|
-
|
|
1406
|
-
export function formatWeeklyResetCountdown(
|
|
1407
|
-
report: CodexUsageReport,
|
|
1408
|
-
modelOrNow?: CodexUsageModel | number,
|
|
1409
|
-
now = Date.now(),
|
|
1410
|
-
): string | undefined {
|
|
1411
|
-
const model = typeof modelOrNow === "number" ? undefined : modelOrNow;
|
|
1412
|
-
const capturedNow = typeof modelOrNow === "number" ? modelOrNow : now;
|
|
1413
|
-
const snapshot = selectActiveUsageSnapshot(report, model);
|
|
1414
|
-
const resetAt = weeklyWindow(snapshot)?.resetAt;
|
|
1415
|
-
if (resetAt === undefined) return undefined;
|
|
1416
|
-
return formatResetCountdown(resetAt, capturedNow);
|
|
1417
|
-
}
|
|
1418
|
-
|
|
1419
|
-
export function formatResetCountdown(
|
|
1420
|
-
resetAt: number,
|
|
1421
|
-
now = Date.now(),
|
|
1422
|
-
): string {
|
|
1423
|
-
const remainingMs = Math.max(0, resetAt - now);
|
|
1424
|
-
if (remainingMs > DAY_MS) {
|
|
1425
|
-
const dayTenths = Math.max(10, Math.ceil(remainingMs / DAY_TENTH_MS));
|
|
1426
|
-
return `${formatTenths(dayTenths)}d`;
|
|
1427
|
-
}
|
|
1428
|
-
if (remainingMs >= HOUR_MS) {
|
|
1429
|
-
const hourTenths = Math.max(10, Math.ceil(remainingMs / HOUR_TENTH_MS));
|
|
1430
|
-
return `${formatTenths(hourTenths)}h`;
|
|
1431
|
-
}
|
|
1432
|
-
if (remainingMs >= MINUTE_MS)
|
|
1433
|
-
return `${Math.floor(remainingMs / MINUTE_MS)}m`;
|
|
1434
|
-
return `${Math.floor(remainingMs / SECOND_MS)}s`;
|
|
1435
|
-
}
|
|
1436
|
-
|
|
1437
|
-
export function nextResetCountdownDelayMs(
|
|
1438
|
-
report: CodexUsageReport,
|
|
1439
|
-
now = Date.now(),
|
|
1440
|
-
model?: CodexUsageModel,
|
|
1441
|
-
): number | undefined {
|
|
1442
|
-
const snapshot = selectActiveUsageSnapshot(report, model);
|
|
1443
|
-
const hasRateLimitWindow = Boolean(snapshot?.primary || snapshot?.secondary);
|
|
1444
|
-
const resetTimes = [
|
|
1445
|
-
hasRateLimitWindow ? weeklyWindow(snapshot)?.resetAt : report.credits?.resetAt,
|
|
1446
|
-
];
|
|
1447
|
-
if (snapshot?.secondary && isQuotaWindowExhausted(snapshot.primary)) {
|
|
1448
|
-
resetTimes.push(snapshot.primary?.resetAt);
|
|
1449
|
-
}
|
|
1450
|
-
const delays = resetTimes
|
|
1451
|
-
.filter((resetAt): resetAt is number => resetAt !== undefined)
|
|
1452
|
-
.map((resetAt) => nextResetCountdownDelayForRemainingMs(resetAt - now))
|
|
1453
|
-
.filter((delay): delay is number => delay !== undefined);
|
|
1454
|
-
return delays.length > 0 ? Math.min(...delays) : undefined;
|
|
1455
|
-
}
|
|
1456
|
-
|
|
1457
|
-
export function nextResetCountdownDelayForRemainingMs(
|
|
1458
|
-
remainingMs: number,
|
|
1459
|
-
): number | undefined {
|
|
1460
|
-
if (remainingMs <= 0) return undefined;
|
|
1461
|
-
if (remainingMs > DAY_MS) {
|
|
1462
|
-
const dayTenths = Math.max(10, Math.ceil(remainingMs / DAY_TENTH_MS));
|
|
1463
|
-
return Math.max(1, remainingMs - (dayTenths - 1) * DAY_TENTH_MS);
|
|
1464
|
-
}
|
|
1465
|
-
if (remainingMs >= HOUR_MS) {
|
|
1466
|
-
const hourTenths = Math.max(10, Math.ceil(remainingMs / HOUR_TENTH_MS));
|
|
1467
|
-
if (hourTenths === 10) return Math.max(1, remainingMs - HOUR_MS + 1);
|
|
1468
|
-
return Math.max(1, remainingMs - (hourTenths - 1) * HOUR_TENTH_MS);
|
|
1469
|
-
}
|
|
1470
|
-
if (remainingMs >= MINUTE_MS) {
|
|
1471
|
-
return Math.max(
|
|
1472
|
-
1,
|
|
1473
|
-
remainingMs - Math.floor(remainingMs / MINUTE_MS) * MINUTE_MS + 1,
|
|
1474
|
-
);
|
|
1475
|
-
}
|
|
1476
|
-
return Math.max(
|
|
1477
|
-
1,
|
|
1478
|
-
remainingMs - Math.floor(remainingMs / SECOND_MS) * SECOND_MS + 1,
|
|
1479
|
-
);
|
|
1480
|
-
}
|
|
1481
|
-
|
|
1482
|
-
function formatTenths(value: number): string {
|
|
1483
|
-
return value % 10 === 0 ? String(value / 10) : (value / 10).toFixed(1);
|
|
1484
|
-
}
|
|
1485
|
-
|
|
1486
|
-
function formatReportBar(
|
|
1487
|
-
report: CodexUsageReport,
|
|
1488
|
-
model?: CodexUsageModel,
|
|
1489
|
-
): string | undefined {
|
|
1490
|
-
const snapshot = selectActiveUsageSnapshot(report, model);
|
|
1491
|
-
if (!snapshot || (!snapshot.primary && !snapshot.secondary)) return undefined;
|
|
1492
|
-
return formatAdaptiveLimitBar(snapshot.primary, snapshot.secondary);
|
|
1493
|
-
}
|
|
1494
|
-
|
|
1495
|
-
function formatStatuslineText(
|
|
1496
|
-
ctx: ExtensionContext,
|
|
1497
|
-
value: string,
|
|
1498
|
-
_model?: CodexUsageModel,
|
|
1499
|
-
): string {
|
|
1500
|
-
const label = ctx.ui.theme.fg("accent", DEFAULT_STATUS_LABEL_TEXT);
|
|
1501
|
-
return `${label} ${ctx.ui.theme.fg("dim", value)}`;
|
|
1502
|
-
}
|
|
1503
|
-
|
|
1504
|
-
function formatStatuslineBarText(
|
|
1505
|
-
ctx: ExtensionContext,
|
|
1506
|
-
bar: string,
|
|
1507
|
-
background: "userMessageBg" | "toolErrorBg",
|
|
1508
|
-
_model?: CodexUsageModel,
|
|
1509
|
-
): string {
|
|
1510
|
-
const label = ctx.ui.theme.fg("accent", DEFAULT_STATUS_LABEL_TEXT);
|
|
1511
|
-
const value = ctx.ui.theme.bg(background, ctx.ui.theme.fg("dim", bar));
|
|
1512
|
-
return `${label} ${value}`;
|
|
1513
|
-
}
|
|
1514
|
-
|
|
1515
|
-
export function formatCodexUsageLoadingBar(frame: number): string {
|
|
1516
|
-
const totalParts = DUAL_BAR_WIDTH * 2;
|
|
1517
|
-
const cycleFrames = (totalParts - 1) * 2;
|
|
1518
|
-
const finiteFrame = Number.isFinite(frame) ? frame : 0;
|
|
1519
|
-
const cycleFrame = Math.abs(Math.trunc(finiteFrame)) % cycleFrames;
|
|
1520
|
-
const primaryPart =
|
|
1521
|
-
cycleFrame < totalParts ? cycleFrame : cycleFrames - cycleFrame;
|
|
1522
|
-
const secondaryPart = totalParts - primaryPart - 1;
|
|
1523
|
-
const masks = Array<number>(DUAL_BAR_WIDTH).fill(0);
|
|
1524
|
-
const primaryCell = Math.floor(primaryPart / 2);
|
|
1525
|
-
const secondaryCell = Math.floor(secondaryPart / 2);
|
|
1526
|
-
masks[primaryCell] |= primaryPart % 2 === 0 ? 1 : 2;
|
|
1527
|
-
masks[secondaryCell] |= secondaryPart % 2 === 0 ? 4 : 8;
|
|
1528
|
-
return masks.map((mask) => DUAL_BAR_CHARS[mask]).join("");
|
|
1529
|
-
}
|
|
1530
|
-
|
|
1531
|
-
function formatStatuslineLoading(
|
|
1532
|
-
ctx: ExtensionContext,
|
|
1533
|
-
frame: number,
|
|
1534
|
-
model?: CodexUsageModel,
|
|
1535
|
-
): string {
|
|
1536
|
-
return formatStatuslineBarText(
|
|
1537
|
-
ctx,
|
|
1538
|
-
formatCodexUsageLoadingBar(frame),
|
|
1539
|
-
"userMessageBg",
|
|
1540
|
-
model,
|
|
1541
|
-
);
|
|
1542
|
-
}
|
|
1543
|
-
|
|
1544
|
-
function formatStatuslineProblem(
|
|
1545
|
-
ctx: ExtensionContext,
|
|
1546
|
-
unavailable: boolean,
|
|
1547
|
-
_model?: CodexUsageModel,
|
|
1548
|
-
): string {
|
|
1549
|
-
const label = ctx.ui.theme.fg("accent", DEFAULT_STATUS_LABEL_TEXT);
|
|
1550
|
-
const value = unavailable
|
|
1551
|
-
? ctx.ui.theme.fg("muted", "n/a")
|
|
1552
|
-
: ctx.ui.theme.fg("error", "error");
|
|
1553
|
-
return `${label} ${value}`;
|
|
1554
|
-
}
|
|
1555
|
-
|
|
1556
|
-
export function isUsageUnavailable(errors: UsageQueryError[]): boolean {
|
|
1557
|
-
return errors.length > 0 && errors.every(isUnavailableError);
|
|
1558
|
-
}
|
|
1559
|
-
|
|
1560
|
-
function isUnavailableError(error: UsageQueryError): boolean {
|
|
1561
|
-
const message = error.message.toLowerCase();
|
|
1562
|
-
return (
|
|
1563
|
-
message.includes("no pi openai codex subscription auth") ||
|
|
1564
|
-
message.includes("no displayable rate-limit windows") ||
|
|
1565
|
-
message.includes("returned no displayable rate-limit windows") ||
|
|
1566
|
-
message.includes("returned 401") ||
|
|
1567
|
-
message.includes("returned 403") ||
|
|
1568
|
-
message.includes("unauthorized") ||
|
|
1569
|
-
message.includes("forbidden") ||
|
|
1570
|
-
message.includes("subscription") ||
|
|
1571
|
-
message.includes("no active plan") ||
|
|
1572
|
-
message.includes("plan unavailable") ||
|
|
1573
|
-
message.includes("quota unavailable") ||
|
|
1574
|
-
message.includes("rate limits unavailable")
|
|
1575
|
-
);
|
|
1576
|
-
}
|
|
1577
|
-
|
|
1578
|
-
function normalizedUsageKey(value: string | undefined): string | undefined {
|
|
1579
|
-
const key = value
|
|
1580
|
-
?.toLowerCase()
|
|
1581
|
-
.replace(/[^a-z0-9]+/g, "-")
|
|
1582
|
-
.replace(/^-+|-+$/g, "");
|
|
1583
|
-
return key || undefined;
|
|
1584
|
-
}
|
|
1585
|
-
|
|
1586
|
-
function formatAdaptiveLimitBar(
|
|
1587
|
-
primary: NormalizedRateLimitWindow | undefined,
|
|
1588
|
-
secondary: NormalizedRateLimitWindow | undefined,
|
|
1589
|
-
): string {
|
|
1590
|
-
if (!primary || !secondary) return formatSingleLimitBar(primary ?? secondary);
|
|
1591
|
-
return formatDualLimitBar(primary, secondary);
|
|
1592
|
-
}
|
|
1593
|
-
|
|
1594
|
-
function formatSingleLimitBar(
|
|
1595
|
-
window: NormalizedRateLimitWindow | undefined,
|
|
1596
|
-
): string {
|
|
1597
|
-
const filled = filledParts(window, DUAL_BAR_WIDTH * 4);
|
|
1598
|
-
const partMasks = [1, 4, 2, 8];
|
|
1599
|
-
let value = "";
|
|
1600
|
-
for (let index = 0; index < DUAL_BAR_WIDTH; index++) {
|
|
1601
|
-
const cellParts = Math.min(4, Math.max(0, filled - index * 4));
|
|
1602
|
-
let mask = 0;
|
|
1603
|
-
for (let part = 0; part < cellParts; part++) mask |= partMasks[part] ?? 0;
|
|
1604
|
-
value += DUAL_BAR_CHARS[mask];
|
|
1605
|
-
}
|
|
1606
|
-
return value;
|
|
1607
|
-
}
|
|
1608
|
-
|
|
1609
|
-
function formatDualLimitBar(
|
|
1610
|
-
primary: NormalizedRateLimitWindow,
|
|
1611
|
-
secondary: NormalizedRateLimitWindow,
|
|
1612
|
-
): string {
|
|
1613
|
-
const primaryParts = filledTwentieths(primary);
|
|
1614
|
-
const secondaryParts = filledTwentieths(secondary);
|
|
1615
|
-
let value = "";
|
|
1616
|
-
for (let index = 0; index < DUAL_BAR_WIDTH; index++) {
|
|
1617
|
-
const leftPart = index * 2 + 1;
|
|
1618
|
-
const rightPart = leftPart + 1;
|
|
1619
|
-
let mask = 0;
|
|
1620
|
-
if (primaryParts >= leftPart) mask |= 1;
|
|
1621
|
-
if (primaryParts >= rightPart) mask |= 2;
|
|
1622
|
-
if (secondaryParts >= leftPart) mask |= 4;
|
|
1623
|
-
if (secondaryParts >= rightPart) mask |= 8;
|
|
1624
|
-
value += DUAL_BAR_CHARS[mask];
|
|
1625
|
-
}
|
|
1626
|
-
return value;
|
|
1627
|
-
}
|
|
1628
|
-
|
|
1629
|
-
function filledTwentieths(
|
|
1630
|
-
window: NormalizedRateLimitWindow | undefined,
|
|
1631
|
-
): number {
|
|
1632
|
-
return filledParts(window, 20);
|
|
1633
|
-
}
|
|
1634
|
-
|
|
1635
|
-
function filledParts(
|
|
1636
|
-
window: NormalizedRateLimitWindow | undefined,
|
|
1637
|
-
totalParts: number,
|
|
1638
|
-
): number {
|
|
1639
|
-
if (!window) return 0;
|
|
1640
|
-
const remaining = remainingPercent(window);
|
|
1641
|
-
if (remaining <= 0) return 0;
|
|
1642
|
-
return Math.max(1, Math.round(remaining / (100 / totalParts)));
|
|
1643
|
-
}
|
|
1644
|
-
|
|
1645
|
-
function remainingPercent(window: NormalizedRateLimitWindow): number {
|
|
1646
|
-
return 100 - clampPercent(window.usedPercent);
|
|
1647
|
-
}
|
|
1648
|
-
|
|
1649
|
-
function isQuotaWindowExhausted(
|
|
1650
|
-
window: NormalizedRateLimitWindow | undefined,
|
|
1651
|
-
): boolean {
|
|
1652
|
-
return window !== undefined && remainingPercent(window) <= 0;
|
|
1653
|
-
}
|
|
1654
|
-
|
|
1655
|
-
function hasExhaustedQuotaWindow(
|
|
1656
|
-
report: CodexUsageReport,
|
|
1657
|
-
model?: CodexUsageModel,
|
|
1658
|
-
): boolean {
|
|
1659
|
-
const snapshot = selectActiveUsageSnapshot(report, model);
|
|
1660
|
-
return (
|
|
1661
|
-
isQuotaWindowExhausted(snapshot?.primary) ||
|
|
1662
|
-
isQuotaWindowExhausted(snapshot?.secondary)
|
|
1663
|
-
);
|
|
1664
|
-
}
|
|
1665
|
-
|
|
1666
|
-
export function canReuseCachedReport(
|
|
1667
|
-
report: CodexUsageReport,
|
|
1668
|
-
model: CodexUsageModel | undefined,
|
|
1669
|
-
): boolean {
|
|
1670
|
-
return (
|
|
1671
|
-
selectActiveUsageSnapshot(report, model) !== undefined ||
|
|
1672
|
-
report.credits !== undefined
|
|
1673
|
-
);
|
|
1674
|
-
}
|
|
1675
|
-
|
|
1676
|
-
export function isFullyAvailableReport(
|
|
1677
|
-
report: CodexUsageReport,
|
|
1678
|
-
model?: CodexUsageModel,
|
|
1679
|
-
): boolean {
|
|
1680
|
-
const snapshot = selectActiveUsageSnapshot(report, model);
|
|
1681
|
-
const windows = [snapshot?.primary, snapshot?.secondary].filter(
|
|
1682
|
-
(window): window is NormalizedRateLimitWindow => window !== undefined,
|
|
1683
|
-
);
|
|
1684
|
-
return (
|
|
1685
|
-
windows.length > 0 &&
|
|
1686
|
-
windows.every((window) => clampPercent(window.usedPercent) === 0)
|
|
1687
|
-
);
|
|
1688
|
-
}
|
|
1689
|
-
|
|
1690
|
-
function weeklyWindow(
|
|
1691
|
-
snapshot: NormalizedRateLimitSnapshot | undefined,
|
|
1692
|
-
): NormalizedRateLimitWindow | undefined {
|
|
1693
|
-
return snapshot?.secondary ?? snapshot?.primary;
|
|
1694
|
-
}
|
|
1695
|
-
|
|
1696
|
-
function selectActiveUsageSnapshot(
|
|
1697
|
-
report: CodexUsageReport,
|
|
1698
|
-
_model: CodexUsageModel | undefined,
|
|
1699
|
-
): NormalizedRateLimitSnapshot | undefined {
|
|
1700
|
-
return selectUsageSnapshot(report, CODEX_USAGE_LIMIT_ID);
|
|
1701
|
-
}
|
|
1702
|
-
|
|
1703
|
-
function selectUsageSnapshot(
|
|
1704
|
-
report: CodexUsageReport,
|
|
1705
|
-
limitId: string,
|
|
1706
|
-
): NormalizedRateLimitSnapshot | undefined {
|
|
1707
|
-
const normalizedLimitId = normalizedUsageKey(limitId);
|
|
1708
|
-
return report.snapshots.find(
|
|
1709
|
-
(snapshot) => normalizedUsageKey(snapshot.limitId) === normalizedLimitId,
|
|
1710
|
-
);
|
|
1711
|
-
}
|
|
1712
|
-
|
|
1713
|
-
function clampPercent(value: number): number {
|
|
1714
|
-
if (!Number.isFinite(value)) return 0;
|
|
1715
|
-
return Math.min(100, Math.max(0, value));
|
|
1716
|
-
}
|
|
1717
|
-
|
|
1718
|
-
function parseJsonObject(
|
|
1719
|
-
text: string,
|
|
1720
|
-
description: string,
|
|
1721
|
-
): Record<string, unknown> {
|
|
1722
|
-
let parsed: unknown;
|
|
1723
|
-
try {
|
|
1724
|
-
parsed = JSON.parse(text) as unknown;
|
|
1725
|
-
} catch (error) {
|
|
1726
|
-
throw new Error(
|
|
1727
|
-
`${description} was not valid JSON: ${errorMessage(error)}`,
|
|
1728
|
-
);
|
|
1729
|
-
}
|
|
1730
|
-
return assertObject(parsed, description);
|
|
1731
|
-
}
|
|
1732
|
-
|
|
1733
|
-
function assertObject(
|
|
1734
|
-
value: unknown,
|
|
1735
|
-
description: string,
|
|
1736
|
-
): Record<string, unknown> {
|
|
1737
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
1738
|
-
throw new Error(`${description} was not an object.`);
|
|
1739
|
-
}
|
|
1740
|
-
return value as Record<string, unknown>;
|
|
1741
|
-
}
|
|
1742
|
-
|
|
1743
|
-
function asString(value: unknown): string | undefined {
|
|
1744
|
-
return typeof value === "string" ? value : undefined;
|
|
1745
|
-
}
|
|
1746
|
-
|
|
1747
|
-
function asNumber(value: unknown): number | undefined {
|
|
1748
|
-
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
1749
|
-
if (typeof value === "string" && value.trim()) {
|
|
1750
|
-
const parsed = Number(value);
|
|
1751
|
-
return Number.isFinite(parsed) ? parsed : undefined;
|
|
1752
|
-
}
|
|
1753
|
-
return undefined;
|
|
1754
|
-
}
|
|
1755
|
-
|
|
1756
|
-
function asResetTime(
|
|
1757
|
-
absoluteValues: unknown[],
|
|
1758
|
-
relativeSeconds: unknown,
|
|
1759
|
-
capturedAt: number,
|
|
1760
|
-
): number | undefined {
|
|
1761
|
-
for (const value of absoluteValues) {
|
|
1762
|
-
const timestamp = asTimestampMs(value);
|
|
1763
|
-
if (timestamp !== undefined) return timestamp;
|
|
1764
|
-
}
|
|
1765
|
-
const seconds = asNumber(relativeSeconds);
|
|
1766
|
-
if (seconds === undefined || seconds < 0) return undefined;
|
|
1767
|
-
return capturedAt + seconds * SECOND_MS;
|
|
1768
|
-
}
|
|
1769
|
-
|
|
1770
|
-
function asTimestampMs(value: unknown): number | undefined {
|
|
1771
|
-
if (typeof value === "number" && Number.isFinite(value)) {
|
|
1772
|
-
if (value <= 0) return undefined;
|
|
1773
|
-
return value < 10_000_000_000 ? value * SECOND_MS : value;
|
|
1774
|
-
}
|
|
1775
|
-
if (typeof value === "string" && value.trim()) {
|
|
1776
|
-
const numeric = Number(value);
|
|
1777
|
-
if (Number.isFinite(numeric)) return asTimestampMs(numeric);
|
|
1778
|
-
const parsed = Date.parse(value);
|
|
1779
|
-
return Number.isFinite(parsed) ? parsed : undefined;
|
|
1780
|
-
}
|
|
1781
|
-
return undefined;
|
|
1782
|
-
}
|
|
1783
|
-
|
|
1784
|
-
function hasHeader(headers: Record<string, string>, name: string): boolean {
|
|
1785
|
-
return Object.keys(headers).some(
|
|
1786
|
-
(key) => key.toLowerCase() === name.toLowerCase(),
|
|
1787
|
-
);
|
|
1788
|
-
}
|
|
1789
|
-
|
|
1790
|
-
function redactErrorBody(body: string): string {
|
|
1791
|
-
return truncateEnd(
|
|
1792
|
-
body
|
|
1793
|
-
.replace(/Bearer\s+[A-Za-z0-9._~+/=-]+/gi, "Bearer <redacted>")
|
|
1794
|
-
.replace(/"access_token"\s*:\s*"[^"]+"/gi, '"access_token":"<redacted>"')
|
|
1795
|
-
.trim(),
|
|
1796
|
-
MAX_ERROR_BODY_CHARS,
|
|
1797
|
-
);
|
|
1798
|
-
}
|
|
1799
|
-
|
|
1800
|
-
function truncateEnd(value: string, maxChars: number): string {
|
|
1801
|
-
if (value.length <= maxChars) return value;
|
|
1802
|
-
return `${value.slice(0, maxChars - 1)}…`;
|
|
1803
|
-
}
|
|
1804
|
-
|
|
1805
|
-
function errorMessage(error: unknown): string {
|
|
1806
|
-
return error instanceof Error ? error.message : String(error);
|
|
1807
|
-
}
|
|
1
|
+
/** Domain: package entrypoint. Owns: public re-exports. Excludes: composition and behavior. */
|
|
2
|
+
export { default } from "./lib/extension.ts";
|
|
3
|
+
export { LEADER_INTERVAL_MS, TAKEOVER_AFTER_MS, MIN_ATTEMPT_GAP_MS, readState, writeState, claimRefresh, ownsRefreshClaim, publishRefresh, nextRefreshAt, isRefreshDue, failureBackoffMs, tryAcquireLock } from "./lib/usage-store.ts";
|
|
4
|
+
export type { SharedState, RefreshClaim, RefreshOutcome } from "./lib/usage-store.ts";
|
|
5
|
+
export { normalizeBackendPayload, normalizeAppServerResponse, isUsageUnavailable, canReuseCachedReport, isFullyAvailableReport } from "./lib/usage.ts";
|
|
6
|
+
export type { CodexUsageModel, CodexUsageReport, NormalizedCreditUsage, NormalizedRateLimitSnapshot, NormalizedRateLimitWindow, UsageQueryError } from "./lib/usage.ts";
|
|
7
|
+
export { formatCodexUsageStatusline, formatCodexUsageBar, formatCodexUsageStatusValue, formatWeeklyResetCountdown, formatResetCountdown, nextResetCountdownDelayMs, nextResetCountdownDelayForRemainingMs, formatCodexUsageLoadingBar } from "./lib/status-format.ts";
|
|
8
|
+
export { isStaleExtensionContextError } from "./lib/status.ts";
|