@llblab/pi-kit 0.25.0 → 0.26.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.
Files changed (104) hide show
  1. package/BACKLOG.md +5 -1
  2. package/CHANGELOG.md +6 -0
  3. package/README.md +9 -7
  4. package/node_modules/@llblab/pi-actors/AGENTS.md +2 -0
  5. package/node_modules/@llblab/pi-actors/CHANGELOG.md +4 -1
  6. package/node_modules/@llblab/pi-actors/LICENSE +21 -0
  7. package/node_modules/@llblab/pi-actors/README.md +1 -1
  8. package/node_modules/@llblab/pi-actors/docs/coordinator-delivery.md +1 -1
  9. package/node_modules/@llblab/pi-actors/package.json +4 -3
  10. package/node_modules/@llblab/pi-claude-usage/AGENTS.md +6 -3
  11. package/node_modules/@llblab/pi-claude-usage/BACKLOG.md +2 -1
  12. package/node_modules/@llblab/pi-claude-usage/CHANGELOG.md +8 -0
  13. package/node_modules/@llblab/pi-claude-usage/README.md +48 -3
  14. package/node_modules/@llblab/pi-claude-usage/index.ts +8 -1159
  15. package/node_modules/@llblab/pi-claude-usage/lib/extension.ts +30 -0
  16. package/node_modules/@llblab/pi-claude-usage/lib/fast.ts +24 -0
  17. package/node_modules/@llblab/pi-claude-usage/lib/query.ts +146 -0
  18. package/node_modules/@llblab/pi-claude-usage/lib/status-format.ts +297 -0
  19. package/node_modules/@llblab/pi-claude-usage/lib/status.ts +366 -0
  20. package/node_modules/@llblab/pi-claude-usage/lib/telegram.ts +44 -0
  21. package/node_modules/@llblab/pi-claude-usage/lib/usage-store.ts +221 -0
  22. package/node_modules/@llblab/pi-claude-usage/lib/usage.ts +128 -0
  23. package/node_modules/@llblab/pi-claude-usage/package.json +9 -5
  24. package/node_modules/@llblab/pi-clean-room/AGENTS.md +1 -0
  25. package/node_modules/@llblab/pi-clean-room/CHANGELOG.md +5 -0
  26. package/node_modules/@llblab/pi-clean-room/LICENSE +21 -0
  27. package/node_modules/@llblab/pi-clean-room/README.md +1 -1
  28. package/node_modules/@llblab/pi-clean-room/package.json +3 -2
  29. package/node_modules/@llblab/pi-codex-usage/AGENTS.md +9 -6
  30. package/node_modules/@llblab/pi-codex-usage/BACKLOG.md +2 -1
  31. package/node_modules/@llblab/pi-codex-usage/CHANGELOG.md +17 -0
  32. package/node_modules/@llblab/pi-codex-usage/README.md +75 -17
  33. package/node_modules/@llblab/pi-codex-usage/index.ts +8 -1602
  34. package/node_modules/@llblab/pi-codex-usage/lib/extension.ts +25 -0
  35. package/node_modules/@llblab/pi-codex-usage/lib/fast.ts +23 -0
  36. package/node_modules/@llblab/pi-codex-usage/lib/query.ts +368 -0
  37. package/node_modules/@llblab/pi-codex-usage/lib/status-format.ts +347 -0
  38. package/node_modules/@llblab/pi-codex-usage/lib/status.ts +435 -0
  39. package/node_modules/@llblab/pi-codex-usage/lib/telegram.ts +45 -0
  40. package/node_modules/@llblab/pi-codex-usage/lib/usage-store.ts +229 -0
  41. package/node_modules/@llblab/pi-codex-usage/lib/usage.ts +425 -0
  42. package/node_modules/@llblab/pi-codex-usage/package.json +11 -6
  43. package/node_modules/@llblab/pi-command-fast/AGENTS.md +7 -0
  44. package/node_modules/@llblab/pi-command-fast/BACKLOG.md +9 -0
  45. package/node_modules/@llblab/pi-command-fast/CHANGELOG.md +7 -0
  46. package/node_modules/@llblab/pi-command-fast/LICENSE +21 -0
  47. package/node_modules/@llblab/pi-command-fast/README.md +42 -0
  48. package/node_modules/@llblab/pi-command-fast/dist/command.d.ts +8 -0
  49. package/node_modules/@llblab/pi-command-fast/dist/command.js +52 -0
  50. package/node_modules/@llblab/pi-command-fast/dist/index.d.ts +3 -0
  51. package/node_modules/@llblab/pi-command-fast/dist/index.js +3 -0
  52. package/node_modules/@llblab/pi-command-fast/dist/models-json.d.ts +10 -0
  53. package/node_modules/@llblab/pi-command-fast/dist/models-json.js +81 -0
  54. package/node_modules/@llblab/pi-command-fast/package.json +49 -0
  55. package/node_modules/@llblab/pi-grow-loop/AGENTS.md +1 -0
  56. package/node_modules/@llblab/pi-grow-loop/CHANGELOG.md +4 -1
  57. package/node_modules/@llblab/pi-grow-loop/LICENSE +21 -0
  58. package/node_modules/@llblab/pi-grow-loop/README.md +1 -1
  59. package/node_modules/@llblab/pi-grow-loop/package.json +3 -2
  60. package/node_modules/@llblab/pi-state-flow/AGENTS.md +6 -5
  61. package/node_modules/@llblab/pi-state-flow/BACKLOG.md +3 -2
  62. package/node_modules/@llblab/pi-state-flow/CHANGELOG.md +7 -1
  63. package/node_modules/@llblab/pi-state-flow/LICENSE +21 -0
  64. package/node_modules/@llblab/pi-state-flow/README.md +5 -5
  65. package/node_modules/@llblab/pi-state-flow/dist/lib/compaction.d.ts +1 -1
  66. package/node_modules/@llblab/pi-state-flow/dist/lib/compaction.js +1 -1
  67. package/node_modules/@llblab/pi-state-flow/dist/lib/extension.js +238 -46
  68. package/node_modules/@llblab/pi-state-flow/dist/lib/git.d.ts +2 -2
  69. package/node_modules/@llblab/pi-state-flow/dist/lib/git.js +16 -5
  70. package/node_modules/@llblab/pi-state-flow/dist/lib/session.d.ts +10 -1
  71. package/node_modules/@llblab/pi-state-flow/dist/lib/session.js +60 -1
  72. package/node_modules/@llblab/pi-state-flow/dist/lib/snapshot.d.ts +6 -0
  73. package/node_modules/@llblab/pi-state-flow/dist/lib/snapshot.js +8 -5
  74. package/node_modules/@llblab/pi-state-flow/dist/package.json +10 -9
  75. package/node_modules/@llblab/pi-state-flow/docs/architecture.md +11 -7
  76. package/node_modules/@llblab/pi-state-flow/docs/compatibility.md +2 -2
  77. package/node_modules/@llblab/pi-state-flow/docs/fork-contract.md +4 -2
  78. package/node_modules/@llblab/pi-state-flow/docs/usage.md +14 -13
  79. package/node_modules/@llblab/pi-state-flow/lib/compaction.ts +2 -2
  80. package/node_modules/@llblab/pi-state-flow/lib/extension.ts +221 -46
  81. package/node_modules/@llblab/pi-state-flow/lib/git.ts +14 -5
  82. package/node_modules/@llblab/pi-state-flow/lib/session.ts +52 -1
  83. package/node_modules/@llblab/pi-state-flow/lib/snapshot.ts +7 -5
  84. package/node_modules/@llblab/pi-state-flow/package.json +10 -9
  85. package/node_modules/jsonc-parser/CHANGELOG.md +76 -0
  86. package/node_modules/jsonc-parser/LICENSE.md +21 -0
  87. package/node_modules/jsonc-parser/README.md +364 -0
  88. package/node_modules/jsonc-parser/SECURITY.md +41 -0
  89. package/node_modules/jsonc-parser/lib/esm/impl/edit.js +185 -0
  90. package/node_modules/jsonc-parser/lib/esm/impl/format.js +261 -0
  91. package/node_modules/jsonc-parser/lib/esm/impl/parser.js +659 -0
  92. package/node_modules/jsonc-parser/lib/esm/impl/scanner.js +443 -0
  93. package/node_modules/jsonc-parser/lib/esm/impl/string-intern.js +29 -0
  94. package/node_modules/jsonc-parser/lib/esm/main.d.ts +351 -0
  95. package/node_modules/jsonc-parser/lib/esm/main.js +178 -0
  96. package/node_modules/jsonc-parser/lib/umd/impl/edit.js +201 -0
  97. package/node_modules/jsonc-parser/lib/umd/impl/format.js +275 -0
  98. package/node_modules/jsonc-parser/lib/umd/impl/parser.js +682 -0
  99. package/node_modules/jsonc-parser/lib/umd/impl/scanner.js +456 -0
  100. package/node_modules/jsonc-parser/lib/umd/impl/string-intern.js +42 -0
  101. package/node_modules/jsonc-parser/lib/umd/main.d.ts +351 -0
  102. package/node_modules/jsonc-parser/lib/umd/main.js +194 -0
  103. package/node_modules/jsonc-parser/package.json +37 -0
  104. package/package.json +7 -7
