@0xkahi/pi-qol 1.1.3 → 1.3.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 (46) hide show
  1. package/README.md +36 -14
  2. package/assets/config.schema.json +12 -19
  3. package/package.json +5 -5
  4. package/src/extensions/auto-session-name/codemap.md +5 -5
  5. package/src/extensions/auto-session-name/guards.ts +9 -18
  6. package/src/extensions/auto-session-name/index.ts +8 -32
  7. package/src/extensions/auto-session-name/naming-text.ts +17 -0
  8. package/src/extensions/custom-footer/codemap.md +5 -6
  9. package/src/extensions/custom-footer/constants.ts +0 -1
  10. package/src/extensions/custom-footer/footer-component.ts +10 -8
  11. package/src/extensions/custom-footer/index.ts +3 -1
  12. package/src/extensions/custom-footer/token-stats.ts +5 -6
  13. package/src/extensions/custom-footer/types.ts +3 -1
  14. package/src/extensions/model-select/codemap.md +8 -4
  15. package/src/extensions/model-select/index.ts +35 -29
  16. package/src/extensions/model-select/model-select-dialog.ts +9 -25
  17. package/src/extensions/model-select/model-select-modal.ts +66 -0
  18. package/src/extensions/model-select/usage-section/codemap.md +14 -0
  19. package/src/extensions/model-select/usage-section/index.ts +37 -0
  20. package/src/extensions/model-select/usage-section/usage-provider-tab.ts +166 -0
  21. package/src/index.ts +7 -3
  22. package/src/libs/modal/README.md +46 -2
  23. package/src/libs/modal/codemap.md +4 -1
  24. package/src/libs/modal/index.ts +2 -0
  25. package/src/libs/modal/label-window.ts +32 -0
  26. package/src/libs/modal/modal-dialog.ts +16 -2
  27. package/src/libs/modal/section-strip.ts +33 -0
  28. package/src/libs/modal/sectioned-modal.ts +105 -0
  29. package/src/libs/modal/tab-strip.ts +2 -26
  30. package/src/libs/subscription-usage/codemap.md +10 -21
  31. package/src/libs/subscription-usage/credential-resolver.ts +44 -0
  32. package/src/libs/subscription-usage/index.ts +8 -0
  33. package/src/libs/subscription-usage/pace.ts +28 -0
  34. package/src/libs/subscription-usage/progress-bar.ts +13 -0
  35. package/src/libs/subscription-usage/provider-color.ts +10 -0
  36. package/src/libs/subscription-usage/strategy/anthropic-oauth-usage.strategy.ts +7 -15
  37. package/src/libs/subscription-usage/strategy/codemap.md +5 -41
  38. package/src/libs/subscription-usage/strategy/openai-codex-usage.strategy.ts +8 -15
  39. package/src/libs/subscription-usage/subscription-usage-api.util.ts +44 -67
  40. package/src/libs/subscription-usage/subscription-usage-cache.ts +89 -0
  41. package/src/schemas/auto-session-name.config.schema.ts +9 -2
  42. package/src/schemas/codemap.md +1 -1
  43. package/src/schemas/config.schema.ts +1 -1
  44. package/src/schemas/custom-footer-config.schema.ts +0 -4
  45. package/src/extensions/custom-footer/progress-bar.ts +0 -16
  46. package/src/extensions/custom-footer/subscription-usage-manager.ts +0 -91
