@fenlyin/pi-subscription-usage 0.0.0-stage → 2.0.1

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/src/usage.ts ADDED
@@ -0,0 +1,679 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import type {
3
+ ExtensionAPI,
4
+ ExtensionCommandContext,
5
+ ExtensionContext,
6
+ } from "@earendil-works/pi-coding-agent";
7
+ import { loadUsageConfig } from "./config.ts";
8
+ import {
9
+ awaitWithDeadline,
10
+ errorMessage,
11
+ isAbortError,
12
+ modelIdentity,
13
+ UsageCache,
14
+ } from "./core.ts";
15
+ import {
16
+ DEFAULT_USAGE_DISPLAY_MODE,
17
+ type UsageDisplayMode,
18
+ } from "./display.ts";
19
+ import {
20
+ CODEX_RESET_CONFIRMATION_OPTIONS,
21
+ codexResetCount,
22
+ formatCodexResetOutcome,
23
+ isCodexResetConfirmed,
24
+ resetOptionExpiration,
25
+ type CodexResetOption,
26
+ } from "./codex-reset-core.ts";
27
+ import {
28
+ consumeCodexResetCredit,
29
+ listCodexResetCredits,
30
+ resolveCodexResetAuth,
31
+ } from "./codex-resets.ts";
32
+ import { formatProviderState } from "./format.ts";
33
+ import {
34
+ CLAUDE_BRIDGE_PROVIDER_ID,
35
+ normalizeClaudeRateLimitHeaders,
36
+ settleClaudeReport,
37
+ } from "./providers/claude-bridge.ts";
38
+ import { CODEX_PROVIDER_ID } from "./providers/codex-constants.ts";
39
+ import { OPENAI_PROVIDER_ID } from "./providers/openai.ts";
40
+ import {
41
+ buildUsageStatusEvent,
42
+ formatUsageStatusline,
43
+ type UsageStatusEvent,
44
+ unavailableUsageStatusEvent,
45
+ USAGE_STATUS_EVENT,
46
+ } from "./status.ts";
47
+ import {
48
+ adapterForProvider,
49
+ queryProviderUsage,
50
+ resolveUsageAuth,
51
+ UsageUnsupportedError,
52
+ } from "./query.ts";
53
+ import type {
54
+ ProviderUsageState,
55
+ ResolvedUsageAuth,
56
+ UsageModel,
57
+ UsageProviderAdapter,
58
+ UsageReport,
59
+ } from "./types.ts";
60
+
61
+ const CACHE_TTL_MS = 5 * 60 * 1_000;
62
+ const QUERY_TIMEOUT_MS = 15_000;
63
+ const FAILURE_BACKOFF_MS = 30_000;
64
+ const STATUS_KEY = "subscription-usage";
65
+
66
+ type QueryOutcome = {
67
+ state: ProviderUsageState;
68
+ fingerprint?: string;
69
+ };
70
+
71
+ type StableCurrent = {
72
+ outcome: QueryOutcome;
73
+ model: UsageModel | undefined;
74
+ };
75
+
76
+ export default function subscriptionUsage(pi: ExtensionAPI): void {
77
+ const cache = new UsageCache(CACHE_TTL_MS);
78
+ const failureBackoff = new Map<string, { until: number; message: string }>();
79
+ const activeControllers = new Set<AbortController>();
80
+ let sessionActive = false;
81
+ let displayMode: UsageDisplayMode = DEFAULT_USAGE_DISPLAY_MODE;
82
+ let statusGeneration = 0;
83
+ let statusController: AbortController | undefined;
84
+ let statusTimer: ReturnType<typeof setTimeout> | undefined;
85
+ // Holds no credential, so session_shutdown leaves it; nothing reads it after.
86
+ let claudeObservation: UsageReport | undefined;
87
+
88
+ function emitUsageStatus(event: UsageStatusEvent): void {
89
+ pi.events.emit(USAGE_STATUS_EVENT, event);
90
+ }
91
+
92
+ function emitUnavailableUsage(): void {
93
+ emitUsageStatus(unavailableUsageStatusEvent());
94
+ }
95
+
96
+ function clearStatusTimer(): void {
97
+ if (statusTimer) clearTimeout(statusTimer);
98
+ statusTimer = undefined;
99
+ }
100
+
101
+ function safeSetStatus(
102
+ ctx: ExtensionContext,
103
+ value: string | undefined,
104
+ ): boolean {
105
+ try {
106
+ ctx.ui.setStatus(STATUS_KEY, value);
107
+ return true;
108
+ } catch (error) {
109
+ if (!sessionActive) return false;
110
+ throw error;
111
+ }
112
+ }
113
+
114
+ function clearStatus(ctx: ExtensionContext): void {
115
+ statusGeneration += 1;
116
+ statusController?.abort();
117
+ statusController = undefined;
118
+ clearStatusTimer();
119
+ safeSetStatus(ctx, undefined);
120
+ emitUnavailableUsage();
121
+ }
122
+
123
+ function scheduleStatusRefresh(
124
+ ctx: ExtensionContext,
125
+ model: UsageModel,
126
+ delayMs = CACHE_TTL_MS,
127
+ ): void {
128
+ clearStatusTimer();
129
+ const generation = statusGeneration;
130
+ statusTimer = setTimeout(() => {
131
+ statusTimer = undefined;
132
+ if (!sessionActive || generation !== statusGeneration) return;
133
+ startStatusRefresh(ctx, model, true);
134
+ }, delayMs);
135
+ }
136
+
137
+ function publishStatus(
138
+ ctx: ExtensionContext,
139
+ outcome: QueryOutcome,
140
+ model: UsageModel,
141
+ schedule: boolean,
142
+ ): void {
143
+ if (
144
+ outcome.state.status === "unsupported" ||
145
+ outcome.state.status === "pending"
146
+ ) {
147
+ clearStatusTimer();
148
+ safeSetStatus(ctx, undefined);
149
+ emitUnavailableUsage();
150
+ return;
151
+ }
152
+ if (outcome.state.status !== "ready") {
153
+ emitUnavailableUsage();
154
+ if (
155
+ safeSetStatus(
156
+ ctx,
157
+ outcome.state.status === "auth-unavailable"
158
+ ? "usage auth ?"
159
+ : "usage error",
160
+ ) &&
161
+ schedule &&
162
+ sessionActive
163
+ ) {
164
+ scheduleStatusRefresh(ctx, model);
165
+ }
166
+ return;
167
+ }
168
+ const nowMs = Date.now();
169
+ emitUsageStatus(
170
+ buildUsageStatusEvent(outcome.state.report, model, displayMode, nowMs),
171
+ );
172
+ const value = formatUsageStatusline(
173
+ outcome.state.report,
174
+ model,
175
+ displayMode,
176
+ nowMs,
177
+ );
178
+ if (!safeSetStatus(ctx, value)) return;
179
+ if (schedule && sessionActive) scheduleStatusRefresh(ctx, model);
180
+ }
181
+
182
+ async function queryAdapterState(
183
+ ctx: ExtensionContext,
184
+ adapter: UsageProviderAdapter,
185
+ force: boolean,
186
+ signal: AbortSignal,
187
+ ): Promise<QueryOutcome> {
188
+ let auth: ResolvedUsageAuth | undefined;
189
+ try {
190
+ auth = await awaitWithDeadline(
191
+ () => resolveUsageAuth(ctx, adapter),
192
+ signal,
193
+ QUERY_TIMEOUT_MS,
194
+ `resolving ${adapter.displayName} authentication`,
195
+ );
196
+ } catch (error) {
197
+ if (isAbortError(error) || !sessionActive) throw error;
198
+ return {
199
+ state: {
200
+ providerId: adapter.id,
201
+ providerName: adapter.displayName,
202
+ status: error instanceof UsageUnsupportedError
203
+ ? "unsupported"
204
+ : "auth-unavailable",
205
+ message: errorMessage(error),
206
+ },
207
+ };
208
+ }
209
+ if (!auth) {
210
+ return {
211
+ state: {
212
+ providerId: adapter.id,
213
+ providerName: adapter.displayName,
214
+ status: "auth-unavailable",
215
+ message: `No Pi runtime credential available for ${adapter.displayName}.`,
216
+ },
217
+ };
218
+ }
219
+ const cached = force ? undefined : cache.get(adapter.id, auth.fingerprint);
220
+ if (cached) {
221
+ return {
222
+ state: {
223
+ providerId: adapter.id,
224
+ providerName: adapter.displayName,
225
+ status: "ready",
226
+ report: cached,
227
+ },
228
+ fingerprint: auth.fingerprint,
229
+ };
230
+ }
231
+ const failureKey = `${adapter.id}:${auth.fingerprint}`;
232
+ const failure = failureBackoff.get(failureKey);
233
+ if (!force && failure && failure.until > Date.now()) {
234
+ return {
235
+ state: {
236
+ providerId: adapter.id,
237
+ providerName: adapter.displayName,
238
+ status: "query-failed",
239
+ message: failure.message,
240
+ },
241
+ fingerprint: auth.fingerprint,
242
+ };
243
+ }
244
+ failureBackoff.delete(failureKey);
245
+ try {
246
+ const report = await queryProviderUsage(
247
+ adapter,
248
+ auth,
249
+ signal,
250
+ QUERY_TIMEOUT_MS,
251
+ );
252
+ cache.set(adapter.id, auth.fingerprint, report);
253
+ return {
254
+ state: {
255
+ providerId: adapter.id,
256
+ providerName: adapter.displayName,
257
+ status: "ready",
258
+ report,
259
+ },
260
+ fingerprint: auth.fingerprint,
261
+ };
262
+ } catch (error) {
263
+ if (isAbortError(error) || !sessionActive) throw error;
264
+ const message = errorMessage(error);
265
+ failureBackoff.set(failureKey, {
266
+ until: Date.now() + FAILURE_BACKOFF_MS,
267
+ message,
268
+ });
269
+ return {
270
+ state: {
271
+ providerId: adapter.id,
272
+ providerName: adapter.displayName,
273
+ status: "query-failed",
274
+ message,
275
+ },
276
+ fingerprint: auth.fingerprint,
277
+ };
278
+ }
279
+ }
280
+
281
+ async function queryCurrentState(
282
+ ctx: ExtensionContext,
283
+ model: UsageModel | undefined,
284
+ force: boolean,
285
+ signal: AbortSignal,
286
+ ): Promise<QueryOutcome> {
287
+ if (isObservedProvider(model)) return observedClaudeOutcome();
288
+ const adapter = adapterForProvider(model?.provider);
289
+ if (!adapter) {
290
+ return {
291
+ state: {
292
+ providerId: model?.provider ?? "none",
293
+ providerName: model?.provider ?? "No model",
294
+ status: "unsupported",
295
+ message: model
296
+ ? `${model.provider} is not supported yet.`
297
+ : "No model selected.",
298
+ },
299
+ };
300
+ }
301
+ return queryAdapterState(ctx, adapter, force, signal);
302
+ }
303
+
304
+ /** Claude has no query to force; /usage and refreshes reread the last observation. */
305
+ function observedClaudeOutcome(): QueryOutcome {
306
+ const providerName = "Claude (Claude Code)";
307
+ if (!claudeObservation) {
308
+ return {
309
+ state: {
310
+ providerId: CLAUDE_BRIDGE_PROVIDER_ID,
311
+ providerName,
312
+ status: "pending",
313
+ message: "Claude Code has not reported usage in this session yet. It reports usage with its responses, which requires pi-claude-bridge 0.9.3 or later.",
314
+ },
315
+ };
316
+ }
317
+ return {
318
+ state: {
319
+ providerId: CLAUDE_BRIDGE_PROVIDER_ID,
320
+ providerName,
321
+ status: "ready",
322
+ report: settleClaudeReport(claudeObservation, Date.now()),
323
+ },
324
+ };
325
+ }
326
+
327
+ async function outcomeStillCurrent(
328
+ ctx: ExtensionContext,
329
+ model: UsageModel | undefined,
330
+ outcome: QueryOutcome,
331
+ signal: AbortSignal,
332
+ ): Promise<boolean> {
333
+ if (modelIdentity(ctx.model) !== modelIdentity(model)) return false;
334
+ if (!outcome.fingerprint) return true;
335
+ const adapter = adapterForProvider(model?.provider);
336
+ if (!adapter) return false;
337
+ try {
338
+ const auth = await awaitWithDeadline(
339
+ () => resolveUsageAuth(ctx, adapter),
340
+ signal,
341
+ QUERY_TIMEOUT_MS,
342
+ `revalidating ${adapter.displayName} authentication`,
343
+ );
344
+ return (
345
+ modelIdentity(ctx.model) === modelIdentity(model) &&
346
+ auth?.fingerprint === outcome.fingerprint
347
+ );
348
+ } catch (error) {
349
+ if (isAbortError(error) || !sessionActive) throw error;
350
+ return false;
351
+ }
352
+ }
353
+
354
+ async function queryStableCurrent(
355
+ ctx: ExtensionContext,
356
+ force: boolean,
357
+ signal: AbortSignal,
358
+ ): Promise<StableCurrent | undefined> {
359
+ for (let attempt = 0; attempt < 2; attempt += 1) {
360
+ const model = ctx.model;
361
+ const outcome = await queryCurrentState(ctx, model, force, signal);
362
+ if (await outcomeStillCurrent(ctx, model, outcome, signal)) {
363
+ return { outcome, model };
364
+ }
365
+ force = false;
366
+ }
367
+ return undefined;
368
+ }
369
+
370
+ async function refreshCurrentStatus(
371
+ ctx: ExtensionContext,
372
+ model: UsageModel | undefined,
373
+ force: boolean,
374
+ ): Promise<void> {
375
+ const observed = isObservedProvider(model);
376
+ if ((!observed && !adapterForProvider(model?.provider)) || !model) {
377
+ clearStatus(ctx);
378
+ return;
379
+ }
380
+ statusGeneration += 1;
381
+ const generation = statusGeneration;
382
+ statusController?.abort();
383
+ const controller = new AbortController();
384
+ statusController = controller;
385
+ activeControllers.add(controller);
386
+ const refreshIsCurrent = (): boolean =>
387
+ sessionActive &&
388
+ generation === statusGeneration &&
389
+ !controller.signal.aborted &&
390
+ modelIdentity(ctx.model) === modelIdentity(model);
391
+ try {
392
+ // An observed provider answers immediately; a placeholder would only flicker.
393
+ if (!observed) safeSetStatus(ctx, "usage …");
394
+ const outcome = await queryCurrentState(
395
+ ctx,
396
+ model,
397
+ force,
398
+ controller.signal,
399
+ );
400
+ if (
401
+ !refreshIsCurrent() ||
402
+ !(await outcomeStillCurrent(ctx, model, outcome, controller.signal))
403
+ ) {
404
+ return;
405
+ }
406
+ publishStatus(ctx, outcome, model, true);
407
+ } catch (error) {
408
+ if (isAbortError(error) || !refreshIsCurrent()) return;
409
+ try {
410
+ emitUnavailableUsage();
411
+ } catch {
412
+ // A status consumer must not stop future refreshes.
413
+ }
414
+ if (!refreshIsCurrent()) return;
415
+ try {
416
+ safeSetStatus(ctx, "usage error");
417
+ } catch {
418
+ // Error reporting must not stop future refreshes.
419
+ }
420
+ if (refreshIsCurrent()) {
421
+ scheduleStatusRefresh(ctx, model, FAILURE_BACKOFF_MS);
422
+ }
423
+ } finally {
424
+ activeControllers.delete(controller);
425
+ if (statusController === controller) statusController = undefined;
426
+ }
427
+ }
428
+
429
+ function startStatusRefresh(
430
+ ctx: ExtensionContext,
431
+ model: UsageModel | undefined,
432
+ force: boolean,
433
+ ): void {
434
+ void refreshCurrentStatus(ctx, model, force).catch(() => {
435
+ // Unsupported-model cleanup is best effort during UI teardown.
436
+ });
437
+ }
438
+
439
+ async function redeemCodexReset(
440
+ ctx: ExtensionCommandContext,
441
+ current: StableCurrent,
442
+ controller: AbortController,
443
+ ): Promise<StableCurrent | undefined> {
444
+ if (
445
+ ![CODEX_PROVIDER_ID, OPENAI_PROVIDER_ID].includes(ctx.model?.provider ?? "") ||
446
+ current.outcome.state.status !== "ready"
447
+ ) {
448
+ ctx.ui.notify(
449
+ "Account resets require the current OpenAI or Codex OAuth account.",
450
+ "warning",
451
+ );
452
+ return undefined;
453
+ }
454
+ const expectedModel = modelIdentity(current.model);
455
+ const isOpenAI = current.model?.provider === OPENAI_PROVIDER_ID;
456
+ const resetNoun = isOpenAI ? "account" : "Codex";
457
+ if (modelIdentity(ctx.model) !== expectedModel) throw new Error("Model changed; reset cancelled.");
458
+ let auth = await awaitWithDeadline(
459
+ () => resolveCodexResetAuth(ctx),
460
+ controller.signal,
461
+ QUERY_TIMEOUT_MS,
462
+ "resolving reset authentication",
463
+ );
464
+ if (auth.usageFingerprint !== current.outcome.fingerprint) {
465
+ throw new Error("Account changed since usage was displayed; run /usage again.");
466
+ }
467
+ // A failed listing never falls back to an unscoped, server-chosen reset.
468
+ const availability = await listCodexResetCredits(
469
+ auth,
470
+ controller.signal,
471
+ QUERY_TIMEOUT_MS,
472
+ );
473
+ if (availability.availableCount <= 0 || availability.options.length === 0) {
474
+ ctx.ui.notify(`No ${resetNoun} reset credits available.`, "info");
475
+ return undefined;
476
+ }
477
+ const labels = availability.options.map(
478
+ (option: CodexResetOption, index: number) =>
479
+ `${index + 1}. ${option.title} · ${resetOptionExpiration(option)}`,
480
+ );
481
+ const selected = await ctx.ui.select(
482
+ isOpenAI ? "Choose an Account Reset" : "Choose a Codex Reset",
483
+ labels,
484
+ );
485
+ if (!selected) return undefined;
486
+ const option = availability.options[labels.indexOf(selected)];
487
+ if (!option) return undefined;
488
+ const confirmation = await ctx.ui.select(
489
+ `Redeem one ${resetNoun} reset?\n${option.title}\n${option.description}\n${resetOptionExpiration(option)}${isOpenAI ? "\nConsumes a reset from the companion Codex account. Only ticket-supported account windows are reset; clearing this app's quota is not guaranteed." : ""}`,
490
+ [...CODEX_RESET_CONFIRMATION_OPTIONS],
491
+ );
492
+ if (!isCodexResetConfirmed(confirmation)) return undefined;
493
+
494
+ const expectedFingerprint = auth.fingerprint;
495
+ const requestId = randomUUID();
496
+ let submitted = false;
497
+ while (!controller.signal.aborted) {
498
+ try {
499
+ auth = await awaitWithDeadline(
500
+ () => resolveCodexResetAuth(ctx),
501
+ controller.signal,
502
+ QUERY_TIMEOUT_MS,
503
+ "revalidating reset authentication",
504
+ );
505
+ if (
506
+ modelIdentity(ctx.model) !== expectedModel ||
507
+ auth.fingerprint !== expectedFingerprint
508
+ ) {
509
+ throw new Error("Model or account changed; reset not submitted.");
510
+ }
511
+ if (isOpenAI) {
512
+ await queryProviderUsage(adapterForProvider(OPENAI_PROVIDER_ID)!, auth, controller.signal, QUERY_TIMEOUT_MS);
513
+ const checked = await awaitWithDeadline(() => resolveCodexResetAuth(ctx), controller.signal, QUERY_TIMEOUT_MS, "revalidating account reset authentication");
514
+ if (checked.fingerprint !== expectedFingerprint || modelIdentity(ctx.model) !== expectedModel) {
515
+ throw new Error("OpenAI or Codex account changed; reset not submitted.");
516
+ }
517
+ auth = checked;
518
+ }
519
+ } catch (error) {
520
+ if (isAbortError(error) || !sessionActive) throw error;
521
+ if (!submitted) throw error;
522
+ // A previous POST may have succeeded even though its response was lost.
523
+ ctx.ui.notify("Reset result uncertain; retry stopped during account or usage verification. Run /usage to check your quota and reset credits.", "warning");
524
+ return undefined;
525
+ }
526
+
527
+ let outcome;
528
+ try {
529
+ submitted = true;
530
+ outcome = await consumeCodexResetCredit(
531
+ auth,
532
+ option,
533
+ requestId,
534
+ controller.signal,
535
+ QUERY_TIMEOUT_MS,
536
+ );
537
+ } catch (error) {
538
+ if (isAbortError(error) || !sessionActive) throw error;
539
+ const retryAction = "Retry with Same Request ID";
540
+ const retry = await ctx.ui.select("Reset Result Uncertain", [
541
+ retryAction,
542
+ "Cancel",
543
+ ]);
544
+ if (retry !== retryAction) {
545
+ ctx.ui.notify(`Reset result uncertain; run /usage to check your quota and reset credits. ${errorMessage(error)}`, "warning");
546
+ return undefined;
547
+ }
548
+ continue;
549
+ }
550
+
551
+ // A confirmed consume result must never become another consume retry.
552
+ cache.clearProvider(CODEX_PROVIDER_ID);
553
+ cache.clearProvider(OPENAI_PROVIDER_ID);
554
+ failureBackoff.clear();
555
+ ctx.ui.notify(formatCodexResetOutcome(outcome, undefined), "info");
556
+ try {
557
+ const refreshed = await queryStableCurrent(ctx, true, controller.signal);
558
+ if (!refreshed || refreshed.outcome.state.status !== "ready") {
559
+ ctx.ui.notify("Reset result confirmed, but usage refresh failed. Run /usage again.", "warning");
560
+ }
561
+ if (refreshed?.model) {
562
+ publishStatus(ctx, refreshed.outcome, refreshed.model, sessionActive);
563
+ }
564
+ return refreshed;
565
+ } catch (error) {
566
+ if (isAbortError(error) || !sessionActive) throw error;
567
+ ctx.ui.notify("Reset result confirmed, but usage refresh or display failed. Run /usage again.", "warning");
568
+ return undefined;
569
+ }
570
+ }
571
+ return undefined;
572
+ }
573
+
574
+ async function showUsage(ctx: ExtensionCommandContext): Promise<void> {
575
+ if (!ctx.hasUI) throw new Error("/usage requires TUI or RPC mode.");
576
+ const controller = new AbortController();
577
+ activeControllers.add(controller);
578
+ try {
579
+ const current = await queryStableCurrent(ctx, true, controller.signal);
580
+ if (!current) {
581
+ ctx.ui.notify(
582
+ "Model or account keeps changing; run /usage again.",
583
+ "warning",
584
+ );
585
+ return;
586
+ }
587
+ ctx.ui.notify(
588
+ formatProviderState(current.outcome.state, displayMode),
589
+ "info",
590
+ );
591
+ if (current.model) {
592
+ publishStatus(ctx, current.outcome, current.model, sessionActive);
593
+ }
594
+ if (
595
+ ![CODEX_PROVIDER_ID, OPENAI_PROVIDER_ID].includes(ctx.model?.provider ?? "") ||
596
+ current.outcome.state.status !== "ready"
597
+ ) {
598
+ return;
599
+ }
600
+ const resetCount = codexResetCount(current.outcome.state.report) ?? 0;
601
+ if (resetCount <= 0) return;
602
+ const action = await ctx.ui.select(
603
+ `Reset Credits: ${resetCount} Available`,
604
+ ["Redeem 1 Reset"],
605
+ );
606
+ if (!action) return;
607
+ const refreshed = await redeemCodexReset(ctx, current, controller);
608
+ if (refreshed?.outcome.state.status === "ready") {
609
+ ctx.ui.notify(
610
+ formatProviderState(refreshed.outcome.state, displayMode),
611
+ "info",
612
+ );
613
+ }
614
+ } finally {
615
+ controller.abort();
616
+ activeControllers.delete(controller);
617
+ }
618
+ }
619
+
620
+ pi.registerCommand("usage", {
621
+ description: "Show subscription usage for the current provider",
622
+ handler: async (args, ctx) => {
623
+ if (args.trim()) {
624
+ ctx.ui.notify("/usage takes no arguments.", "warning");
625
+ return;
626
+ }
627
+ try {
628
+ await showUsage(ctx);
629
+ } catch (error) {
630
+ if (isAbortError(error) || !sessionActive) return;
631
+ ctx.ui.notify(`Usage query failed: ${errorMessage(error)}`, "error");
632
+ }
633
+ },
634
+ });
635
+
636
+ pi.on("session_start", (_event, ctx) => {
637
+ sessionActive = ctx.hasUI;
638
+ const config = loadUsageConfig(ctx.cwd, ctx.isProjectTrusted());
639
+ displayMode = config.displayMode;
640
+ for (const warning of config.warnings) {
641
+ ctx.ui.notify(`Usage config ignored: ${warning}`, "warning");
642
+ }
643
+ if (ctx.hasUI) startStatusRefresh(ctx, ctx.model, false);
644
+ });
645
+ pi.on("session_tree", (_event, ctx) => {
646
+ if (ctx.hasUI) startStatusRefresh(ctx, ctx.model, false);
647
+ });
648
+ pi.on("model_select", (event, ctx) => {
649
+ if (!ctx.hasUI) return;
650
+ emitUnavailableUsage();
651
+ startStatusRefresh(ctx, event.model, false);
652
+ });
653
+ pi.on("agent_settled", (_event, ctx) => {
654
+ if (ctx.hasUI) startStatusRefresh(ctx, ctx.model, false);
655
+ });
656
+ pi.on("after_provider_response", (event, ctx) => {
657
+ if (!isObservedProvider(ctx.model)) return;
658
+ const report = normalizeClaudeRateLimitHeaders(event.headers, Date.now());
659
+ if (!report) return;
660
+ claudeObservation = report;
661
+ if (ctx.hasUI && sessionActive) startStatusRefresh(ctx, ctx.model, false);
662
+ });
663
+ pi.on("session_shutdown", (_event, ctx) => {
664
+ sessionActive = false;
665
+ statusGeneration += 1;
666
+ clearStatusTimer();
667
+ for (const controller of activeControllers) controller.abort();
668
+ activeControllers.clear();
669
+ statusController = undefined;
670
+ cache.clear();
671
+ failureBackoff.clear();
672
+ safeSetStatus(ctx, undefined);
673
+ emitUnavailableUsage();
674
+ });
675
+ }
676
+
677
+ function isObservedProvider(model: UsageModel | undefined): boolean {
678
+ return model?.provider === CLAUDE_BRIDGE_PROVIDER_ID;
679
+ }