@astrosheep/pi-quota 0.5.1 → 0.5.2

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/README.md CHANGED
@@ -6,7 +6,7 @@ Compact quota status for Pi: Codex, Kimi and OpenCode Go work out of the box; ne
6
6
  pi install npm:@astrosheep/pi-quota
7
7
  ```
8
8
 
9
- Reload Pi after installing or changing settings. Use `/usage` for a persistent, context-free snapshot in the chat history. Automatic footer polling never adds chat items.
9
+ Reload Pi after installing or changing settings. Use `/usage` for a persistent, context-free snapshot covering every configured provider with a quota adapter, including the current one. Automatic footer polling never adds chat items.
10
10
 
11
11
  ## What it shows
12
12
 
@@ -18,7 +18,7 @@ Reload Pi after installing or changing settings. Use `/usage` for a persistent,
18
18
 
19
19
  A percentage always means **remaining**, not used. Unknown is `[?] ?`; an expired reset is `↺ due` with the stale percentage hidden until the next successful query. A wallet balance never becomes a percentage. Historical spend is not a quota.
20
20
 
21
- The footer shows at most two windows and `+N` for additional ones. `/usage` includes all windows; it does not open a modal or send messages to the model. Snapshots remain frozen at capture time. Errors replace stale values.
21
+ The footer shows at most two windows and `+N` for additional ones, for the current provider only. `/usage` queries all configured supported providers and includes all windows, grouped by provider; it does not open a modal or send messages to the model. Snapshots remain frozen at capture time. Errors replace stale values and are shown per provider.
22
22
 
23
23
  ## Configure providers
24
24
 
@@ -58,12 +58,12 @@ Pi model/auth → adapter → QuotaSnapshot → controller → footer / /usage /
58
58
 
59
59
  - `src/query/`: protocol-specific parsing, credential resolution, safe URLs, bounded GET client, state validation and controller. No Pi/TUI imports.
60
60
  - `src/config.ts`: strict global provider bindings.
61
- - `src/bar/`: pure compact rendering and persistent chat card.
61
+ - `src/bar/`: pure compact rendering and persistent multi-provider chat card.
62
62
  - `src/extension.ts` and `src/index.ts`: Pi lifecycle and auth bridge.
63
63
 
64
64
  `QuotaSnapshot` separates `balance` (wallet), `allowance` (finite key quota), `windows` (renewable limits), and optional `spend` (Today/Lifetime actual charge). This prevents unrelated amounts from sharing an ambiguous `Used` label. Custom adapters can be passed to `createQuotaExtension({ adapters: [...] })`; see `examples/custom-provider.ts`. Provider aliases are never inferred.
65
65
 
66
- The extension publishes structured state on `quota-bar:state:v1`. Use `createQuotaExtension({ footer: false })` to consume it without this extension's footer. Normal queries are throttled, cancellable, timeout-bounded and backed off after errors. `/usage` forces a fresh query. Switching provider discards old values immediately.
66
+ The extension publishes structured state on `quota-bar:state:v1`. Use `createQuotaExtension({ footer: false })` to consume it without this extension's footer. Normal queries are throttled, cancellable, timeout-bounded and backed off after errors. `/usage` forces a fresh query for every configured supported provider. Switching provider discards old footer values immediately.
67
67
 
68
68
  ## Development
69
69
 
package/package.json CHANGED
@@ -1,7 +1,9 @@
1
1
  {
2
2
  "name": "@astrosheep/pi-quota",
3
- "version": "0.5.1",
4
- "publishConfig": { "access": "public" },
3
+ "version": "0.5.2",
4
+ "publishConfig": {
5
+ "access": "public"
6
+ },
5
7
  "type": "module",
6
8
  "description": "Composable quota bar with Codex, Kimi, OpenCode Go, new-api, DeepSeek and Sub2API adapters",
7
9
  "keywords": [
package/src/bar/card.ts CHANGED
@@ -6,27 +6,39 @@ import type { QuotaState } from '../query/types.ts';
6
6
 
7
7
  export const USAGE_ENTRY = 'quota-bar:usage:v1';
8
8
 
9
- export interface UsageCard {
10
- version: 1;
11
- capturedAt: number;
12
- state: Exclude<QuotaState, { kind: 'loading' }>;
13
- }
9
+ export type UsageCard =
10
+ | { version: 1; capturedAt: number; state: Exclude<QuotaState, { kind: 'loading' }> }
11
+ | { version: 2; capturedAt: number; states: Exclude<QuotaState, { kind: 'loading' }>[] };
14
12
 
15
13
  export function captureUsage(state: QuotaState, now = Date.now()): UsageCard | undefined {
16
14
  if (state.kind === 'loading') return undefined;
17
- // Separate the persistent entry from the live controller's state/objects.
15
+ // Preserve v1 rendering for cards already saved in sessions.
18
16
  return { version: 1, capturedAt: now, state: structuredClone(state) };
19
17
  }
20
18
 
19
+ export function captureAllUsage(states: readonly QuotaState[], now = Date.now()): UsageCard {
20
+ return { version: 2, capturedAt: now, states: structuredClone(states.filter(
21
+ (state): state is Exclude<QuotaState, { kind: 'loading' }> => state.kind !== 'loading',
22
+ )) };
23
+ }
24
+
25
+ export function usageLines(card: UsageCard, paint?: Paint, barWidth = 20): string[] {
26
+ if (card.version === 1) return renderUsage(card.state, paint, card.capturedAt, barWidth);
27
+ if (card.states.length === 0) return ['No supported quota providers available.'];
28
+ return card.states.flatMap((state, index) => [
29
+ ...(index ? ['', ''] : []), ...renderUsage(state, paint, card.capturedAt, barWidth),
30
+ ]);
31
+ }
32
+
21
33
  export function usageCardComponent(card: UsageCard | undefined, paint?: Paint): Component {
22
34
  return {
23
35
  render(width: number): string[] {
24
36
  if (width <= 0) return [];
25
- if (!card || card.version !== 1 || !Number.isFinite(card.capturedAt)) {
37
+ if (!card || (card.version !== 1 && card.version !== 2) || !Number.isFinite(card.capturedAt)) {
26
38
  return new Text('Usage snapshot unavailable.', 0, 0).render(width);
27
39
  }
28
40
  // Rebuild on every render for theme/width changes, but freeze time at capture.
29
- const lines = renderUsage(card.state, paint, card.capturedAt, width < 55 ? 10 : 20);
41
+ const lines = usageLines(card, paint, width < 55 ? 10 : 20);
30
42
  // Wrapping, not clipping: long quota names remain readable in narrow terminals.
31
43
  return new Text(lines.join('\n'), 0, 0).render(width);
32
44
  },
package/src/extension.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';
2
- import { renderFooter, renderUsage } from './bar/quota.ts';
3
- import { captureUsage, USAGE_ENTRY, usageCardComponent } from './bar/card.ts';
2
+ import { renderFooter } from './bar/quota.ts';
3
+ import { captureAllUsage, USAGE_ENTRY, usageCardComponent, usageLines } from './bar/card.ts';
4
4
  import type { UsageCard } from './bar/card.ts';
5
5
  import { codexAdapter } from './query/codex.ts';
6
6
  import { kimiAdapter } from './query/kimi.ts';
@@ -8,7 +8,7 @@ import { openCodeGoAdapter } from './query/opencode-go.ts';
8
8
  import { QuotaController } from './query/controller.ts';
9
9
  import { createJsonClient } from './query/http.ts';
10
10
  import { AdapterRegistry } from './query/registry.ts';
11
- import type { ProviderAuth, QuotaAdapter } from './query/types.ts';
11
+ import type { ProviderAuth, QuotaAdapter, QuotaState } from './query/types.ts';
12
12
 
13
13
  export const STATUS_EVENT = 'quota-bar:state:v1';
14
14
  const STATUS_KEY = 'quota-bar';
@@ -58,29 +58,64 @@ export function createQuotaExtension(options: QuotaExtensionOptions = {}) {
58
58
  }
59
59
  };
60
60
 
61
+ const getJson = createJsonClient();
62
+
61
63
  const controller = new QuotaController({
62
- registry, getJson: createJsonClient(), intervalMs: options.intervalMs, timeoutMs: options.timeoutMs,
64
+ registry, getJson, intervalMs: options.intervalMs, timeoutMs: options.timeoutMs,
63
65
  onState(state) {
64
66
  paintFooter();
65
67
  pi.events.emit(STATUS_EVENT, state); // Structured data, no credentials or ANSI.
66
68
  },
67
69
  });
68
70
 
71
+ const resolveAuth = (ctx: ExtensionContext) => async (provider: string): Promise<ProviderAuth | undefined> => {
72
+ const resolved = await ctx.modelRegistry.getProviderAuth(provider);
73
+ if (!resolved) return undefined;
74
+ const headers: Record<string, string | undefined> = {};
75
+ for (const [name, value] of Object.entries(resolved.auth.headers ?? {})) {
76
+ if (typeof value === 'string') headers[name] = value;
77
+ }
78
+ const auth: ProviderAuth = { ...resolved.auth, headers };
79
+ // A model-level custom endpoint must not be mistaken for an official account.
80
+ if (ctx.model?.provider === provider && ctx.model.baseUrl) auth.baseUrl = ctx.model.baseUrl;
81
+ return auth;
82
+ };
83
+
69
84
  const refresh = (force = false): Promise<void> => {
70
85
  const ctx = current;
71
86
  if (!ctx?.hasUI) return Promise.resolve();
72
- return controller.refresh(async provider => {
73
- const resolved = await ctx.modelRegistry.getProviderAuth(provider);
74
- if (!resolved) return undefined;
75
- const headers: Record<string, string | undefined> = {};
76
- for (const [name, value] of Object.entries(resolved.auth.headers ?? {})) {
77
- if (typeof value === 'string') headers[name] = value;
87
+ return controller.refresh(resolveAuth(ctx), force);
88
+ };
89
+
90
+ const supportedProviders = (ctx: ExtensionContext): string[] => {
91
+ const providers: string[] = [];
92
+ const seen = new Set<string>();
93
+ const add = (provider: string | undefined) => {
94
+ if (provider && registry.get(provider) && !seen.has(provider)) {
95
+ seen.add(provider);
96
+ providers.push(provider);
78
97
  }
79
- const auth: ProviderAuth = { ...resolved.auth, headers };
80
- // A model-level custom endpoint must not be mistaken for an official account.
81
- if (ctx.model?.provider === provider && ctx.model.baseUrl) auth.baseUrl = ctx.model.baseUrl;
82
- return auth;
83
- }, force);
98
+ };
99
+ add(ctx.model?.provider);
100
+ for (const model of ctx.modelRegistry.getAll()) add(model.provider);
101
+ return providers;
102
+ };
103
+
104
+ const queryProvider = async (provider: string, getAuth: ReturnType<typeof resolveAuth>): Promise<QuotaState> => {
105
+ const adapter = registry.get(provider);
106
+ if (!adapter) return { kind: 'error', provider, label: provider, code: 'unsupported-auth' };
107
+ if (provider === selectedProvider) {
108
+ // The footer already owns this provider's lifecycle and cache; do not fork it.
109
+ await controller.refresh(getAuth, true);
110
+ return controller.state;
111
+ }
112
+ const scratch = new QuotaController({
113
+ registry, getJson, intervalMs: options.intervalMs, timeoutMs: options.timeoutMs,
114
+ onState() {},
115
+ });
116
+ scratch.select(provider);
117
+ await scratch.refresh(getAuth, true);
118
+ return scratch.state;
84
119
  };
85
120
 
86
121
  const bind = (ctx: ExtensionContext, select = false, provider = ctx.model?.provider) => {
@@ -122,23 +157,24 @@ export function createQuotaExtension(options: QuotaExtensionOptions = {}) {
122
157
  });
123
158
 
124
159
  pi.registerCommand('usage', {
125
- description: 'Query current provider quota and add a snapshot to the chat history',
160
+ description: 'Query quota for every configured supported provider and add snapshots to the chat history',
126
161
  handler: async (_args, ctx) => {
127
162
  if (!ctx.hasUI) return;
128
163
  bind(ctx);
129
164
  const generation = ++commandGeneration;
130
- if (ctx.mode === 'tui') ctx.ui.setWidget(USAGE_WIDGET, ['Loading…']);
165
+ if (ctx.mode === 'tui') ctx.ui.setWidget(USAGE_WIDGET, ['Quota …']);
131
166
  try {
132
- await refresh(true);
167
+ const getAuth = resolveAuth(ctx);
168
+ const providers = supportedProviders(ctx);
169
+ const states = await Promise.all(providers.map(provider => queryProvider(provider, getAuth)));
133
170
  // Never append via a stale Pi runtime, or label a replacement model's data
134
171
  // as the result of the original command. A newer command owns its result.
135
172
  if (!current || generation !== commandGeneration) return;
136
- const card = captureUsage(controller.state);
137
- if (!card) return;
173
+ const card = captureAllUsage(states);
138
174
  pi.appendEntry<UsageCard>(USAGE_ENTRY, card);
139
175
  // Custom entry renderers are TUI-only; RPC clients still get readable output.
140
176
  if (ctx.mode !== 'tui') {
141
- ctx.ui.notify(renderUsage(card.state, undefined, card.capturedAt).join('\n'), 'info');
177
+ ctx.ui.notify(usageLines(card, undefined).join('\n'), 'info');
142
178
  }
143
179
  } finally {
144
180
  // An older request must not clear a newer command's loading indicator.
@@ -19,6 +19,10 @@ export class AdapterRegistry {
19
19
  get(provider: string | undefined): QuotaAdapter | undefined {
20
20
  return provider ? this.adapters.get(provider) : undefined;
21
21
  }
22
+
23
+ list(): readonly QuotaAdapter[] {
24
+ return [...this.adapters.values()];
25
+ }
22
26
  }
23
27
 
24
28
  // Validate even custom adapter output before it reaches the bar.