@@ -21,7 +21,7 @@ import { fitToTerminalHeight, hintRow, normalizeTerminalRows, padLine, singleLin
21
21
  import type { Hint, ModalLayer, ModalTab, NavigationScheme } from './types';
22
22
 
23
23
  /** Framing style: inline rules, or a rounded border for host-centered overlays. */
24
- export type ModalFrame = 'inline' | 'bordered';
24
+ export type ModalFrame = 'inline' | 'bordered' | 'none';
25
25
 
26
26
  /** Height policy: natural content height, or bounded to half the terminal. */
27
27
  export type ModalHeight = 'auto' | 'half';
@@ -37,6 +37,8 @@ export interface ModalDialogOptions<TResult> {
37
37
  /** Navigation scheme; defaults to the host keybindings scheme. */
38
38
  navigation?: NavigationScheme;
39
39
  frame?: ModalFrame;
40
+ /** Additional footer hints, inserted before Esc. */
41
+ extraHints?: Hint[] | (() => Hint[]);
40
42
  height?: ModalHeight;
41
43
  /** Optional title line rendered above the tab strip. */
42
44
  title?: string | (() => string);
@@ -59,6 +61,7 @@ export class ModalDialog<TResult> implements Component, Focusable {
59
61
  private readonly layerStacks = new Map<ModalTab, ModalLayer[]>();
60
62
  private activeTabIndex: number;
61
63
  private _focused = false;
64
+ private extraHints: Hint[] | (() => Hint[]);
62
65
 
63
66
  public constructor(
64
67
  private readonly tui: TUI,
@@ -70,6 +73,7 @@ export class ModalDialog<TResult> implements Component, Focusable {
70
73
  this.scheme = options.navigation ?? new PiKeybindingsScheme(keybindings);
71
74
  this.frame = options.frame ?? 'inline';
72
75
  this.height = options.height ?? 'auto';
76
+ this.extraHints = options.extraHints ?? [];
73
77
  this.activeTabIndex = Math.min(Math.max(0, options.initialTabIndex ?? 0), options.tabs.length - 1);
74
78
 
75
79
  for (const tab of options.tabs) {
@@ -118,6 +122,14 @@ export class ModalDialog<TResult> implements Component, Focusable {
118
122
  this.options.onComplete(result);
119
123
  }
120
124
 
125
+ public setExtraHints(hints: Hint[]): void {
126
+ this.extraHints = hints;
127
+ }
128
+
129
+ public resetNavigation(): void {
130
+ this.scheme.reset();
131
+ }
132
+
121
133
  public handleInput(data: string): void {
122
134
  if (this.options.tabs.length > 1) {
123
135
  if (matchesKey(data, Key.shift('tab'))) {
@@ -163,7 +175,8 @@ export class ModalDialog<TResult> implements Component, Focusable {
163
175
  const rule = this.theme.fg('border', '─'.repeat(safeWidth));
164
176
  const lines = [rule, ...this.buildContentLines(safeWidth, this.contentHeight()), rule];
165
177
  const budget = this.heightBudget();
166
- return budget === undefined ? lines : fitToTerminalHeight(lines, budget, rule);
178
+ const fitted = budget === undefined ? lines : fitToTerminalHeight(lines, budget, rule);
179
+ return this.frame === 'none' ? fitted.slice(1, -1) : fitted;
167
180
  }
168
181
 
169
182
  // === Input routing internals ===
@@ -291,6 +304,7 @@ export class ModalDialog<TResult> implements Component, Focusable {
291
304
  const target = layer ?? this.activeTab;
292
305
  const hints: Hint[] = [...this.scheme.hints(layer === undefined ? 'Navigate' : 'Scroll'), ...target.hints()];
293
306
  if (this.options.tabs.length > 1) hints.push(['Tab', 'Switch']);
307
+ hints.push(...(typeof this.extraHints === 'function' ? this.extraHints() : this.extraHints));
294
308
  hints.push(['Esc', layer === undefined ? 'Close' : 'Back']);
295
309
  return hints;
296
310
  }
@@ -0,0 +1,33 @@
1
+ import type { Theme } from '@earendil-works/pi-coding-agent';
2
+ import { truncateToWidth, visibleWidth } from '@earendil-works/pi-tui';
3
+ import { labelWindow } from './label-window';
4
+
5
+ /** Render section labels inside the frame's top rule without adding height. */
6
+ export function renderSectionRule(theme: Theme, labels: string[], activeIndex: number, width: number, style: 'inline' | 'bordered'): string {
7
+ const safeWidth = Math.max(0, Math.floor(width));
8
+ const border = (text: string) => theme.fg('border', text);
9
+ const bordered = style === 'bordered' && safeWidth >= 2;
10
+ const inner = safeWidth - (bordered ? 2 : 0);
11
+ const separator = bordered ? ' ─ ' : ' ── ';
12
+ const prefix = bordered ? '─ ' : '── ';
13
+ const budget = Math.max(0, inner - visibleWidth(prefix) - 1);
14
+ const { start, end } = labelWindow(labels, activeIndex, budget, separator);
15
+ const parts: string[] = [];
16
+ if (start > 0) parts.push(theme.fg('muted', '…'));
17
+ for (let index = start; index <= end; index++) {
18
+ const label = labels[index] ?? '';
19
+ parts.push(index === activeIndex ? theme.fg('accent', theme.bold(label)) : theme.fg('muted', label));
20
+ }
21
+ if (end < labels.length - 1) parts.push(theme.fg('muted', '…'));
22
+ let strip = parts.join(border(separator));
23
+ let body: string;
24
+ if (visibleWidth(strip) > budget) {
25
+ const active = truncateToWidth(labels[activeIndex] ?? '', inner, '');
26
+ strip = theme.fg('accent', theme.bold(active));
27
+ body = strip;
28
+ } else {
29
+ body = border(prefix) + strip + border(' ');
30
+ }
31
+ body += border('─'.repeat(Math.max(0, inner - visibleWidth(body))));
32
+ return bordered ? border('╭') + body + border('╮') : body;
33
+ }
@@ -0,0 +1,105 @@
1
+ import type { Theme } from '@earendil-works/pi-coding-agent';
2
+ import { type Component, type Focusable, matchesKey, type TUI } from '@earendil-works/pi-tui';
3
+ import type { ModalDialog } from './modal-dialog';
4
+ import { renderSectionRule } from './section-strip';
5
+ import { padLine } from './text';
6
+
7
+ export type SectionFrame = 'inline' | 'bordered';
8
+
9
+ export interface ModalSection<TResult> {
10
+ label: string;
11
+ dialog: ModalDialog<TResult>;
12
+ onActivate?: () => void;
13
+ }
14
+
15
+ /** Frame and section routing around retained, caller-wired embedded dialogs. */
16
+ export class SectionedModal<TResult> implements Component, Focusable {
17
+ private readonly activated = new Set<number>();
18
+ private readonly frame: SectionFrame;
19
+ private activeIndex: number;
20
+ private _focused = false;
21
+
22
+ public constructor(
23
+ private readonly tui: TUI,
24
+ private readonly theme: Theme,
25
+ private readonly options: { sections: ModalSection<TResult>[]; frame?: SectionFrame; initialSectionIndex?: number },
26
+ ) {
27
+ if (options.sections.length === 0) throw new Error('SectionedModal requires at least one section');
28
+ this.frame = options.frame ?? 'inline';
29
+ this.activeIndex = Math.min(Math.max(0, options.initialSectionIndex ?? 0), options.sections.length - 1);
30
+ for (const section of options.sections) {
31
+ section.dialog.focused = false;
32
+ if (options.sections.length > 1) section.dialog.setExtraHints([['^]/^[', 'Section']]);
33
+ }
34
+ this.activate();
35
+ }
36
+
37
+ public get activeSectionIndex(): number {
38
+ return this.activeIndex;
39
+ }
40
+
41
+ public get focused(): boolean {
42
+ return this._focused;
43
+ }
44
+
45
+ public set focused(value: boolean) {
46
+ this._focused = value;
47
+ for (const [index, section] of this.options.sections.entries()) section.dialog.focused = value && index === this.activeIndex;
48
+ }
49
+
50
+ public handleInput(data: string): void {
51
+ if (matchesKey(data, 'ctrl+]')) {
52
+ this.switchSection(1);
53
+ } else if (data !== '\x1b' && matchesKey(data, 'ctrl+[')) {
54
+ this.switchSection(-1);
55
+ } else {
56
+ this.activeDialog().handleInput(data);
57
+ }
58
+ }
59
+
60
+ public render(width: number): string[] {
61
+ const safeWidth = Math.max(3, width);
62
+ const bordered = this.frame === 'bordered';
63
+ const inner = safeWidth - (bordered ? 2 : 0);
64
+ const lines = this.activeDialog().render(inner);
65
+ const border = (text: string) => this.theme.fg('border', text);
66
+ const top = renderSectionRule(
67
+ this.theme,
68
+ this.options.sections.map(section => section.label),
69
+ this.activeIndex,
70
+ safeWidth,
71
+ this.frame,
72
+ );
73
+ if (bordered) {
74
+ const side = border('│');
75
+ return [top, ...lines.map(line => `${side}${padLine(line, inner)}${side}`), border(`╰${'─'.repeat(inner)}╯`)];
76
+ }
77
+ return [top, ...lines, border('─'.repeat(safeWidth))];
78
+ }
79
+
80
+ public invalidate(): void {
81
+ for (const section of this.options.sections) section.dialog.invalidate();
82
+ }
83
+
84
+ private activeDialog(): ModalDialog<TResult> {
85
+ const section = this.options.sections[this.activeIndex];
86
+ if (section === undefined) throw new Error('SectionedModal requires at least one section');
87
+ return section.dialog;
88
+ }
89
+
90
+ private switchSection(direction: -1 | 1): void {
91
+ const count = this.options.sections.length;
92
+ if (count === 1) return;
93
+ this.activeDialog().resetNavigation();
94
+ this.activeIndex = (this.activeIndex + direction + count) % count;
95
+ this.focused = this._focused;
96
+ this.activate();
97
+ this.tui.requestRender();
98
+ }
99
+
100
+ private activate(): void {
101
+ if (this.activated.has(this.activeIndex)) return;
102
+ this.activated.add(this.activeIndex);
103
+ this.options.sections[this.activeIndex]?.onActivate?.();
104
+ }
105
+ }
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import type { Theme } from '@earendil-works/pi-coding-agent';
7
7
  import { truncateToWidth, visibleWidth } from '@earendil-works/pi-tui';
8
+ import { labelWindow } from './label-window';
8
9
  import { singleLine } from './text';
9
10
 
10
11
  const SEPARATOR = ' ';
@@ -18,32 +19,7 @@ export function renderTabStrip(theme: Theme, labels: string[], activeIndex: numb
18
19
  return styleLabels(theme, labels, activeIndex, 0, labels.length - 1, false, false);
19
20
  }
20
21
 
21
- let start = activeIndex;
22
- let end = activeIndex;
23
- let expandLeft = true;
24
- while (true) {
25
- const nextStart = expandLeft && start > 0 ? start - 1 : start;
26
- const nextEnd = !expandLeft && end < labels.length - 1 ? end + 1 : end;
27
- expandLeft = !expandLeft;
28
-
29
- if (nextStart === start && nextEnd === end) {
30
- if ((start === 0 || nextStart === start) && (end === labels.length - 1 || nextEnd === end)) break;
31
- continue;
32
- }
33
-
34
- const candidate = plainViewport(labels, nextStart, nextEnd);
35
- if (visibleWidth(candidate) <= safeWidth) {
36
- start = nextStart;
37
- end = nextEnd;
38
- continue;
39
- }
40
-
41
- const otherStart = start > 0 ? start - 1 : start;
42
- const otherEnd = end < labels.length - 1 ? end + 1 : end;
43
- if ((otherStart === start && otherEnd === end) || visibleWidth(plainViewport(labels, otherStart, otherEnd)) > safeWidth) break;
44
- start = otherStart;
45
- end = otherEnd;
46
- }
22
+ const { start, end } = labelWindow(labels, activeIndex, safeWidth, SEPARATOR);
47
23
 
48
24
  const leftOmitted = start > 0;
49
25
  const rightOmitted = end < labels.length - 1;
@@ -2,27 +2,16 @@
2
2
 
3
3
  ## Responsibility
4
4
 
5
- Encapsulates fetching and normalizing subscription usage (rate-limit utilization) from external AI providers into a common `RateWindow` representation. It is the single place the system queries provider-specific usage APIs and turns their heterogeneous responses into a consistent, UI-friendly shape.
5
+ Shared subscription data pipeline for Claude and Codex, exported through `index.ts`.
6
6
 
7
- ## Design Patterns
7
+ - `subscription-usage-api.util.ts`: provider/auth/window types, supported-provider labels derived from strategies, shared fetch timeout and TTL constants, status-discriminated `UsageResult`, injectable API. Classifies no-auth, expired, HTTP errors, network/timeout, unavailable and ok; owns fetch timeout and error catching. Malformed JSON is unavailable; fetch and abort failures remain network.
8
+ - `credential-resolver.ts`: verifies stored OAuth auth through PathUtil and RawDataParser, asks the latest host context for refreshed tokens, falls back to stored access. Codex account id comes from stored accountId or defensive JWT decoding.
9
+ - `subscription-usage-cache.ts`: shared injected cache with TTL, per-provider in-flight deduplication, forced refresh, retained last-success windows/timestamp, and completion subscribers. Includes provider aliases and soonest-reset window selection.
10
+ - `pace.ts`: pure elapsed-window pace and relative reset formatting.
11
+ - `progress-bar.ts`: pure percentage clamp and glyph-configurable bar (defaults █/░).
12
+ - `provider-color.ts`: fixed shared provider colors (Claude #D97706, Codex #10B981), exported as PROVIDER_USAGE_COLORS and providerUsageColor; no configuration dependency.
13
+ - `strategy/`: pure request construction and JSON normalization; no network I/O.
8
14
 
9
- - **Strategy**: `SubscriptionUsageApi` consumes a `SubscriptionUsageStrategy` (`AnthropicOauthUsageStrategy`, `OpenAiCodexUsageStrategy`) without knowing provider-specific details.
10
- - **Adapter / Normalization**: each strategy adapts a provider response to the shared `RateWindow[]` model (`label`, `usedPercent`, `resetAt`).
11
- - **Safe parsing**: `RawDataParser` guards against unexpected JSON shapes and missing fields.
12
- - **Utility API class**: `SubscriptionUsageApi` wraps auth loading, fetching, and formatting in one injectable-style class.
15
+ ## Flow
13
16
 
14
- ## Data & Control Flow
15
-
16
- 1. A caller invokes `SubscriptionUsageApi.fetchUsage(strategy)`.
17
- 2. The API loads provider OAuth credentials from the local auth config via `PathUtil.findPiAuthConfig()`.
18
- 3. It calls `strategy.fetchUsage(auth)`.
19
- 4. The strategy performs a provider HTTP request, parses JSON, and maps relevant fields to `RateWindow[]`.
20
- 5. The API wraps the result in `FetchUsageResponse` (`label`, `rateWindow`).
21
- 6. `formatResetDescription(resetAt)` converts reset timestamps to human-readable relative strings (`5m`, `2h30m`, `1d`, etc.).
22
-
23
- ## Integration Points
24
-
25
- - **Local auth config**: `PathUtil.findPiAuthConfig()` supplies `SubscriptionAuthconfig`, which maps providers to `{ access, accountId }` objects.
26
- - **Anthropic API**: `AnthropicOauthUsageStrategy` calls `https://api.anthropic.com/api/oauth/usage` with `Authorization: Bearer <token>` and `anthropic-beta: oauth-2025-04-20`.
27
- - **OpenAI Codex API**: `OpenAiCodexUsageStrategy` calls `https://chatgpt.com/backend-api/wham/usage` with bearer token and optional `ChatGPT-Account-Id` header.
28
- - **Shared utilities**: depends on `src/utils/path.util` for config discovery and `src/utils/raw-data-parser.util` for defensive JSON parsing.
17
+ Consumers ensure freshness or force refresh → cache picks strategy → API resolves credentials and fetches → strategy parses windows with durations → cache stores status and last success, then notifies subscribers. Footer shows ok windows or last-success windows for network/http-error/unavailable; no-auth/expired hide usage. Other consumers can retain earlier windows alongside failure status.
@@ -0,0 +1,44 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import type { ExtensionContext } from '@earendil-works/pi-coding-agent';
3
+ import { PathUtil } from '../../utils/path.util';
4
+ import { RawDataParser } from '../../utils/raw-data-parser.util';
5
+ import type { CredentialResolver } from './subscription-usage-api.util';
6
+
7
+ function jwtAccountId(token: string): string | undefined {
8
+ try {
9
+ const payload = token.split('.')[1];
10
+ if (!payload) return undefined;
11
+ const claims = RawDataParser.asRecord(JSON.parse(Buffer.from(payload, 'base64url').toString('utf8')));
12
+ const auth = RawDataParser.asRecord(claims?.['https://api.openai.com/auth']);
13
+ return RawDataParser.stringValue(auth?.chatgpt_account_id);
14
+ } catch {
15
+ return undefined;
16
+ }
17
+ }
18
+
19
+ export function createHostCredentialResolver(getCtx: () => ExtensionContext | undefined): CredentialResolver {
20
+ return async provider => {
21
+ try {
22
+ const path = PathUtil.findPiAuthConfig();
23
+ if (!path.exists) return undefined;
24
+ const config = RawDataParser.asRecord(JSON.parse(readFileSync(path.path, 'utf8')));
25
+ const stored = RawDataParser.asRecord(config?.[provider]);
26
+ if (!stored || (stored.type !== undefined && stored.type !== 'oauth')) return undefined;
27
+ let token: string | undefined;
28
+ try {
29
+ const resolved = await getCtx()?.modelRegistry.getProviderAuth(provider);
30
+ token = RawDataParser.stringValue(resolved?.auth?.apiKey);
31
+ } catch {
32
+ // Stored access is the verified fallback when host refresh fails.
33
+ }
34
+ token ||= RawDataParser.stringValue(stored.access);
35
+ if (!token) return undefined;
36
+ return {
37
+ token,
38
+ accountId: provider === 'openai-codex' ? RawDataParser.stringValue(stored.accountId) || jwtAccountId(token) : undefined,
39
+ };
40
+ } catch {
41
+ return undefined;
42
+ }
43
+ };
44
+ }
@@ -0,0 +1,8 @@
1
+ export * from './credential-resolver';
2
+ export * from './pace';
3
+ export * from './progress-bar';
4
+ export * from './provider-color';
5
+ export * from './strategy/anthropic-oauth-usage.strategy';
6
+ export * from './strategy/openai-codex-usage.strategy';
7
+ export * from './subscription-usage-api.util';
8
+ export * from './subscription-usage-cache';
@@ -0,0 +1,28 @@
1
+ import { clampPercent } from './progress-bar';
2
+ import type { RateWindow } from './subscription-usage-api.util';
3
+
4
+ export function computePace(window: RateWindow, now = Date.now()): { elapsedPercent: number; pace: 'limit' | 'ahead' | 'on-pace' } | undefined {
5
+ if (
6
+ !window.resetAt ||
7
+ !window.windowSeconds ||
8
+ window.windowSeconds <= 0 ||
9
+ !Number.isFinite(window.windowSeconds) ||
10
+ !Number.isFinite(window.resetAt.getTime())
11
+ )
12
+ return undefined;
13
+ const elapsedPercent = clampPercent(100 * (1 - (window.resetAt.getTime() - now) / (window.windowSeconds * 1000)));
14
+ return { elapsedPercent, pace: window.usedPercent >= 100 ? 'limit' : window.usedPercent > elapsedPercent ? 'ahead' : 'on-pace' };
15
+ }
16
+
17
+ export function formatResetDescription(date: Date, now = Date.now()): string {
18
+ const diffMs = date.getTime() - now;
19
+ if (diffMs <= 0) return 'now';
20
+ const minutes = Math.floor(diffMs / 60000);
21
+ if (minutes < 60) return `${minutes}m`;
22
+ const hours = Math.floor(minutes / 60);
23
+ const remainingMinutes = minutes % 60;
24
+ if (hours < 24) return remainingMinutes > 0 ? `${hours}h${remainingMinutes}m` : `${hours}h`;
25
+ const days = Math.floor(hours / 24);
26
+ const remainingHours = hours % 24;
27
+ return remainingHours > 0 ? `${days}d${remainingHours}h` : `${days}d`;
28
+ }
@@ -0,0 +1,13 @@
1
+ export function clampPercent(n: number): number {
2
+ return Number.isFinite(n) ? Math.max(0, Math.min(100, n)) : 0;
3
+ }
4
+
5
+ export function renderProgressBar(
6
+ usedPercent: number,
7
+ width = 10,
8
+ glyphs: { filled: string; empty: string } = { filled: '█', empty: '░' },
9
+ ): { filled: string; empty: string } {
10
+ const barWidth = Number.isFinite(width) ? Math.max(0, Math.floor(width)) : 0;
11
+ const filledCount = Math.round((clampPercent(usedPercent) / 100) * barWidth);
12
+ return { filled: glyphs.filled.repeat(filledCount), empty: glyphs.empty.repeat(barWidth - filledCount) };
13
+ }
@@ -0,0 +1,10 @@
1
+ import type { SubscriptionProvider } from './subscription-usage-api.util';
2
+
3
+ export const PROVIDER_USAGE_COLORS: Readonly<Record<SubscriptionProvider, string>> = {
4
+ anthropic: '#D97706',
5
+ 'openai-codex': '#10B981',
6
+ };
7
+
8
+ export function providerUsageColor(provider: SubscriptionProvider): string {
9
+ return PROVIDER_USAGE_COLORS[provider];
10
+ }
@@ -1,21 +1,13 @@
1
1
  import { RawDataParser } from '../../../utils/raw-data-parser.util';
2
- import {
3
- type ProviderAuth,
4
- type RateWindow,
5
- SUBSCRIPTION_USAGE_FETCH_TIMEOUT_MS,
6
- type SubscriptionUsageStrategy,
7
- } from '../subscription-usage-api.util';
2
+ import type { ProviderAuth, RateWindow, SubscriptionUsageStrategy } from '../subscription-usage-api.util';
8
3
 
9
4
  export class AnthropicOauthUsageStrategy implements SubscriptionUsageStrategy {
10
5
  readonly provider = 'anthropic';
11
6
  readonly label = 'Claude';
12
7
 
13
- async fetchUsage(auth: ProviderAuth) {
14
- const response = await fetch(this.request(auth));
15
- if (!response.ok) return;
16
-
17
- const data = RawDataParser.asRecord(await response.json());
18
- if (!data) return;
8
+ parse(json: unknown): RateWindow[] {
9
+ const data = RawDataParser.asRecord(json);
10
+ if (!data) return [];
19
11
 
20
12
  const windows: RateWindow[] = [];
21
13
  for (const [key, label] of [
@@ -30,16 +22,16 @@ export class AnthropicOauthUsageStrategy implements SubscriptionUsageStrategy {
30
22
  windows.push({
31
23
  label,
32
24
  usedPercent,
25
+ windowSeconds: key === 'five_hour' ? 18000 : 604800,
33
26
  resetAt: resetDate && Number.isFinite(resetDate.getTime()) ? resetDate : undefined,
34
27
  });
35
28
  }
36
- return windows.length > 0 ? windows : undefined;
29
+ return windows;
37
30
  }
38
31
 
39
- private request(opts: ProviderAuth) {
32
+ request(opts: ProviderAuth): Request {
40
33
  return new Request('https://api.anthropic.com/api/oauth/usage', {
41
34
  method: 'GET',
42
- signal: AbortSignal.timeout(SUBSCRIPTION_USAGE_FETCH_TIMEOUT_MS),
43
35
  headers: {
44
36
  Authorization: `Bearer ${opts.token}`,
45
37
  'anthropic-beta': 'oauth-2025-04-20',
@@ -1,44 +1,8 @@
1
- # subscription-usage strategy codemap
1
+ # subscription-usage strategies
2
2
 
3
- ## Responsibility
3
+ Pure `SubscriptionUsageStrategy` implementations expose `provider`, `label`, `request(auth): Request`, and `parse(json: unknown): RateWindow[]`. Network I/O, timeout and status classification belong to SubscriptionUsageApi, not strategies. Unknown shapes return an empty array.
4
4
 
5
- This directory contains provider-specific implementations of `SubscriptionUsageStrategy`.
6
- Each strategy is responsible for:
5
+ - `anthropic-oauth-usage.strategy.ts`: bearer-authenticated Anthropic OAuth usage request with beta header. Parses five_hour (5h, 18000 seconds) and seven_day (Week, 604800 seconds), utilization and optional valid reset dates.
6
+ - `openai-codex-usage.strategy.ts`: bearer-authenticated wham usage request with optional ChatGPT-Account-Id. Keeps primary, secondary and named additional limits. Uses reported limit_window_seconds, falling back to 10800 / 86400 seconds; normalizes used percentage and reset epoch seconds.
7
7
 
8
- - Building the authenticated HTTP request for a single provider.
9
- - Fetching usage data from that provider's API.
10
- - Parsing the raw JSON response into a normalized `RateWindow[]`.
11
- - Returning `undefined` when no usable usage data is available.
12
-
13
- Current strategies:
14
-
15
- - `AnthropicOauthUsageStrategy` — fetches Anthropic OAuth usage and exposes the `five_hour` and `seven_day` windows.
16
- - `OpenAiCodexUsageStrategy` — fetches OpenAI Codex usage and exposes the main `rate_limit` windows plus any `additional_rate_limits`.
17
-
18
- ## Design Patterns
19
-
20
- - **Strategy pattern** — both classes implement the common `SubscriptionUsageStrategy` interface, so the caller (`SubscriptionUsageApi`) can treat them uniformly.
21
- - **Encapsulation of provider details** — request construction, response parsing, and window labeling are kept private to each strategy.
22
- - **Defensive parsing** — unknown API responses are coerced safely through `RawDataParser` before being used.
23
- - **Helper decomposition** — the OpenAI strategy splits parsing into small private helpers (`pushRateLimitWindows`, `pushRateWindow`, `getResetDate`, `getWindowLabel`) to keep the main flow readable.
24
-
25
- ## Data & Control Flow
26
-
27
- 1. `SubscriptionUsageApi.fetchUsage(strategy)` loads provider credentials and calls `strategy.fetchUsage(auth)`.
28
- 2. Each strategy builds a provider-specific `Request` and calls `fetch`.
29
- 3. The JSON response is converted to a `Record<string, unknown>` via `RawDataParser.asRecord`.
30
- 4. Relevant fields are extracted:
31
- - **Anthropic**: iterates over `five_hour` and `seven_day`, reads `utilization` as `usedPercent`, and parses `resets_at` into a `Date`.
32
- - **OpenAI**: reads `rate_limit.primary_window` and `rate_limit.secondary_window`, then loops over `additional_rate_limits`.
33
- 5. Each discovered window is pushed as a `RateWindow` object with `label`, `usedPercent`, and optional `resetAt`.
34
- 6. The array is returned to `SubscriptionUsageApi`, which wraps it in a `FetchUsageResponse` keyed by the strategy's `label`.
35
-
36
- ## Integration Points
37
-
38
- - **Interface contract**: strategies implement `SubscriptionUsageStrategy` and use the `ProviderAuth`, `RateWindow`, and `SubscriptionProvider` types from `../subscription-usage-api.util`.
39
- - **Shared utility**: all parsing helpers come from `../../../utils/raw-data-parser.util` (`RawDataParser`).
40
- - **Network layer**: strategies use the global `fetch` API directly.
41
- - **Provider endpoints**:
42
- - Anthropic: `https://api.anthropic.com/api/oauth/usage` — authenticated with a `Bearer` token and the `anthropic-beta: oauth-2025-04-20` header.
43
- - OpenAI Codex: `https://chatgpt.com/backend-api/wham/usage` — authenticated with a `Bearer` token and an optional `ChatGPT-Account-Id` header.
44
- - **Consumer**: `SubscriptionUsageApi` orchestrates strategies, loads auth config via `PathUtil.findPiAuthConfig`, and formats results for downstream display.
8
+ Both use RawDataParser for defensive parsing and the shared auth/window contracts. Their requests have no timeout side effects; the API adds its abort signal.
@@ -1,10 +1,5 @@
1
1
  import { RawDataParser } from '../../../utils/raw-data-parser.util';
2
- import {
3
- type ProviderAuth,
4
- type RateWindow,
5
- SUBSCRIPTION_USAGE_FETCH_TIMEOUT_MS,
6
- type SubscriptionUsageStrategy,
7
- } from '../subscription-usage-api.util';
2
+ import type { ProviderAuth, RateWindow, SubscriptionUsageStrategy } from '../subscription-usage-api.util';
8
3
 
9
4
  const PRIMARY_WINDOW_FALLBACK_SECONDS = 10800;
10
5
  const SECONDARY_WINDOW_FALLBACK_SECONDS = 86400;
@@ -13,12 +8,9 @@ export class OpenAiCodexUsageStrategy implements SubscriptionUsageStrategy {
13
8
  readonly provider = 'openai-codex';
14
9
  readonly label = 'Codex';
15
10
 
16
- async fetchUsage(auth: ProviderAuth) {
17
- const response = await fetch(this.request(auth));
18
- if (!response.ok) return;
19
-
20
- const data = RawDataParser.asRecord(await response.json());
21
- if (!data) return;
11
+ parse(json: unknown): RateWindow[] {
12
+ const data = RawDataParser.asRecord(json);
13
+ if (!data) return [];
22
14
 
23
15
  const windows: RateWindow[] = [];
24
16
  this.pushRateLimitWindows(windows, RawDataParser.asRecord(data.rate_limit));
@@ -32,7 +24,7 @@ export class OpenAiCodexUsageStrategy implements SubscriptionUsageStrategy {
32
24
  this.pushRateLimitWindows(windows, RawDataParser.asRecord(entry.rate_limit), prefix);
33
25
  }
34
26
 
35
- return windows.length > 0 ? windows : undefined;
27
+ return windows;
36
28
  }
37
29
 
38
30
  private pushRateLimitWindows(windows: RateWindow[], rateLimit: Record<string, unknown> | undefined, prefix?: string): void {
@@ -44,10 +36,12 @@ export class OpenAiCodexUsageStrategy implements SubscriptionUsageStrategy {
44
36
  if (!window) return;
45
37
 
46
38
  const resetDate = this.getResetDate(window);
39
+ const seconds = RawDataParser.numberValue(window.limit_window_seconds);
47
40
  windows.push({
48
41
  label: this.getWindowLabel(RawDataParser.numberValue(window.limit_window_seconds), fallbackWindowSeconds, prefix),
49
42
  usedPercent: RawDataParser.numberValue(window.used_percent) ?? 0,
50
43
  resetAt: resetDate,
44
+ windowSeconds: seconds && seconds > 0 ? seconds : fallbackWindowSeconds,
51
45
  });
52
46
  }
53
47
 
@@ -67,10 +61,9 @@ export class OpenAiCodexUsageStrategy implements SubscriptionUsageStrategy {
67
61
  return prefix ? `${prefix} ${label}` : label;
68
62
  }
69
63
 
70
- private request(opts: ProviderAuth) {
64
+ request(opts: ProviderAuth): Request {
71
65
  return new Request('https://chatgpt.com/backend-api/wham/usage', {
72
66
  method: 'GET',
73
- signal: AbortSignal.timeout(SUBSCRIPTION_USAGE_FETCH_TIMEOUT_MS),
74
67
  headers: {
75
68
  Authorization: `Bearer ${opts.token}`,
76
69
  ...(opts?.accountId ? { 'ChatGPT-Account-Id': opts.accountId } : {}),