pi-usage-hub 1.0.7 → 1.0.9

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
@@ -27,6 +27,8 @@ Inside the panel, **Tab** switches between Quota and Session. In the Quota view,
27
27
 
28
28
  ![pi-usage-hub quota panel](assets/usage-hub-panel.png)
29
29
 
30
+ ![pi-usage-hub session panel](assets/usage-hub-session.png)
31
+
30
32
  ## Configuration
31
33
 
32
34
  Create `~/.pi/agent/pi-usage-hub.json`. Provider order is preserved in the panel.
@@ -70,6 +72,7 @@ Create `~/.pi/agent/pi-usage-hub.json`. Provider order is preserved in the panel
70
72
  | `name` | no | Instance key; defaults to `type`, then `type-2`, `type-3`, and so on |
71
73
  | `matchProviders` | no | Additional `model.provider` values mapped to this entry |
72
74
  | `shortLabel` / `label` | no | Override the footer label or panel title |
75
+ | `hidden` | no | Exclude from panel and footer; `/usage-hub login` still works |
73
76
 
74
77
  ### Provider types
75
78
 
@@ -158,7 +161,7 @@ pi.on("agent_end", (_event, ctx) => {
158
161
 
159
162
  // Inside footer render():
160
163
  // const usageText = usageHub?.getSummary(ctx.model);
161
- // "XAI 87% · ↻ 3d 16h / M48%"
164
+ // "XAI 87% · ↻ 3d 16h"
162
165
 
163
166
  pi.on("session_shutdown", async () => {
164
167
  offReady();
Binary file
Binary file
package/core/config.ts CHANGED
@@ -65,6 +65,7 @@ function parseProviderEntry(
65
65
  matchProviders: asStringArray(raw.matchProviders),
66
66
  shortLabel: typeof raw.shortLabel === "string" ? raw.shortLabel : undefined,
67
67
  label: typeof raw.label === "string" ? raw.label : undefined,
68
+ hidden: typeof raw.hidden === "boolean" ? raw.hidden : undefined,
68
69
  };
69
70
 
70
71
  switch (type) {
package/core/registry.ts CHANGED
@@ -31,6 +31,7 @@ export class ProviderRegistry {
31
31
 
32
32
  detectActive(): UsageProvider[] {
33
33
  return this.list().filter(p => {
34
+ if (p.hidden) return false;
34
35
  try {
35
36
  return p.detect();
36
37
  } catch {
package/index.ts CHANGED
@@ -60,7 +60,7 @@ export default function register(pi: ExtensionAPI) {
60
60
  if (d?.key) hub.unregister(d.key);
61
61
  });
62
62
 
63
- // Emit now and again on session_start so late listeners (footer-hub) still get the hub.
63
+ // Emit now and again on session_start so late listeners still get the hub.
64
64
  pi.events.emit("pi-usage-hub:ready", hub);
65
65
  pi.on("session_start", async () => {
66
66
  pi.events.emit("pi-usage-hub:ready", hub);
@@ -189,7 +189,7 @@ export default function register(pi: ExtensionAPI) {
189
189
  const termWidth = process.stdout.columns ?? 80;
190
190
  return {
191
191
  width: Math.min(Math.floor(termWidth * 0.65), 100),
192
- minWidth: 74,
192
+ minWidth: 80,
193
193
  maxHeight: "80%",
194
194
  anchor: "center",
195
195
  visible: (_tw, termHeight) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-usage-hub",
3
- "version": "1.0.7",
3
+ "version": "1.0.9",
4
4
  "description": "Usage hub for pi — provider quota/balance registry with cache, /usage-hub panel, and pull API",
5
5
  "keywords": [
6
6
  "pi",
package/providers/ark.ts CHANGED
@@ -108,6 +108,7 @@ export function makeArkProvider(name: string, cfg: ArkConfig = {}): UsageProvide
108
108
  matchProviders: cfg.matchProviders ?? [name, "ark"],
109
109
  shortLabel: cfg.shortLabel ?? "ARK",
110
110
  label: cfg.label ?? "ARK Coding",
111
+ hidden: cfg.hidden,
111
112
  detect: () => resolveCookies(cfg) !== null,
112
113
 
113
114
  fetchUsage: async (): Promise<UsageReport> => {
@@ -10,6 +10,7 @@ export function makeDeepseekProvider(name: string, cfg: DeepseekConfig): UsagePr
10
10
  matchProviders: cfg.matchProviders ?? [name, "deepseek"],
11
11
  shortLabel: cfg.shortLabel ?? "DS",
12
12
  label: cfg.label ?? "DeepSeek",
13
+ hidden: cfg.hidden,
13
14
  detect: () => !!apiKey,
14
15
 
15
16
  fetchUsage: async (): Promise<UsageReport> => {
package/providers/kiro.ts CHANGED
@@ -272,6 +272,7 @@ export function makeKiroProvider(name: string, cfg: KiroConfig = {}): UsageProvi
272
272
  matchProviders: cfg.matchProviders ?? [name, "kiro"],
273
273
  shortLabel: cfg.shortLabel ?? "KIRO",
274
274
  label: cfg.label ?? "Kiro",
275
+ hidden: cfg.hidden,
275
276
  // Presence in config enables the provider; auth comes from auth.json.
276
277
  detect: () => true,
277
278
 
@@ -60,6 +60,7 @@ export function makeNewApiProvider(name: string, cfg: NewApiConfig): UsageProvid
60
60
  matchProviders: cfg.matchProviders ?? [name],
61
61
  shortLabel,
62
62
  label: cfg.label ?? `NewAPI ${shortLabel}`,
63
+ hidden: cfg.hidden,
63
64
  detect: () => !!(cfg.host && cfg.token && cfg.userId),
64
65
 
65
66
  fetchUsage: async (): Promise<UsageReport> => {
@@ -47,6 +47,7 @@ export function makeOpencodeGoProvider(name: string, cfg: OpencodeGoConfig): Usa
47
47
  matchProviders: cfg.matchProviders ?? [name, "opencode-go"],
48
48
  shortLabel: cfg.shortLabel ?? "OCG",
49
49
  label: cfg.label ?? "OpenCode Go",
50
+ hidden: cfg.hidden,
50
51
  detect: () => !!workspaceId && (!!resolveAuth(cfg) || !manual),
51
52
 
52
53
  fetchUsage: async (): Promise<UsageReport> => {
package/providers/xai.ts CHANGED
@@ -22,12 +22,6 @@ interface XaiCredentials {
22
22
  tokenEndpoint?: string;
23
23
  }
24
24
 
25
- interface MonthlyUsage {
26
- monthlyLimit: number;
27
- used: number;
28
- billingPeriodEnd: string;
29
- }
30
-
31
25
  interface WeeklyUsage {
32
26
  creditUsagePercent: number;
33
27
  billingPeriodEnd: string;
@@ -102,12 +96,11 @@ function isFresh(credentials: XaiCredentials): boolean {
102
96
  }
103
97
 
104
98
  function validateTokenEndpoint(url: string): string {
105
- const parsed = new URL(url);
106
- const host = parsed.hostname.toLowerCase();
107
- if (parsed.protocol !== "https:" || (host !== "x.ai" && !host.endsWith(".x.ai"))) {
108
- throw new Error(`unexpected xAI token endpoint: ${url}`);
99
+ const normalized = url.replace(/\/$/, "");
100
+ if (normalized !== DEFAULT_TOKEN_ENDPOINT) {
101
+ throw new Error("unexpected xAI token endpoint — run /login xai-auth");
109
102
  }
110
- return url;
103
+ return DEFAULT_TOKEN_ENDPOINT;
111
104
  }
112
105
 
113
106
  async function refreshCredentials(credentials: XaiCredentials): Promise<XaiCredentials> {
@@ -156,38 +149,17 @@ function resetsInFromIso(iso: string | undefined): string | undefined {
156
149
  return formatDurationMs(end - Date.now());
157
150
  }
158
151
 
159
- function parseMonthlyUsage(payload: unknown): MonthlyUsage {
152
+ function parseWeeklyUsage(payload: unknown): WeeklyUsage {
160
153
  if (!payload || typeof payload !== "object") throw new Error("invalid billing payload");
161
154
  const config = (payload as Record<string, unknown>).config;
162
155
  if (!config || typeof config !== "object") throw new Error("invalid billing payload");
163
156
 
164
- const monthlyLimit = ((config as Record<string, unknown>).monthlyLimit as Record<string, unknown>)?.val;
165
- const used = ((config as Record<string, unknown>).used as Record<string, unknown>)?.val;
166
- const billingPeriodEnd = (config as Record<string, unknown>).billingPeriodEnd;
167
-
168
- if (
169
- typeof monthlyLimit !== "number" ||
170
- !Number.isFinite(monthlyLimit) ||
171
- typeof used !== "number" ||
172
- !Number.isFinite(used) ||
173
- typeof billingPeriodEnd !== "string" ||
174
- !Number.isFinite(new Date(billingPeriodEnd).getTime())
175
- ) {
176
- throw new Error("invalid billing payload");
177
- }
178
-
179
- return { monthlyLimit, used, billingPeriodEnd };
180
- }
181
-
182
- function parseWeeklyUsage(payload: unknown): WeeklyUsage | undefined {
183
- if (!payload || typeof payload !== "object") return undefined;
184
- const config = (payload as Record<string, unknown>).config;
185
- if (!config || typeof config !== "object") return undefined;
186
-
187
157
  const currentPeriod = (config as Record<string, unknown>).currentPeriod as
188
158
  | Record<string, unknown>
189
159
  | undefined;
190
- if (currentPeriod?.type !== "USAGE_PERIOD_TYPE_WEEKLY") return undefined;
160
+ if (currentPeriod?.type !== "USAGE_PERIOD_TYPE_WEEKLY") {
161
+ throw new Error("could not parse usage");
162
+ }
191
163
 
192
164
  const creditUsagePercent = (config as Record<string, unknown>).creditUsagePercent;
193
165
  const billingPeriodEnd = (config as Record<string, unknown>).billingPeriodEnd;
@@ -197,7 +169,7 @@ function parseWeeklyUsage(payload: unknown): WeeklyUsage | undefined {
197
169
  typeof billingPeriodEnd !== "string" ||
198
170
  !Number.isFinite(new Date(billingPeriodEnd).getTime())
199
171
  ) {
200
- return undefined;
172
+ throw new Error("could not parse usage");
201
173
  }
202
174
 
203
175
  return { creditUsagePercent, billingPeriodEnd };
@@ -216,76 +188,83 @@ async function fetchJson(url: string, token: string): Promise<unknown> {
216
188
  },
217
189
  signal: controller.signal,
218
190
  });
219
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
191
+ if (!res.ok) {
192
+ const err = new Error(`HTTP ${res.status}`) as Error & { status?: number };
193
+ err.status = res.status;
194
+ throw err;
195
+ }
220
196
  return await res.json();
221
197
  } finally {
222
198
  clearTimeout(timer);
223
199
  }
224
200
  }
225
201
 
226
- async function fetchBillingUsage(token: string): Promise<{ monthly: MonthlyUsage; weekly?: WeeklyUsage }> {
227
- const monthly = parseMonthlyUsage(await fetchJson(`${BILLING_BASE_URL}/billing`, token));
228
- let weekly: WeeklyUsage | undefined;
229
- try {
230
- const weeklyPayload = await fetchJson(`${BILLING_BASE_URL}/billing?format=credits`, token);
231
- weekly = parseWeeklyUsage(weeklyPayload);
232
- if (!weekly && weeklyPayload) {
233
- const config = (weeklyPayload as any)?.config;
234
- weekly = {
235
- creditUsagePercent: 0,
236
- billingPeriodEnd: config?.billingPeriodEnd || new Date().toISOString(),
237
- };
238
- }
239
- } catch {
240
- weekly = undefined;
241
- }
242
- return { monthly, weekly };
202
+ function isUnauthorized(err: unknown): boolean {
203
+ return !!err && typeof err === "object" && (err as { status?: number }).status === 401;
243
204
  }
244
205
 
245
- function mapUsage(monthly: MonthlyUsage, weekly?: WeeklyUsage): UsageReport {
246
- const report: UsageReport = {};
206
+ async function fetchBillingUsage(token: string): Promise<WeeklyUsage> {
207
+ return parseWeeklyUsage(await fetchJson(`${BILLING_BASE_URL}/billing?format=credits`, token));
208
+ }
247
209
 
248
- if (weekly) {
249
- report.weekly = {
210
+ function mapUsage(weekly: WeeklyUsage): UsageReport {
211
+ return {
212
+ weekly: {
250
213
  pct: weekly.creditUsagePercent,
251
214
  resetsIn: resetsInFromIso(weekly.billingPeriodEnd),
252
- };
253
- }
254
-
255
- if (monthly.monthlyLimit > 0) {
256
- report.monthly = {
257
- pct: (monthly.used / monthly.monthlyLimit) * 100,
258
- resetsIn: resetsInFromIso(monthly.billingPeriodEnd),
259
- };
260
- }
261
-
262
- if (!report.weekly && !report.monthly) {
263
- return { error: "could not parse usage" };
264
- }
265
-
266
- return report;
215
+ },
216
+ };
267
217
  }
268
218
 
269
219
  export function makeXaiProvider(name: string, cfg: XaiConfig = {}): UsageProvider {
220
+ // In-memory only — intentionally not written back to auth.json.
270
221
  let cachedCredentials: XaiCredentials | null = null;
222
+ let diskRefreshAtCache: string | undefined;
271
223
 
272
- async function getCredentials(): Promise<XaiCredentials | null> {
224
+ async function getCredentials(forceRefresh = false): Promise<XaiCredentials | null> {
273
225
  const stored = readStoredCredentials();
274
- if (!stored) return null;
275
- if (isFresh(stored)) {
276
- cachedCredentials = stored;
277
- return stored;
226
+ if (!stored) {
227
+ cachedCredentials = null;
228
+ diskRefreshAtCache = undefined;
229
+ return null;
278
230
  }
279
231
 
232
+ // Drop cache if disk was re-logged to a different refresh token.
280
233
  if (
281
234
  cachedCredentials &&
282
- cachedCredentials.refresh === stored.refresh &&
283
- isFresh(cachedCredentials)
235
+ stored.refresh &&
236
+ diskRefreshAtCache &&
237
+ stored.refresh !== diskRefreshAtCache &&
238
+ stored.refresh !== cachedCredentials.refresh
284
239
  ) {
285
- return cachedCredentials;
240
+ cachedCredentials = null;
241
+ diskRefreshAtCache = undefined;
242
+ }
243
+
244
+ if (!forceRefresh) {
245
+ if (isFresh(stored)) {
246
+ cachedCredentials = stored;
247
+ diskRefreshAtCache = stored.refresh;
248
+ return stored;
249
+ }
250
+ // Prefer session cache after a prior refresh (tokens are not persisted).
251
+ if (cachedCredentials && isFresh(cachedCredentials)) {
252
+ return cachedCredentials;
253
+ }
286
254
  }
287
255
 
288
- cachedCredentials = await refreshCredentials(stored);
256
+ const base =
257
+ cachedCredentials?.refresh
258
+ ? {
259
+ access: cachedCredentials.access,
260
+ refresh: cachedCredentials.refresh,
261
+ expires: cachedCredentials.expires,
262
+ tokenEndpoint: cachedCredentials.tokenEndpoint ?? stored.tokenEndpoint,
263
+ }
264
+ : stored;
265
+
266
+ cachedCredentials = await refreshCredentials(base);
267
+ diskRefreshAtCache = stored.refresh;
289
268
  return cachedCredentials;
290
269
  }
291
270
 
@@ -294,14 +273,21 @@ export function makeXaiProvider(name: string, cfg: XaiConfig = {}): UsageProvide
294
273
  matchProviders: cfg.matchProviders ?? [name, "xai-auth", "xai", "grok-cli"],
295
274
  shortLabel: cfg.shortLabel ?? "XAI",
296
275
  label: cfg.label ?? "xAI (SuperGrok)",
276
+ hidden: cfg.hidden,
297
277
  detect: () => readStoredCredentials() !== null,
298
278
 
299
279
  fetchUsage: async (): Promise<UsageReport> => {
300
280
  try {
301
- const credentials = await getCredentials();
281
+ const credentials = await getCredentials(false);
302
282
  if (!credentials) return { error: "not logged in — run /login xai-auth" };
303
- const usage = await fetchBillingUsage(credentials.access);
304
- return mapUsage(usage.monthly, usage.weekly);
283
+ try {
284
+ return mapUsage(await fetchBillingUsage(credentials.access));
285
+ } catch (err) {
286
+ if (!isUnauthorized(err)) throw err;
287
+ const refreshed = await getCredentials(true);
288
+ if (!refreshed) return { error: "session expired — run /login xai-auth" };
289
+ return mapUsage(await fetchBillingUsage(refreshed.access));
290
+ }
305
291
  } catch (err: any) {
306
292
  if (err?.name === "AbortError") return { error: "timeout" };
307
293
  return { error: err?.message ?? String(err) };
package/types.ts CHANGED
@@ -17,6 +17,8 @@ export interface UsageProvider {
17
17
  matchProviders?: string[];
18
18
  shortLabel: string;
19
19
  label: string;
20
+ /** If true, excluded from active providers (quota panel and footer). Login still works. */
21
+ hidden?: boolean;
20
22
  detect(): boolean;
21
23
  fetchUsage(): Promise<UsageReport>;
22
24
  login?(): Promise<boolean>;
@@ -36,6 +38,8 @@ export interface ProviderMeta {
36
38
  matchProviders?: string[];
37
39
  shortLabel?: string;
38
40
  label?: string;
41
+ /** If true, exclude from active providers (quota panel, footer). Login still works. */
42
+ hidden?: boolean;
39
43
  }
40
44
 
41
45
  /** Factory input — no type (caller already picked the factory). */
@@ -1,7 +1,7 @@
1
1
  import type { UsageProvider, UsageReport } from "../types";
2
2
 
3
3
  export function bar(pct: number, width = 24): string {
4
- const filled = Math.round((pct / 100) * width);
4
+ const filled = Math.min(width, Math.max(0, Math.round((pct / 100) * width)));
5
5
  const empty = width - filled;
6
6
  const color = pct < 70 ? "32" : pct < 90 ? "33" : "31";
7
7
  const blocks = "\u2588".repeat(filled) + "\u2591".repeat(empty);
@@ -20,6 +20,7 @@ export function shortReport(report: UsageReport, provider: UsageProvider): strin
20
20
 
21
21
  const resetStr = primary.resetsIn ? ` · ↻ ${primary.resetsIn}` : "";
22
22
  let text = `${primary.pct.toFixed(0)}%${resetStr}`;
23
+ if (primary.pct >= 100) text += " OVER";
23
24
 
24
25
  const secondary: string[] = [];
25
26
  if (report.session != null) {
@@ -64,5 +65,8 @@ export function fullReport(report: UsageReport, provider: UsageProvider, content
64
65
  lines.push(` Monthly: ${bar(report.monthly.pct, barWidth)} ${report.monthly.pct.toFixed(1)}%${r}`);
65
66
  }
66
67
 
68
+ const over = [report.session, report.weekly, report.monthly].some(d => d != null && d.pct >= 100);
69
+ if (over) lines.push(` \x1b[31m\u26A0 over limit\x1b[0m`);
70
+
67
71
  return lines.join("\n");
68
72
  }