@@ -1,1159 +1,8 @@
1
- import { randomUUID } from "node:crypto";
2
- import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
3
- import { join } from "node:path";
4
- import { DatabaseSync } from "node:sqlite";
5
-
6
- import {
7
- type ExtensionAPI,
8
- type ExtensionContext,
9
- getAgentDir,
10
- } from "@earendil-works/pi-coding-agent";
11
-
12
- const ANTHROPIC_PROVIDER_ID = "anthropic";
13
- const CLAUDE_USAGE_EXTENSION_ID = "@llblab/pi-claude-usage";
14
- const CLAUDE_USAGE_URL = "https://api.anthropic.com/api/oauth/usage";
15
- const ANTHROPIC_OAUTH_BETA = "oauth-2025-04-20";
16
- const DEFAULT_TIMEOUT_MS = 15_000;
17
- const SECOND_MS = 1000;
18
- const MINUTE_MS = 60 * SECOND_MS;
19
- const HOUR_MS = 60 * MINUTE_MS;
20
- const HOUR_TENTH_MS = 6 * MINUTE_MS;
21
- const DAY_MS = 24 * HOUR_MS;
22
- const DAY_TENTH_MS = 144 * MINUTE_MS;
23
- /** How often an instance re-reads the shared file to redraw fresh data. */
24
- const MAX_TICK_MS = 30 * SECOND_MS;
25
- const MIN_TICK_MS = SECOND_MS;
26
- const TAKEOVER_JITTER_MS = 2 * SECOND_MS;
27
- /** A report older than this is no longer shown as current. */
28
- const STALE_REPORT_MAX_AGE_MS = HOUR_MS;
29
- const LOADING_FRAME_MS = 30;
30
- const REDRAW_BLINK_MS = 150;
31
- const STATUS_KEY = "aa-claude-usage";
32
- const MAX_ERROR_BODY_CHARS = 600;
33
- const STATUS_LABEL_TEXT = "claude";
34
- const DUAL_BAR_WIDTH = 10;
35
- const TELEGRAM_STATUS_IMPORT_SPECIFIERS = [
36
- "@llblab/pi-telegram/status",
37
- new URL("../pi-telegram/api/status.ts", import.meta.url).href,
38
- ];
39
- const DUAL_BAR_CHARS = [
40
- "⠀",
41
- "▘",
42
- "▝",
43
- "▀",
44
- "▖",
45
- "▌",
46
- "▞",
47
- "▛",
48
- "▗",
49
- "▚",
50
- "▐",
51
- "▜",
52
- "▄",
53
- "▙",
54
- "▟",
55
- "█",
56
- ];
57
-
58
- type TimeoutHandle = ReturnType<typeof setTimeout> & { unref?: () => void };
59
- type PiModel = NonNullable<ExtensionContext["model"]>;
60
- type ClaudeUsageTelegramStatusModel = Pick<PiModel, "id" | "name" | "provider">;
61
- type TelegramStatusLineProviderResult =
62
- { label: string; value: string } | undefined;
63
- type TelegramStatusLineProvider = (ctx: {
64
- activeModel?: ClaudeUsageTelegramStatusModel;
65
- }) => TelegramStatusLineProviderResult;
66
- type TelegramStatusLineModule = {
67
- registerTelegramStatusLineProvider?: (
68
- provider: TelegramStatusLineProvider,
69
- options: { id: string },
70
- ) => () => void;
71
- };
72
-
73
- type QueryUsageResult =
74
- | { ok: true; report: ClaudeUsageReport }
75
- | {
76
- ok: false;
77
- message: string;
78
- rateLimited: boolean;
79
- retryAfterMs?: number;
80
- };
81
-
82
- export type UsageQueryError = {
83
- message: string;
84
- cause?: unknown;
85
- };
86
-
87
- // --- Shared Refresh ---
88
-
89
- /**
90
- * Cross-instance coordination for quota polling. Every Pi instance reads one
91
- * JSON file; a single "leader"
92
- * refreshes it every `LEADER_INTERVAL_MS`. Any other instance may take over once
93
- * the file is `TAKEOVER_AFTER_MS` old: it first claims leadership (owner and
94
- * timestamp) so nobody else is due, then fetches, then stamps the result. The
95
- * file is the only authority for requests and fenced publication. Writes are
96
- * atomic renames; short critical sections use an OS-backed SQLite mutex.
97
- */
98
-
99
- export const LEADER_INTERVAL_MS = 60_000;
100
- /** The leader is considered gone after missing its slot by 30 seconds. */
101
- export const TAKEOVER_AFTER_MS = LEADER_INTERVAL_MS + 30_000;
102
- /** Minimum pause between two fetch attempts of the same instance. */
103
- export const MIN_ATTEMPT_GAP_MS = 60_000;
104
-
105
- const STATE_FILE = "usage.json";
106
- const LOCK_FILE = "mutex.sqlite";
107
-
108
- /** `primary` is the 5-hour session window; `secondary` is the weekly window. */
109
- export type ClaudeUsageReport = {
110
- primary?: NormalizedRateLimitWindow;
111
- secondary?: NormalizedRateLimitWindow;
112
- };
113
-
114
- export type NormalizedRateLimitWindow = {
115
- usedPercent: number;
116
- resetAt?: number;
117
- };
118
-
119
- export type SharedState = {
120
- report?: ClaudeUsageReport;
121
- /** When `report` was last fetched successfully. */
122
- updatedAt?: number;
123
- /**
124
- * When the leader last touched the file: written when it claims a refresh,
125
- * before fetching, and again when the fetch finishes.
126
- */
127
- claimedAt?: number;
128
- /** Instance id of the current leader (the last instance to claim). */
129
- owner?: string;
130
- /** Unique generation for this refresh, including renewals by the same owner. */
131
- claimId?: string;
132
- /** Last failure message; cleared by the next success. */
133
- error?: string;
134
- failures?: number;
135
- /** No instance should fetch before this time. */
136
- retryNotBefore?: number;
137
- };
138
-
139
- export function readState(dir: string): SharedState | undefined {
140
- try {
141
- const parsed = JSON.parse(
142
- readFileSync(join(dir, STATE_FILE), "utf8"),
143
- ) as unknown;
144
- return parsed && typeof parsed === "object" && !Array.isArray(parsed)
145
- ? (parsed as SharedState)
146
- : undefined;
147
- } catch {
148
- return undefined;
149
- }
150
- }
151
-
152
- export function writeState(dir: string, state: SharedState): boolean {
153
- try {
154
- mkdirSync(dir, { recursive: true });
155
- const temp = join(dir, `${STATE_FILE}.${process.pid}.tmp`);
156
- writeFileSync(temp, JSON.stringify(state), { mode: 0o600 });
157
- renameSync(temp, join(dir, STATE_FILE));
158
- return true;
159
- } catch {
160
- return false;
161
- }
162
- }
163
-
164
- export type RefreshClaim = { owner: string; claimId: string };
165
-
166
- export type RefreshOutcome =
167
- | { ok: true; report: ClaudeUsageReport }
168
- | {
169
- ok: false;
170
- error: string;
171
- rateLimited: boolean;
172
- retryAfterMs?: number;
173
- };
174
-
175
- /** Read, decide and claim under the lock; never authorize an unwritten claim. */
176
- export function claimRefresh(
177
- dir: string,
178
- owner: string,
179
- now?: number,
180
- ): RefreshClaim | undefined {
181
- const release = tryAcquireLock(dir);
182
- if (!release) return undefined;
183
- try {
184
- const current = readState(dir);
185
- const at = now ?? Date.now();
186
- if (!isRefreshDue(current, owner, at)) return undefined;
187
- const claim = { owner, claimId: randomUUID() };
188
- return writeState(dir, { ...current, ...claim, claimedAt: at })
189
- ? claim
190
- : undefined;
191
- } finally {
192
- release();
193
- }
194
- }
195
-
196
- function matchesClaim(
197
- state: SharedState | undefined,
198
- claim: RefreshClaim,
199
- now: number,
200
- ): boolean {
201
- return (
202
- state?.owner === claim.owner &&
203
- state.claimId === claim.claimId &&
204
- typeof state.claimedAt === "number" &&
205
- now - state.claimedAt < TAKEOVER_AFTER_MS
206
- );
207
- }
208
-
209
- /** Each admission check reads the file, not a remembered leadership flag. */
210
- export function ownsRefreshClaim(
211
- dir: string,
212
- claim: RefreshClaim,
213
- now?: number,
214
- ): boolean {
215
- const current = readState(dir);
216
- return matchesClaim(current, claim, now ?? Date.now());
217
- }
218
-
219
- /** A late success OR failure must not overwrite a successor's state. */
220
- export function publishRefresh(
221
- dir: string,
222
- claim: RefreshClaim,
223
- outcome: RefreshOutcome,
224
- now?: number,
225
- ): boolean {
226
- const release = tryAcquireLock(dir);
227
- if (!release) return false;
228
- try {
229
- const current = readState(dir);
230
- const at = now ?? Date.now();
231
- if (!matchesClaim(current, claim, at)) return false;
232
- if (outcome.ok) {
233
- return writeState(dir, {
234
- ...claim,
235
- claimedAt: at,
236
- updatedAt: at,
237
- report: outcome.report,
238
- });
239
- }
240
- const failures = (current?.failures ?? 0) + 1;
241
- return writeState(dir, {
242
- ...current,
243
- ...claim,
244
- claimedAt: at,
245
- error: outcome.error,
246
- failures,
247
- retryNotBefore: at + failureBackoffMs(failures, outcome),
248
- });
249
- } finally {
250
- release();
251
- }
252
- }
253
-
254
- /** Earliest time at which `owner` should try to refresh the state. */
255
- export function nextRefreshAt(
256
- state: SharedState | undefined,
257
- owner: string,
258
- now: number,
259
- ): number {
260
- const hold = state?.retryNotBefore ?? 0;
261
- const touchedAt = Math.max(
262
- state?.updatedAt ?? -Infinity,
263
- state?.claimedAt ?? -Infinity,
264
- );
265
- if (touchedAt === -Infinity) return Math.max(now, hold);
266
- const interval =
267
- state?.owner === owner ? LEADER_INTERVAL_MS : TAKEOVER_AFTER_MS;
268
- return Math.max(touchedAt + interval, hold);
269
- }
270
-
271
- export function isRefreshDue(
272
- state: SharedState | undefined,
273
- owner: string,
274
- now: number,
275
- ): boolean {
276
- return nextRefreshAt(state, owner, now) <= now;
277
- }
278
-
279
- /** Exponential failure backoff; HTTP 429 gets a longer base and cap. */
280
- export function failureBackoffMs(
281
- failures: number,
282
- options: { rateLimited: boolean; retryAfterMs?: number },
283
- ): number {
284
- const base = options.rateLimited ? 5 * 60_000 : 60_000;
285
- const cap = options.rateLimited ? 30 * 60_000 : 5 * 60_000;
286
- const exponential = Math.min(cap, base * 2 ** Math.max(0, failures - 1));
287
- return Math.max(options.retryAfterMs ?? 0, exponential);
288
- }
289
-
290
- /**
291
- * An empty SQLite transaction is a non-waiting, OS-backed mutex, not storage
292
- * for quota or leadership. Close or process death releases it; a paused live
293
- * holder cannot be evicted. Never unlink/replace mutex.sqlite while in use.
294
- */
295
- export function tryAcquireLock(dir: string): (() => void) | undefined {
296
- let database: DatabaseSync | undefined;
297
- try {
298
- mkdirSync(dir, { recursive: true });
299
- database = new DatabaseSync(join(dir, LOCK_FILE));
300
- // Contention must not wait on Pi's TUI thread; PRAGMA also works on Node 22.
301
- database.exec("PRAGMA busy_timeout = 0; BEGIN EXCLUSIVE");
302
- } catch {
303
- database?.close();
304
- return undefined;
305
- }
306
- return () => {
307
- const held = database;
308
- database = undefined;
309
- held?.close();
310
- };
311
- }
312
-
313
- export default function claudeUsage(pi: ExtensionAPI) {
314
- const instanceId = `${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
315
- const stateDir = join(getAgentDir(), "tmp", "pi-claude-usage");
316
- let lastAttemptAt = 0;
317
- let inFlightRefresh: Promise<void> | undefined;
318
- let shown: { key?: string; report?: ClaudeUsageReport; updatedAt?: number } = {};
319
- let statuslineBlinkTimer: TimeoutHandle | undefined;
320
- let statuslineCountdownTimer: TimeoutHandle | undefined;
321
- let statuslineLoadingTimer: TimeoutHandle | undefined;
322
- let statuslineRefreshTimer: TimeoutHandle | undefined;
323
- let statuslineLoadingFrame = 0;
324
- let statuslineRequestId = 0;
325
- let unregisterTelegramStatusLine: (() => void) | undefined;
326
- let telegramStatusLineRegistration: Promise<void> | undefined;
327
-
328
- const loadState = () => readState(stateDir);
329
-
330
- const ensureTelegramStatusLineRegistered = () => {
331
- if (unregisterTelegramStatusLine || telegramStatusLineRegistration) return;
332
- telegramStatusLineRegistration = registerClaudeUsageTelegramStatusLine(
333
- ({ activeModel }) => {
334
- if (!isAnthropicModel(activeModel)) return undefined;
335
- if (!shown.report) return undefined;
336
- const value = formatClaudeUsageStatusValue(shown.report);
337
- return value ? { label: STATUS_LABEL_TEXT, value } : undefined;
338
- },
339
- )
340
- .then((unregister) => {
341
- unregisterTelegramStatusLine = unregister;
342
- })
343
- .finally(() => {
344
- telegramStatusLineRegistration = undefined;
345
- });
346
- };
347
-
348
- const clearStatuslineTimers = () => {
349
- if (statuslineBlinkTimer) clearTimeout(statuslineBlinkTimer);
350
- if (statuslineCountdownTimer) clearTimeout(statuslineCountdownTimer);
351
- if (statuslineLoadingTimer) clearTimeout(statuslineLoadingTimer);
352
- if (statuslineRefreshTimer) clearTimeout(statuslineRefreshTimer);
353
- statuslineBlinkTimer = undefined;
354
- statuslineCountdownTimer = undefined;
355
- statuslineLoadingTimer = undefined;
356
- statuslineRefreshTimer = undefined;
357
- };
358
-
359
- const stopStatuslineLoading = () => {
360
- if (statuslineLoadingTimer) clearTimeout(statuslineLoadingTimer);
361
- statuslineLoadingTimer = undefined;
362
- };
363
-
364
- const startStatuslineLoading = (ctx: ExtensionContext) => {
365
- if (statuslineLoadingTimer) return;
366
- statuslineLoadingFrame = Math.random() < 0.5 ? 0 : DUAL_BAR_WIDTH * 2 - 1;
367
- const drawNextFrame = () => {
368
- try {
369
- ctx.ui.setStatus(
370
- STATUS_KEY,
371
- formatStatuslineLoading(ctx, statuslineLoadingFrame),
372
- );
373
- statuslineLoadingFrame += 1;
374
- statuslineLoadingTimer = setTimeout(
375
- drawNextFrame,
376
- LOADING_FRAME_MS,
377
- ) as TimeoutHandle;
378
- statuslineLoadingTimer.unref?.();
379
- } catch (error) {
380
- statuslineLoadingTimer = undefined;
381
- handleTimerError(error);
382
- }
383
- };
384
- drawNextFrame();
385
- };
386
-
387
- const clearUsageStatusline = (ctx: ExtensionContext) => {
388
- statuslineRequestId += 1;
389
- clearStatuslineTimers();
390
- shown = {};
391
- ctx.ui.setStatus(STATUS_KEY, undefined);
392
- };
393
-
394
- const scheduleStatuslineRefresh = (ctx: ExtensionContext, delayMs: number) => {
395
- if (statuslineRefreshTimer) clearTimeout(statuslineRefreshTimer);
396
- statuslineRefreshTimer = setTimeout(() => {
397
- void refreshCurrentClaudeUsageStatusline(ctx, false).catch(
398
- handleAsyncTimerError,
399
- );
400
- }, delayMs) as TimeoutHandle;
401
- statuslineRefreshTimer.unref?.();
402
- };
403
-
404
- const scheduleStatuslineCountdown = (
405
- ctx: ExtensionContext,
406
- report: ClaudeUsageReport,
407
- ) => {
408
- if (statuslineCountdownTimer) clearTimeout(statuslineCountdownTimer);
409
- const delayMs = nextResetCountdownDelayMs(report, Date.now());
410
- if (delayMs === undefined) {
411
- statuslineCountdownTimer = undefined;
412
- return;
413
- }
414
- statuslineCountdownTimer = setTimeout(() => {
415
- try {
416
- if (isAnthropicModel(ctx.model)) {
417
- ctx.ui.setStatus(STATUS_KEY, formatClaudeUsageStatusline(report, ctx));
418
- scheduleStatuslineCountdown(ctx, report);
419
- }
420
- } catch (error) {
421
- handleTimerError(error);
422
- }
423
- }, delayMs) as TimeoutHandle;
424
- statuslineCountdownTimer.unref?.();
425
- };
426
-
427
- const setUsageStatusline = (
428
- ctx: ExtensionContext,
429
- report: ClaudeUsageReport,
430
- blink: boolean,
431
- ) => {
432
- if (statuslineBlinkTimer) clearTimeout(statuslineBlinkTimer);
433
- if (statuslineCountdownTimer) clearTimeout(statuslineCountdownTimer);
434
- stopStatuslineLoading();
435
- statuslineBlinkTimer = undefined;
436
- statuslineCountdownTimer = undefined;
437
- const text = formatClaudeUsageStatusline(report, ctx);
438
- if (blink) {
439
- ctx.ui.setStatus(
440
- STATUS_KEY,
441
- formatStatuslineLoading(ctx, statuslineLoadingFrame),
442
- );
443
- statuslineBlinkTimer = setTimeout(() => {
444
- try {
445
- ctx.ui.setStatus(STATUS_KEY, text);
446
- scheduleStatuslineCountdown(ctx, report);
447
- statuslineBlinkTimer = undefined;
448
- } catch (error) {
449
- handleTimerError(error);
450
- }
451
- }, REDRAW_BLINK_MS) as TimeoutHandle;
452
- statuslineBlinkTimer.unref?.();
453
- } else {
454
- ctx.ui.setStatus(STATUS_KEY, text);
455
- scheduleStatuslineCountdown(ctx, report);
456
- }
457
- };
458
-
459
- /** Draws the shared state; skips redraws when nothing changed. */
460
- const renderState = (
461
- ctx: ExtensionContext,
462
- state: SharedState | undefined,
463
- force: boolean,
464
- ) => {
465
- // Cached display data is not permission to query when the file is unreadable.
466
- if (!state && shown.report && Date.now() - (shown.updatedAt ?? 0) < STALE_REPORT_MAX_AGE_MS) {
467
- if (force) setUsageStatusline(ctx, shown.report, false);
468
- return;
469
- }
470
- const usable =
471
- state?.report &&
472
- state.updatedAt !== undefined &&
473
- Date.now() - state.updatedAt < STALE_REPORT_MAX_AGE_MS
474
- ? state.report
475
- : undefined;
476
- if (usable) {
477
- const key = `report:${state?.updatedAt}`;
478
- if (!force && shown.key === key) return;
479
- const blink = shown.report
480
- ? formatClaudeUsageBar(shown.report) !== formatClaudeUsageBar(usable)
481
- : false;
482
- shown = { key, report: usable, updatedAt: state?.updatedAt };
483
- setUsageStatusline(ctx, usable, blink);
484
- } else if (state?.error) {
485
- const key = `error:${state.error}`;
486
- if (!force && shown.key === key) return;
487
- shown = { key };
488
- clearStatuslineTimers();
489
- ctx.ui.setStatus(
490
- STATUS_KEY,
491
- formatStatuslineProblem(ctx, [{ message: state.error }]),
492
- );
493
- } else {
494
- shown = { key: "loading" };
495
- startStatuslineLoading(ctx);
496
- }
497
- };
498
-
499
- /**
500
- * When this instance is due (leader after 1 minute, anyone after 90 seconds) it
501
- * claims leadership under the lock (owner and timestamp, so no other
502
- * instance is due), then fetches, then stamps the outcome. Failures are
503
- * published with a backoff so other instances do not pile on.
504
- */
505
- const refreshSharedState = (ctx: ExtensionContext) => {
506
- if (inFlightRefresh) return inFlightRefresh;
507
- const promise = (async () => {
508
- const claim = claimRefresh(stateDir, instanceId);
509
- if (!claim) return;
510
- lastAttemptAt = Date.now();
511
- const result = await queryUsage(
512
- ctx,
513
- DEFAULT_TIMEOUT_MS,
514
- () => ownsRefreshClaim(stateDir, claim),
515
- );
516
- if (!result) return;
517
- if (result.ok) {
518
- publishRefresh(stateDir, claim, result);
519
- return;
520
- }
521
- // A stale extension context is a local shutdown, not a server failure.
522
- if (result.message.includes("ctx is stale")) return;
523
- publishRefresh(stateDir, claim, {
524
- ok: false,
525
- error: result.message,
526
- rateLimited: result.rateLimited,
527
- retryAfterMs: result.retryAfterMs,
528
- });
529
- })().finally(() => {
530
- if (inFlightRefresh === promise) inFlightRefresh = undefined;
531
- });
532
- inFlightRefresh = promise;
533
- return promise;
534
- };
535
-
536
- const nextTickDelayMs = (state: SharedState | undefined) => {
537
- // Nothing to show yet (e.g. a claimed fetch is in flight): poll quickly.
538
- if (shown.key === "loading") return MIN_TICK_MS;
539
- const now = Date.now();
540
- const dueAt = Math.max(
541
- nextRefreshAt(state, instanceId, now),
542
- lastAttemptAt + MIN_ATTEMPT_GAP_MS,
543
- );
544
- const jitter =
545
- state?.owner === instanceId ? 0 : Math.random() * TAKEOVER_JITTER_MS;
546
- return Math.min(MAX_TICK_MS, Math.max(MIN_TICK_MS, dueAt - now + jitter));
547
- };
548
-
549
- const refreshCurrentClaudeUsageStatusline = async (
550
- ctx: ExtensionContext,
551
- forceRender: boolean,
552
- model?: ClaudeUsageTelegramStatusModel,
553
- ) => {
554
- try {
555
- if (!isAnthropicModel(model ?? ctx.model)) {
556
- clearUsageStatusline(ctx);
557
- return;
558
- }
559
-
560
- const requestId = statuslineRequestId + 1;
561
- statuslineRequestId = requestId;
562
- let state = loadState();
563
- renderState(ctx, state, forceRender);
564
-
565
- const now = Date.now();
566
- if (
567
- isRefreshDue(state, instanceId, now) &&
568
- now - lastAttemptAt >= MIN_ATTEMPT_GAP_MS
569
- ) {
570
- await refreshSharedState(ctx);
571
- if (requestId !== statuslineRequestId) return;
572
- if (!isAnthropicModel(ctx.model)) {
573
- clearUsageStatusline(ctx);
574
- return;
575
- }
576
- state = loadState();
577
- renderState(ctx, state, false);
578
- }
579
- scheduleStatuslineRefresh(ctx, nextTickDelayMs(state));
580
- } catch (error) {
581
- if (isStaleExtensionContextError(error)) {
582
- clearStatuslineTimers();
583
- return;
584
- }
585
- throw error;
586
- }
587
- };
588
-
589
- ensureTelegramStatusLineRegistered();
590
-
591
- pi.on("session_start", (_event, ctx) => {
592
- ensureTelegramStatusLineRegistered();
593
- if (isAnthropicModel(ctx.model))
594
- void refreshCurrentClaudeUsageStatusline(ctx, true).catch(
595
- handleAsyncTimerError,
596
- );
597
- else clearUsageStatusline(ctx);
598
- });
599
-
600
- pi.on("session_tree", (_event, ctx) => {
601
- if (isAnthropicModel(ctx.model))
602
- void refreshCurrentClaudeUsageStatusline(ctx, true).catch(
603
- handleAsyncTimerError,
604
- );
605
- else clearUsageStatusline(ctx);
606
- });
607
-
608
- pi.on("model_select", (event, ctx) => {
609
- if (isAnthropicModel(event.model)) {
610
- void refreshCurrentClaudeUsageStatusline(ctx, true, event.model).catch(
611
- handleAsyncTimerError,
612
- );
613
- } else {
614
- clearUsageStatusline(ctx);
615
- }
616
- });
617
-
618
- pi.on("session_shutdown", (_event, ctx) => {
619
- clearUsageStatusline(ctx);
620
- unregisterTelegramStatusLine?.();
621
- unregisterTelegramStatusLine = undefined;
622
- });
623
- }
624
-
625
- function handleAsyncTimerError(error: unknown): void {
626
- handleTimerError(error);
627
- }
628
-
629
- function handleTimerError(error: unknown): void {
630
- if (isStaleExtensionContextError(error)) return;
631
- throw error;
632
- }
633
-
634
- export function isStaleExtensionContextError(error: unknown): boolean {
635
- return error instanceof Error && error.message.includes("ctx is stale");
636
- }
637
-
638
- function isAnthropicModel(
639
- model: Pick<PiModel, "provider"> | undefined,
640
- ): boolean {
641
- return model?.provider === ANTHROPIC_PROVIDER_ID;
642
- }
643
-
644
- async function importTelegramStatusLineModule(): Promise<
645
- TelegramStatusLineModule | undefined
646
- > {
647
- for (const specifier of TELEGRAM_STATUS_IMPORT_SPECIFIERS) {
648
- try {
649
- const imported = (await import(specifier)) as TelegramStatusLineModule;
650
- if (typeof imported.registerTelegramStatusLineProvider === "function") {
651
- return imported;
652
- }
653
- } catch {
654
- // pi-telegram is optional; absence just disables the Telegram status line.
655
- }
656
- }
657
- return undefined;
658
- }
659
-
660
- async function registerClaudeUsageTelegramStatusLine(
661
- provider: TelegramStatusLineProvider,
662
- ): Promise<(() => void) | undefined> {
663
- const telegramStatus = await importTelegramStatusLineModule();
664
- return telegramStatus?.registerTelegramStatusLineProvider?.(provider, {
665
- id: CLAUDE_USAGE_EXTENSION_ID,
666
- });
667
- }
668
-
669
- async function queryUsage(
670
- ctx: ExtensionContext,
671
- timeoutMs: number,
672
- mayQuery: () => boolean,
673
- ): Promise<QueryUsageResult | undefined> {
674
- try {
675
- if (!mayQuery()) return undefined;
676
- const auth = await resolvePiAnthropicAuth(ctx);
677
- if (!auth) {
678
- throw new Error(
679
- "No Pi Anthropic subscription auth was available. Use a Pi Anthropic model or run /login for Anthropic Claude Pro/Max.",
680
- );
681
- }
682
-
683
- if (!mayQuery()) return undefined;
684
- const response = await fetchWithTimeout(
685
- CLAUDE_USAGE_URL,
686
- { headers: auth.headers },
687
- timeoutMs,
688
- );
689
- const text = await response.text();
690
- if (!response.ok) {
691
- return {
692
- ok: false,
693
- message: `Claude usage endpoint returned ${response.status} ${response.statusText}: ${redactErrorBody(text)}`,
694
- rateLimited: response.status === 429,
695
- retryAfterMs: parseRetryAfterMs(response.headers.get("retry-after")),
696
- };
697
- }
698
-
699
- const payload = parseJsonObject(text, "Claude usage endpoint response");
700
- return { ok: true, report: normalizeUsagePayload(payload) };
701
- } catch (cause) {
702
- return { ok: false, message: errorMessage(cause), rateLimited: false };
703
- }
704
- }
705
-
706
- function parseRetryAfterMs(value: string | null): number | undefined {
707
- const seconds = value === null ? undefined : asNumber(value);
708
- return seconds !== undefined && seconds > 0 ? seconds * SECOND_MS : undefined;
709
- }
710
-
711
- async function resolvePiAnthropicAuth(
712
- ctx: ExtensionContext,
713
- ): Promise<{ headers: Record<string, string> } | undefined> {
714
- const errors: string[] = [];
715
-
716
- for (const model of anthropicAuthCandidateModels(ctx)) {
717
- const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
718
- if (!auth.ok) {
719
- errors.push(auth.error);
720
- continue;
721
- }
722
- // The usage endpoint only accepts subscription OAuth tokens, not API keys.
723
- if (auth.apiKey?.includes("sk-ant-oat")) {
724
- return {
725
- headers: {
726
- Authorization: `Bearer ${auth.apiKey}`,
727
- "anthropic-beta": ANTHROPIC_OAUTH_BETA,
728
- Accept: "application/json",
729
- "User-Agent": "pi-claude-usage",
730
- },
731
- };
732
- }
733
- }
734
-
735
- if (errors.length > 0) {
736
- throw new Error(errors.join("; "));
737
- }
738
- return undefined;
739
- }
740
-
741
- function anthropicAuthCandidateModels(ctx: ExtensionContext): PiModel[] {
742
- const candidates: PiModel[] = [];
743
- const seen = new Set<string>();
744
- const add = (model: PiModel | undefined) => {
745
- if (!model || model.provider !== ANTHROPIC_PROVIDER_ID) return;
746
- const key = `${model.provider}/${model.id}`;
747
- if (seen.has(key)) return;
748
- seen.add(key);
749
- candidates.push(model);
750
- };
751
-
752
- add(ctx.model);
753
- for (const model of ctx.modelRegistry.getAvailable()) add(model);
754
- for (const model of ctx.modelRegistry.getAll()) add(model);
755
- return candidates;
756
- }
757
-
758
- async function fetchWithTimeout(
759
- url: string,
760
- init: RequestInit,
761
- timeoutMs: number,
762
- ): Promise<Response> {
763
- const controller = new AbortController();
764
- const timeout = setTimeout(() => controller.abort(), timeoutMs);
765
- try {
766
- return await fetch(url, { ...init, signal: controller.signal });
767
- } catch (error) {
768
- if (controller.signal.aborted) {
769
- throw new Error(
770
- `Timed out after ${Math.round(timeoutMs / 1000)}s while fetching Claude usage.`,
771
- );
772
- }
773
- throw error;
774
- } finally {
775
- clearTimeout(timeout);
776
- }
777
- }
778
-
779
- /**
780
- * Normalizes the `/api/oauth/usage` payload. `five_hour` maps to the primary
781
- * window and `seven_day` to the secondary one; `utilization` is a used percent.
782
- */
783
- export function normalizeUsagePayload(
784
- payload: Record<string, unknown>,
785
- ): ClaudeUsageReport {
786
- const primary = normalizeUsageWindow(payload.five_hour);
787
- const secondary = normalizeUsageWindow(payload.seven_day);
788
- if (!primary && !secondary) {
789
- throw new Error(
790
- "Claude usage endpoint returned no displayable rate-limit windows.",
791
- );
792
- }
793
- const report: ClaudeUsageReport = {};
794
- if (primary) report.primary = primary;
795
- if (secondary) report.secondary = secondary;
796
- return report;
797
- }
798
-
799
- function normalizeUsageWindow(
800
- value: unknown,
801
- ): NormalizedRateLimitWindow | undefined {
802
- if (value === null || value === undefined) return undefined;
803
- const window = assertObject(value, "rate-limit window");
804
- const usedPercent = asNumber(window.utilization);
805
- if (usedPercent === undefined) return undefined;
806
- const resetAt = asResetTime(window.resets_at);
807
- return resetAt === undefined ? { usedPercent } : { usedPercent, resetAt };
808
- }
809
-
810
- export function formatClaudeUsageStatusline(
811
- report: ClaudeUsageReport,
812
- ctx: ExtensionContext,
813
- ): string {
814
- const value = formatClaudeUsageStatusValue(report);
815
- if (!value) return formatStatuslineText(ctx, "n/a");
816
- if (!report.primary || !report.secondary)
817
- return formatStatuslineText(ctx, value);
818
- const [bar, countdown] = value.split(" ", 2);
819
- const barText = formatStatuslineBarText(
820
- ctx,
821
- bar ?? "",
822
- hasExhaustedQuotaWindow(report) ? "toolErrorBg" : "userMessageBg",
823
- );
824
- return countdown
825
- ? `${barText} ${ctx.ui.theme.fg("dim", countdown)}`
826
- : barText;
827
- }
828
-
829
- export function formatClaudeUsageBar(
830
- report: ClaudeUsageReport,
831
- ): string | undefined {
832
- if (!report.primary && !report.secondary) return undefined;
833
- return formatAdaptiveLimitBar(report.primary, report.secondary);
834
- }
835
-
836
- export function formatClaudeUsageStatusValue(
837
- report: ClaudeUsageReport,
838
- now = Date.now(),
839
- ): string | undefined {
840
- if (!report.primary || !report.secondary) {
841
- const window = report.primary ?? report.secondary;
842
- if (!window) return undefined;
843
- const percentage = `${Math.round(remainingPercent(window))}%`;
844
- const countdown = window.resetAt
845
- ? formatResetCountdown(window.resetAt, now)
846
- : undefined;
847
- return countdown ? `${percentage} ${countdown}` : percentage;
848
- }
849
- const bar = formatDualLimitBar(report.primary, report.secondary);
850
- if (isQuotaWindowExhausted(report.primary) && report.primary.resetAt) {
851
- const primaryCountdown = formatResetCountdown(report.primary.resetAt, now);
852
- const weeklyCountdown = report.secondary.resetAt
853
- ? formatResetCountdown(report.secondary.resetAt, now)
854
- : undefined;
855
- return weeklyCountdown
856
- ? `${bar} ${primaryCountdown}/${weeklyCountdown}`
857
- : `${bar} ${primaryCountdown}`;
858
- }
859
- const countdown = formatWeeklyResetCountdown(report, now);
860
- return countdown ? `${bar} ${countdown}` : bar;
861
- }
862
-
863
- export function formatWeeklyResetCountdown(
864
- report: ClaudeUsageReport,
865
- now = Date.now(),
866
- ): string | undefined {
867
- const resetAt = weeklyWindow(report)?.resetAt;
868
- if (resetAt === undefined) return undefined;
869
- return formatResetCountdown(resetAt, now);
870
- }
871
-
872
- export function formatResetCountdown(
873
- resetAt: number,
874
- now = Date.now(),
875
- ): string {
876
- const remainingMs = Math.max(0, resetAt - now);
877
- if (remainingMs > DAY_MS) {
878
- const dayTenths = Math.max(10, Math.ceil(remainingMs / DAY_TENTH_MS));
879
- return `${formatTenths(dayTenths)}d`;
880
- }
881
- if (remainingMs >= HOUR_MS) {
882
- const hourTenths = Math.max(10, Math.ceil(remainingMs / HOUR_TENTH_MS));
883
- return `${formatTenths(hourTenths)}h`;
884
- }
885
- if (remainingMs >= MINUTE_MS)
886
- return `${Math.floor(remainingMs / MINUTE_MS)}m`;
887
- return `${Math.floor(remainingMs / SECOND_MS)}s`;
888
- }
889
-
890
-
891
- export function nextResetCountdownDelayMs(
892
- report: ClaudeUsageReport,
893
- now = Date.now(),
894
- ): number | undefined {
895
- const resetTimes = [weeklyWindow(report)?.resetAt];
896
- if (report.secondary && isQuotaWindowExhausted(report.primary)) {
897
- resetTimes.push(report.primary?.resetAt);
898
- }
899
- const delays = resetTimes
900
- .filter((resetAt): resetAt is number => resetAt !== undefined)
901
- .map((resetAt) => nextResetCountdownDelayForRemainingMs(resetAt - now))
902
- .filter((delay): delay is number => delay !== undefined);
903
- return delays.length > 0 ? Math.min(...delays) : undefined;
904
- }
905
-
906
- export function nextResetCountdownDelayForRemainingMs(
907
- remainingMs: number,
908
- ): number | undefined {
909
- if (remainingMs <= 0) return undefined;
910
- if (remainingMs > DAY_MS) {
911
- const dayTenths = Math.max(10, Math.ceil(remainingMs / DAY_TENTH_MS));
912
- return Math.max(1, remainingMs - (dayTenths - 1) * DAY_TENTH_MS);
913
- }
914
- if (remainingMs >= HOUR_MS) {
915
- const hourTenths = Math.max(10, Math.ceil(remainingMs / HOUR_TENTH_MS));
916
- if (hourTenths === 10) return Math.max(1, remainingMs - HOUR_MS + 1);
917
- return Math.max(1, remainingMs - (hourTenths - 1) * HOUR_TENTH_MS);
918
- }
919
- if (remainingMs >= MINUTE_MS) {
920
- return Math.max(
921
- 1,
922
- remainingMs - Math.floor(remainingMs / MINUTE_MS) * MINUTE_MS + 1,
923
- );
924
- }
925
- return Math.max(
926
- 1,
927
- remainingMs - Math.floor(remainingMs / SECOND_MS) * SECOND_MS + 1,
928
- );
929
- }
930
-
931
- function formatTenths(value: number): string {
932
- return value % 10 === 0 ? String(value / 10) : (value / 10).toFixed(1);
933
- }
934
-
935
- function formatStatuslineText(
936
- ctx: ExtensionContext,
937
- value: string,
938
- ): string {
939
- const label = ctx.ui.theme.fg("accent", STATUS_LABEL_TEXT);
940
- return `${label} ${ctx.ui.theme.fg("dim", value)}`;
941
- }
942
-
943
- function formatStatuslineBarText(
944
- ctx: ExtensionContext,
945
- bar: string,
946
- background: "userMessageBg" | "toolErrorBg",
947
- ): string {
948
- const label = ctx.ui.theme.fg("accent", STATUS_LABEL_TEXT);
949
- const value = ctx.ui.theme.bg(background, ctx.ui.theme.fg("dim", bar));
950
- return `${label} ${value}`;
951
- }
952
-
953
- export function formatClaudeUsageLoadingBar(frame: number): string {
954
- const totalParts = DUAL_BAR_WIDTH * 2;
955
- const cycleFrames = (totalParts - 1) * 2;
956
- const finiteFrame = Number.isFinite(frame) ? frame : 0;
957
- const cycleFrame = Math.abs(Math.trunc(finiteFrame)) % cycleFrames;
958
- const primaryPart =
959
- cycleFrame < totalParts ? cycleFrame : cycleFrames - cycleFrame;
960
- const secondaryPart = totalParts - primaryPart - 1;
961
- const masks = Array<number>(DUAL_BAR_WIDTH).fill(0);
962
- const primaryCell = Math.floor(primaryPart / 2);
963
- const secondaryCell = Math.floor(secondaryPart / 2);
964
- masks[primaryCell] |= primaryPart % 2 === 0 ? 1 : 2;
965
- masks[secondaryCell] |= secondaryPart % 2 === 0 ? 4 : 8;
966
- return masks.map((mask) => DUAL_BAR_CHARS[mask]).join("");
967
- }
968
-
969
- function formatStatuslineLoading(
970
- ctx: ExtensionContext,
971
- frame: number,
972
- ): string {
973
- return formatStatuslineBarText(
974
- ctx,
975
- formatClaudeUsageLoadingBar(frame),
976
- "userMessageBg",
977
- );
978
- }
979
-
980
- function formatStatuslineProblem(
981
- ctx: ExtensionContext,
982
- errors: UsageQueryError[],
983
- ): string {
984
- const label = ctx.ui.theme.fg("accent", STATUS_LABEL_TEXT);
985
- const value = isUsageUnavailable(errors)
986
- ? ctx.ui.theme.fg("muted", "n/a")
987
- : ctx.ui.theme.fg("error", "error");
988
- return `${label} ${value}`;
989
- }
990
-
991
- export function isUsageUnavailable(errors: UsageQueryError[]): boolean {
992
- return errors.length > 0 && errors.every(isUnavailableError);
993
- }
994
-
995
- function isUnavailableError(error: UsageQueryError): boolean {
996
- const message = error.message.toLowerCase();
997
- return (
998
- message.includes("no pi anthropic subscription auth") ||
999
- message.includes("no displayable rate-limit windows") ||
1000
- message.includes("returned 401") ||
1001
- message.includes("returned 403") ||
1002
- message.includes("unauthorized") ||
1003
- message.includes("forbidden") ||
1004
- message.includes("subscription") ||
1005
- message.includes("permission")
1006
- );
1007
- }
1008
-
1009
- function formatAdaptiveLimitBar(
1010
- primary: NormalizedRateLimitWindow | undefined,
1011
- secondary: NormalizedRateLimitWindow | undefined,
1012
- ): string {
1013
- if (!primary || !secondary) return formatSingleLimitBar(primary ?? secondary);
1014
- return formatDualLimitBar(primary, secondary);
1015
- }
1016
-
1017
- function formatSingleLimitBar(
1018
- window: NormalizedRateLimitWindow | undefined,
1019
- ): string {
1020
- const filled = filledParts(window, DUAL_BAR_WIDTH * 4);
1021
- const partMasks = [1, 4, 2, 8];
1022
- let value = "";
1023
- for (let index = 0; index < DUAL_BAR_WIDTH; index++) {
1024
- const cellParts = Math.min(4, Math.max(0, filled - index * 4));
1025
- let mask = 0;
1026
- for (let part = 0; part < cellParts; part++) mask |= partMasks[part] ?? 0;
1027
- value += DUAL_BAR_CHARS[mask];
1028
- }
1029
- return value;
1030
- }
1031
-
1032
- function formatDualLimitBar(
1033
- primary: NormalizedRateLimitWindow,
1034
- secondary: NormalizedRateLimitWindow,
1035
- ): string {
1036
- const primaryParts = filledTwentieths(primary);
1037
- const secondaryParts = filledTwentieths(secondary);
1038
- let value = "";
1039
- for (let index = 0; index < DUAL_BAR_WIDTH; index++) {
1040
- const leftPart = index * 2 + 1;
1041
- const rightPart = leftPart + 1;
1042
- let mask = 0;
1043
- if (primaryParts >= leftPart) mask |= 1;
1044
- if (primaryParts >= rightPart) mask |= 2;
1045
- if (secondaryParts >= leftPart) mask |= 4;
1046
- if (secondaryParts >= rightPart) mask |= 8;
1047
- value += DUAL_BAR_CHARS[mask];
1048
- }
1049
- return value;
1050
- }
1051
-
1052
- function filledTwentieths(
1053
- window: NormalizedRateLimitWindow | undefined,
1054
- ): number {
1055
- return filledParts(window, 20);
1056
- }
1057
-
1058
- function filledParts(
1059
- window: NormalizedRateLimitWindow | undefined,
1060
- totalParts: number,
1061
- ): number {
1062
- if (!window) return 0;
1063
- const remaining = remainingPercent(window);
1064
- if (remaining <= 0) return 0;
1065
- return Math.max(1, Math.round(remaining / (100 / totalParts)));
1066
- }
1067
-
1068
- function remainingPercent(window: NormalizedRateLimitWindow): number {
1069
- return 100 - clampPercent(window.usedPercent);
1070
- }
1071
-
1072
- function isQuotaWindowExhausted(
1073
- window: NormalizedRateLimitWindow | undefined,
1074
- ): boolean {
1075
- return window !== undefined && remainingPercent(window) <= 0;
1076
- }
1077
-
1078
- function hasExhaustedQuotaWindow(report: ClaudeUsageReport): boolean {
1079
- return (
1080
- isQuotaWindowExhausted(report.primary) ||
1081
- isQuotaWindowExhausted(report.secondary)
1082
- );
1083
- }
1084
-
1085
- function weeklyWindow(
1086
- report: ClaudeUsageReport,
1087
- ): NormalizedRateLimitWindow | undefined {
1088
- return report.secondary ?? report.primary;
1089
- }
1090
-
1091
- function clampPercent(value: number): number {
1092
- if (!Number.isFinite(value)) return 0;
1093
- return Math.min(100, Math.max(0, value));
1094
- }
1095
-
1096
- function parseJsonObject(
1097
- text: string,
1098
- description: string,
1099
- ): Record<string, unknown> {
1100
- let parsed: unknown;
1101
- try {
1102
- parsed = JSON.parse(text) as unknown;
1103
- } catch (error) {
1104
- throw new Error(
1105
- `${description} was not valid JSON: ${errorMessage(error)}`,
1106
- );
1107
- }
1108
- return assertObject(parsed, description);
1109
- }
1110
-
1111
- function assertObject(
1112
- value: unknown,
1113
- description: string,
1114
- ): Record<string, unknown> {
1115
- if (!value || typeof value !== "object" || Array.isArray(value)) {
1116
- throw new Error(`${description} was not an object.`);
1117
- }
1118
- return value as Record<string, unknown>;
1119
- }
1120
-
1121
- function asNumber(value: unknown): number | undefined {
1122
- if (typeof value === "number" && Number.isFinite(value)) return value;
1123
- if (typeof value === "string" && value.trim()) {
1124
- const parsed = Number(value);
1125
- return Number.isFinite(parsed) ? parsed : undefined;
1126
- }
1127
- return undefined;
1128
- }
1129
-
1130
- function asResetTime(value: unknown): number | undefined {
1131
- if (typeof value === "number" && Number.isFinite(value) && value > 0) {
1132
- return value < 10_000_000_000 ? value * SECOND_MS : value;
1133
- }
1134
- if (typeof value === "string" && value.trim()) {
1135
- const parsed = Date.parse(value);
1136
- return Number.isFinite(parsed) ? parsed : undefined;
1137
- }
1138
- return undefined;
1139
- }
1140
-
1141
- function redactErrorBody(body: string): string {
1142
- return truncateEnd(
1143
- body
1144
- .replace(/Bearer\s+[A-Za-z0-9._~+/=-]+/gi, "Bearer <redacted>")
1145
- .replace(/sk-ant-[A-Za-z0-9_-]+/g, "<redacted>")
1146
- .replace(/"access_token"\s*:\s*"[^"]+"/gi, '"access_token":"<redacted>"')
1147
- .trim(),
1148
- MAX_ERROR_BODY_CHARS,
1149
- );
1150
- }
1151
-
1152
- function truncateEnd(value: string, maxChars: number): string {
1153
- if (value.length <= maxChars) return value;
1154
- return `${value.slice(0, maxChars - 1)}…`;
1155
- }
1156
-
1157
- function errorMessage(error: unknown): string {
1158
- return error instanceof Error ? error.message : String(error);
1159
- }
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 { normalizeUsagePayload, isUsageUnavailable } from "./lib/usage.ts";
6
+ export type { ClaudeUsageReport, NormalizedRateLimitWindow, UsageQueryError } from "./lib/usage.ts";
7
+ export { formatClaudeUsageStatusline, formatClaudeUsageBar, formatClaudeUsageStatusValue, formatWeeklyResetCountdown, formatResetCountdown, nextResetCountdownDelayMs, nextResetCountdownDelayForRemainingMs, formatClaudeUsageLoadingBar } from "./lib/status-format.ts";
8
+ export { isStaleExtensionContextError } from "./lib/status.ts";