@hk_net/pi-usage-bars 0.7.0 → 0.8.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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,35 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## [0.8.0] - 2026-11-17
6
+
7
+ ### Added
8
+
9
+ - Quota bars now show the amounts behind the percentage when the provider reports them, in the footer and in `/usage`: the OpenRouter key limit in its reported currency, and Kimi and MiniMax windows as unlabeled counts.
10
+
11
+ ### Changed
12
+
13
+ - Updated the development and test baseline to Pi SDK 1.5.2 and verified extension loading with Pi 1.5.2.
14
+ - Quota percentages above zero but below 1% now render as `<1%` instead of `0%`.
15
+ - The footer no longer shows a provider's quota when the active model's `baseUrl` points at another host, such as a proxy, LiteLLM, or another gateway, because those requests do not spend that quota. OpenRouter regional hosts (`*.openrouter.ai`) still count as OpenRouter; models without a `baseUrl` keep provider-ID detection.
16
+ - A model routed to OpenRouter or Vercel AI Gateway under another provider ID now shows that gateway's footer usage, fetched with the credential Pi sends for the model rather than the gateway provider's configured key.
17
+
18
+ ### Development
19
+
20
+ - The extension entry point accepts optional `fetchFn`, `env`, and `cacheFile` dependencies; Pi still calls it with the API only. Extension tests inject them instead of replacing `globalThis.fetch`, run with an empty environment, use a private cache file each, and fail on any request they do not stub.
21
+ - Added `npm run verify:tarball`, which packs the package and checks that every module reachable from the Pi extension entry point is in the tarball and imports only declared dependencies. CI, the manual publish workflow, and `scripts/release.sh` run it.
22
+ - Pinned GitHub Actions to commit SHAs and updated the CI, release, and `@types/bun` development baseline to Bun 1.4.3.
23
+
24
+ ## [0.7.1] - 2026-10-20
25
+
26
+ ### Changed
27
+
28
+ - Updated the development and test baseline to Pi SDK 1.3.0; verified the extension loader and Kimi OAuth/xAI Management credential resolution with the Pi 1.3.0 CLI.
29
+
30
+ ### Documentation
31
+
32
+ - Audited Pi 1.3.0 provider additions and documented why TypeSafe, Xiaomi Token Plan, and GitHub Copilot metrics do not currently meet the account-usage support criteria.
33
+
5
34
  ## [0.7.0] - 2026-09-24
6
35
 
7
36
  ### Added
package/README.md CHANGED
@@ -2,7 +2,8 @@
2
2
 
3
3
  Quota, balance, and spend indicators for [Pi](https://github.com/earendil-works/pi).
4
4
 
5
- ![Codex footer bar](https://raw.githubusercontent.com/hknet/pi-usage-bars/main/assets/codex.png)
5
+ <img width="50%" alt="pi-usage-bars screenshot" src="https://github.com/user-attachments/assets/45bff327-bf23-4510-9d9e-290eb04878d3" />
6
+
6
7
 
7
8
  It adds:
8
9
 
@@ -31,15 +32,15 @@ It adds:
31
32
 
32
33
  DeepSeek shows total, topped-up, and granted balances in the currency returned by the API. Moonshot shows available, cash, and voucher balances; this is separate from the Kimi For Coding subscription provider. Pi uses `MOONSHOT_API_KEY` for both Moonshot regions, so `/usage` automatically hides the expected authentication failure from the region where a shared environment key is not valid.
33
34
 
34
- OpenRouter shows the account credit balance and current daily, weekly, and monthly key spend. If the API key has a configured credit limit, that limit is also rendered as a usage bar. Baseten shows current calendar-month credits used, aggregated across its documented dedicated, training, and Model APIs billing categories; it does not invent a remaining-balance or quota percentage. Vercel AI Gateway shows the team's remaining AI Gateway Credits balance and lifetime spend. Fireworks shows account-wide rated spend for the current UTC calendar month. Its high default monthly-spend quota is not treated as a useful budget percentage. xAI shows the team's prepaid balance and current billing-cycle spend.
35
+ OpenRouter shows the account credit balance and current daily, weekly, and monthly key spend. If the API key has a configured credit limit, that limit is also rendered as a usage bar with the amount used and the limit, for example `75% $15/$20`. Baseten shows current calendar-month credits used, aggregated across its documented dedicated, training, and Model APIs billing categories; it does not invent a remaining-balance or quota percentage. Vercel AI Gateway shows the team's remaining AI Gateway Credits balance and lifetime spend. Fireworks shows account-wide rated spend for the current UTC calendar month. Its high default monthly-spend quota is not treated as a useful budget percentage. xAI shows the team's prepaid balance and current billing-cycle spend.
35
36
 
36
37
  MiniMax Subscription Keys can represent an active Token Plan, purchased Credits, or both. The extension shows quota windows when present and a neutral credit-balance line if a first-party key-authenticated response exposes `points_balance`/`credits_balance`. MiniMax currently exposes Credits-only balances through a console endpoint requiring browser-cookie authentication, so a key-only Credits account is shown as “No active Token Plan” with a direction to check the console rather than a fabricated percentage. The extension does not import browser cookies.
37
38
 
38
- Google Gemini CLI and Google Antigravity are not supported because Pi removed those built-in providers in version 0.71.0.
39
+ Google Gemini CLI and Google Antigravity are not supported because Pi removed those built-in providers in version 0.71.0. Pi 1.3.0 also adds the TypeSafe classifier, which is not an active chat model monitored by the footer. The reviewed TypeSafe and Xiaomi MiMo documentation does not describe a key-authenticated account-usage endpoint, so neither is currently supported; see [provider support research](docs/provider-research.md).
39
40
 
40
41
  ## Requirements
41
42
 
42
- - Pi 0.84.2 or newer (tested with the current Pi 0.87.1 release)
43
+ - Pi 0.84.2 or newer (tested with Pi 1.5.2)
43
44
  - Node.js 22.19 or newer when using the npm-distributed Pi CLI
44
45
 
45
46
  Authenticate providers through Pi's `/login` command. The extension resolves credentials through Pi's provider API; it does not read or write `auth.json` itself.
@@ -80,7 +81,13 @@ pi update npm:@hk_net/pi-usage-bars
80
81
 
81
82
  When the active model belongs to a configured supported provider, the footer shows its available quota windows with reset countdowns when provided by the service.
82
83
 
83
- ![Claude footer bar](https://raw.githubusercontent.com/hknet/pi-usage-bars/main/assets/claude.png)
84
+ When a provider reports the amounts behind a quota window, the footer and `/usage` show them next to the percentage: the OpenRouter key limit in the reported currency (`$15/$20`), and Kimi and MiniMax windows as plain counts (`50/200`). Kimi and MiniMax do not document what those counts measure, so they carry no unit. The footer abbreviates amounts from 10,000 upward (`12.5K`); `/usage` shows them in full.
85
+
86
+ The footer only shows a provider's quota when the model actually calls that provider. If `models.json` points a supported provider at another host, such as a local proxy or LiteLLM, the footer stays empty instead of showing a quota that the request does not spend. OpenRouter regional hosts such as `us.openrouter.ai` count as OpenRouter.
87
+
88
+ A model routed to OpenRouter (`openrouter.ai`, `*.openrouter.ai`) or Vercel AI Gateway (`ai-gateway.vercel.sh`) under any other provider ID shows that gateway's usage instead. The footer then queries the gateway with the key Pi sends for that model, not the key configured for the `openrouter` or `vercel-ai-gateway` provider, so it reports the account the model actually spends. `/usage` still lists every configured account with its provider credentials.
89
+
90
+ <img width="50%" alt="pi-usage-bars screenshot" src="https://github.com/user-attachments/assets/45bff327-bf23-4510-9d9e-290eb04878d3" />
84
91
 
85
92
  Usage refresh runs in interactive TUI sessions every two minutes. It does not run in print, JSON, or RPC mode.
86
93
 
@@ -88,17 +95,18 @@ Usage refresh runs in interactive TUI sessions every two minutes. It does not ru
88
95
 
89
96
  Run `/usage` to open a searchable list of configured supported providers. The selected provider's details are expanded; use the configured selection and page-navigation keybindings to browse the bounded list.
90
97
 
91
- ![/usage command](https://raw.githubusercontent.com/hknet/pi-usage-bars/main/assets/usage-command.png)
98
+ <img width="50%" alt="/usage command" src="https://github.com/user-attachments/assets/50058db1-5de5-4bc7-af37-d4b211112dfd" />
99
+
92
100
 
93
101
  ### `--usage`
94
102
 
95
103
  Pass `--usage` to print one JSON line for the active model provider and exit without opening the usage UI. This is also useful as a loader and credential smoke test:
96
104
 
97
105
  ```powershell
98
- pi --no-extensions -e C:\hk\code\pi-usage-bars\extensions\usage-bars\index.ts --usage
106
+ pi --print --no-session --no-extensions -e C:\hk\code\pi-usage-bars\extensions\usage-bars\index.ts --usage
99
107
  ```
100
108
 
101
- The result has `status` set to `ok`, `unconfigured`, `unsupported`, or `error`. No credential is included in the output.
109
+ The result has `status` set to `ok`, `unconfigured`, `unsupported`, or `error`. A supported provider routed through another host reports `unsupported`, unless the host is a supported gateway. No credential is included in the output. In print mode, Pi writes extension logs—including this JSON line—to stderr; use `2>&1` to capture it. In JSON mode, stdout remains Pi's event stream and the usage line is still written to stderr.
102
110
 
103
111
  ## Endpoint configuration
104
112
 
@@ -62,6 +62,34 @@ A live redacted test with a read-only, team-scoped key returned HTTP 200 for key
62
62
 
63
63
  Pi 0.86.1 added the `meta` provider with Meta Muse subscription OAuth and `META_API_KEY` authentication. No documented first-party endpoint was found for remaining subscription quota, reset timing, account balance, or spend. Do not infer quota from local requests or use undocumented console endpoints.
64
64
 
65
+ ## Pi 1.3.0 provider audit (2026-10-20)
66
+
67
+ Comparing the registered `builtinProviders()` lists in [`pi-ai` 0.87.1](https://github.com/earendil-works/pi/blob/v0.87.1/packages/ai/src/providers/all.ts) and [1.3.0](https://github.com/earendil-works/pi/blob/v1.3.0/packages/ai/src/providers/all.ts) found one new provider, `typesafe`, and the Azure provider rename from `azure-openai-responses` to `azure`. The other built-in provider IDs were already present in the 0.87.1 baseline.
68
+
69
+ ### TypeSafe
70
+
71
+ **Status:** No documented key-authenticated account-usage endpoint found in the reviewed documentation.
72
+
73
+ Pi documents `typesafe` as a classifier provider. Classifier models do not appear in `/model`; they are called through the classifier API, so they are not the active chat model this extension monitors. That only prevents active-model footer monitoring; the blocker for account usage reporting is separate. TypeSafe's public `POST /v1/systemone` response reports token usage for that individual request and its docs describe per-organization rate limits and per-token pricing, but no key-authenticated account-level quota, balance, or period-spend endpoint is documented. Summing requests seen by Pi would omit activity from other clients and would not represent account usage.
74
+
75
+ Sources: [Pi classifier models](https://github.com/earendil-works/pi/blob/v1.3.0/packages/coding-agent/docs/models.md#use-classifier-models), [TypeSafe API](https://docs.typesafe.ai/api/system-one), [TypeSafe model pricing and limits](https://docs.typesafe.ai/models).
76
+
77
+ ### Xiaomi MiMo Token Plan
78
+
79
+ **Status:** Blocked — no documented key-authenticated account-usage endpoint found in the reviewed documentation as of 2026-10-20.
80
+
81
+ Xiaomi's official documentation describes fixed monthly/annual Token Plan Credits and says current plan usage is available through the Token Plan progress bar/console. Its published API reference lists inference, rate-limit, and model endpoints, but no API-key-authenticated endpoint for remaining/used plan credits or reset time was found. Do not scrape the console or invent usage from requests observed by Pi. Revisit if Xiaomi publishes an authorized account-usage API.
82
+
83
+ Sources: [Xiaomi Token Plan pricing and quota](https://mimo.mi.com/docs/en-US/price/token-plan), [Xiaomi Token Plan usage FAQ](https://mimo.mi.com/static/docs/quick-start/faq/token-plan/Usage&Quota.md), [Token Plan console](https://platform.xiaomimimo.com/token-plan), [published API reference](https://mimo.mi.com/llms.txt), [Pi provider authentication](https://github.com/earendil-works/pi/blob/v1.3.0/packages/coding-agent/docs/providers.md).
84
+
85
+ ### GitHub Copilot metrics
86
+
87
+ **Status:** Not suitable for per-user usage bars through Pi's normal Copilot credential.
88
+
89
+ GitHub's documented Copilot usage-metrics API returns organization or enterprise reports. The policy must be enabled for the enterprise, and access requires the relevant enterprise/org reporting permissions; the API is not a personal subscription balance or remaining-quota endpoint. Pi resolves a user's Copilot sign-in/token, which does not establish those administrator permissions or an organization context. Supporting enterprise reports would need a separate, explicitly configured admin credential and scope, and would still not provide a user's current personal quota.
90
+
91
+ Source: [GitHub Copilot usage metrics API](https://docs.github.com/en/rest/copilot/copilot-usage-metrics).
92
+
65
93
  ## Acceptance criteria for a new provider
66
94
 
67
95
  A provider is suitable when a documented first-party API or response header supplies at least one meaningful account-level value:
package/docs/releasing.md CHANGED
@@ -38,7 +38,7 @@ Preparation:
38
38
  2. rejects an existing npm version or Git tag;
39
39
  3. updates `package.json` and `package-lock.json` without creating an early tag;
40
40
  4. promotes the `Unreleased` changelog entries into a dated release while preserving an empty `Unreleased` heading;
41
- 5. installs dependencies with `npm ci --no-audit`, provisions a temporary pinned Bun binary, and runs typecheck, tests, detailed dependency audits, and package dry-run; and
41
+ 5. installs dependencies with `npm ci --no-audit`, provisions a temporary pinned Bun binary, and runs typecheck, tests, detailed dependency audits, tarball verification, and package dry-run; and
42
42
  6. commits and pushes the release source.
43
43
 
44
44
  After reviewing the prepared commit, stage it for browser approval:
@@ -49,9 +49,19 @@ export interface AccountSpend {
49
49
  lifetime?: number;
50
50
  }
51
51
 
52
+ // Used and allowed amounts behind a quota bar. A three-letter unit is an ISO
53
+ // currency code; no unit means a count the provider does not label.
54
+ export interface AccountQuota {
55
+ used: number;
56
+ limit: number;
57
+ unit?: string;
58
+ }
59
+
52
60
  export interface UsageData {
53
61
  session: number;
54
62
  weekly: number;
63
+ sessionQuota?: AccountQuota;
64
+ weeklyQuota?: AccountQuota;
55
65
  quotaHidden?: boolean;
56
66
  accountBalance?: AccountBalance;
57
67
  accountBalanceDetails?: AccountBalance[];
@@ -491,6 +501,8 @@ function snapshotUsage(usage: UsageData, nowMs = Date.now()): UsageData {
491
501
  return {
492
502
  session: usage.session,
493
503
  weekly: usage.weekly,
504
+ sessionQuota: usage.sessionQuota,
505
+ weeklyQuota: usage.weeklyQuota,
494
506
  quotaHidden: usage.quotaHidden,
495
507
  accountBalance: usage.accountBalance,
496
508
  accountBalanceDetails: usage.accountBalanceDetails,
@@ -714,6 +726,19 @@ function usedPercentFromCounts(
714
726
  return null;
715
727
  }
716
728
 
729
+ function quotaFromCounts(
730
+ value: Record<string, unknown> | null | undefined,
731
+ options: { used?: string; total?: string; remaining?: string } = {},
732
+ ): AccountQuota | undefined {
733
+ if (!value) return undefined;
734
+ const total = readNumber(value[options.total ?? "limit"]);
735
+ if (total === null || total <= 0) return undefined;
736
+ const used = readNumber(value[options.used ?? "used"]);
737
+ const remaining = readNumber(value[options.remaining ?? "remaining"]);
738
+ const amount = used ?? (remaining === null ? null : total - remaining);
739
+ return amount === null ? undefined : { used: Math.max(0, amount), limit: total };
740
+ }
741
+
717
742
  function normalizeIsoDate(value: unknown): string | undefined {
718
743
  if (typeof value !== "string" || !value.trim()) return undefined;
719
744
  const normalized = value.trim().replace(/(\.\d{3})\d+(?=Z|[+-]\d\d:\d\d$)/, "$1");
@@ -763,6 +788,8 @@ export function extractKimiUsageFromPayload(payload: unknown, nowMs = Date.now()
763
788
  const weeklyReset = normalizeIsoDate(usage?.resetTime ?? usage?.reset_at ?? usage?.reset_time);
764
789
  return hydrateUsageResets({
765
790
  ...normalizeUsagePair(session, weekly),
791
+ sessionQuota: quotaFromCounts(sessionDetail),
792
+ weeklyQuota: quotaFromCounts(usage),
766
793
  sessionLabel: "5-hour",
767
794
  weeklyLabel: "Weekly",
768
795
  sessionResetsAt: sessionReset,
@@ -789,6 +816,7 @@ export async function fetchKimiUsage(token: string, config: FetchConfig = {}): P
789
816
  interface MiniMaxWindow {
790
817
  percent: number;
791
818
  resetsAt?: string;
819
+ quota?: AccountQuota;
792
820
  }
793
821
 
794
822
  function pickHighestWindow(windows: MiniMaxWindow[]): MiniMaxWindow | undefined {
@@ -839,7 +867,8 @@ export function extractMiniMaxUsageFromPayload(payload: unknown, nowMs = Date.no
839
867
  if (percent === null) continue;
840
868
  const windowType = String(service.window_type ?? service.windowType ?? "").toLowerCase();
841
869
  const resetsAt = normalizeIsoDate(service.resets_at ?? service.reset_time ?? service.end_time);
842
- (windowType.includes("week") ? weeklyWindows : intervalWindows).push({ percent, resetsAt });
870
+ const quota = quotaFromCounts(service, { total: "limit", used: "usage" });
871
+ (windowType.includes("week") ? weeklyWindows : intervalWindows).push({ percent, resetsAt, quota });
843
872
  }
844
873
  }
845
874
 
@@ -871,7 +900,11 @@ export function extractMiniMaxUsageFromPayload(payload: unknown, nowMs = Date.no
871
900
  remaining: "current_interval_usage_count",
872
901
  });
873
902
  if (interval !== null) {
874
- intervalWindows.push({ percent: interval, resetsAt: miniMaxResetAt(model, "current", nowMs) });
903
+ intervalWindows.push({
904
+ percent: interval,
905
+ resetsAt: miniMaxResetAt(model, "current", nowMs),
906
+ quota: quotaFromCounts(model, { total: "current_interval_total_count", remaining: "current_interval_usage_count" }),
907
+ });
875
908
  }
876
909
  const weekly = unavailable("weekly") ? null : usedPercentFromCounts(model, {
877
910
  remainingPercent: "current_weekly_remaining_percent",
@@ -879,7 +912,11 @@ export function extractMiniMaxUsageFromPayload(payload: unknown, nowMs = Date.no
879
912
  remaining: "current_weekly_usage_count",
880
913
  });
881
914
  if (weekly !== null) {
882
- weeklyWindows.push({ percent: weekly, resetsAt: miniMaxResetAt(model, "weekly", nowMs) });
915
+ weeklyWindows.push({
916
+ percent: weekly,
917
+ resetsAt: miniMaxResetAt(model, "weekly", nowMs),
918
+ quota: quotaFromCounts(model, { total: "current_weekly_total_count", remaining: "current_weekly_usage_count" }),
919
+ });
883
920
  }
884
921
  }
885
922
  }
@@ -895,6 +932,8 @@ export function extractMiniMaxUsageFromPayload(payload: unknown, nowMs = Date.no
895
932
  session: Number(session.percent.toFixed(2)),
896
933
  accountBalance,
897
934
  weekly: Number((weekly?.percent ?? 0).toFixed(2)),
935
+ sessionQuota: session.quota,
936
+ weeklyQuota: weekly?.quota,
898
937
  sessionLabel: "Interval",
899
938
  weeklyLabel: "Weekly",
900
939
  weeklyHidden: !weekly,
@@ -1020,6 +1059,7 @@ export function extractOpenRouterUsageFromPayloads(
1020
1059
  weekly: 0,
1021
1060
  quotaHidden: limitPercent === null,
1022
1061
  weeklyHidden: true,
1062
+ sessionQuota: limitUsed !== null && limit !== null ? { used: limitUsed, limit, unit: "USD" } : undefined,
1023
1063
  sessionLabel: "Key limit",
1024
1064
  accountBalance,
1025
1065
  accountSpend,
@@ -1498,11 +1538,88 @@ export async function fetchZaiUsage(
1498
1538
  return extractUsageFromPayload(result.data) ?? { session: 0, weekly: 0, error: "unrecognized response shape" };
1499
1539
  }
1500
1540
 
1541
+ // Inference hosts Pi 1.3 uses for each supported provider. A model whose
1542
+ // baseUrl points elsewhere (a proxy, LiteLLM, or another gateway) does not spend
1543
+ // that provider's quota, so the footer shows no bar instead of a wrong one,
1544
+ // unless the host is a supported gateway.
1545
+ const PROVIDER_HOSTS: Record<ProviderKey, readonly string[]> = {
1546
+ codex: ["chatgpt.com"],
1547
+ claude: ["api.anthropic.com"],
1548
+ zai: ["api.z.ai"],
1549
+ "zai-cn": ["open.bigmodel.cn"],
1550
+ kimi: ["api.kimi.com"],
1551
+ minimax: ["api.minimax.io"],
1552
+ "minimax-cn": ["api.minimaxi.com"],
1553
+ openrouter: ["openrouter.ai"],
1554
+ deepseek: ["api.deepseek.com"],
1555
+ moonshot: ["api.moonshot.ai"],
1556
+ "moonshot-cn": ["api.moonshot.cn"],
1557
+ baseten: ["inference.baseten.co"],
1558
+ vercel: ["ai-gateway.vercel.sh"],
1559
+ fireworks: ["api.fireworks.ai"],
1560
+ xai: ["api.x.ai"],
1561
+ };
1562
+
1563
+ // Providers that also serve documented regional subdomains, such as
1564
+ // us.openrouter.ai.
1565
+ const PROVIDER_HOST_SUFFIXES: Partial<Record<ProviderKey, string>> = {
1566
+ openrouter: ".openrouter.ai",
1567
+ };
1568
+
1569
+ // Gateways whose usage belongs to the key a model sends them, whatever Pi
1570
+ // provider ID the model is registered under.
1571
+ const GATEWAY_PROVIDERS: readonly ProviderKey[] = ["openrouter", "vercel"];
1572
+
1573
+ // Where usage for the active model comes from. "provider" uses the credential
1574
+ // configured for the provider's own Pi provider ID; "model" uses the credential
1575
+ // Pi sends with the model itself, because the model reaches a gateway under
1576
+ // another provider ID.
1577
+ export type UsageCredentialSource = "provider" | "model";
1578
+
1579
+ export interface ProviderRoute {
1580
+ provider: ProviderKey;
1581
+ credential: UsageCredentialSource;
1582
+ }
1583
+
1584
+ function routeHost(baseUrl: string | undefined): string | undefined {
1585
+ if (typeof baseUrl !== "string" || !baseUrl.trim()) return undefined;
1586
+ try {
1587
+ return new URL(baseUrl.trim()).hostname.replace(/\.$/, "");
1588
+ } catch {
1589
+ return undefined;
1590
+ }
1591
+ }
1592
+
1593
+ function isProviderHost(provider: ProviderKey, host: string): boolean {
1594
+ if (PROVIDER_HOSTS[provider].includes(host)) return true;
1595
+ const suffix = PROVIDER_HOST_SUFFIXES[provider];
1596
+ return suffix !== undefined && host.endsWith(suffix);
1597
+ }
1598
+
1599
+ export function isProviderRoute(provider: ProviderKey, baseUrl: string | undefined): boolean {
1600
+ const host = routeHost(baseUrl);
1601
+ return host === undefined || isProviderHost(provider, host);
1602
+ }
1603
+
1604
+ export function detectProviderRoute(
1605
+ model: { provider?: string; baseUrl?: string } | string | undefined | null,
1606
+ ): ProviderRoute | null {
1607
+ if (!model || typeof model === "string") return null;
1608
+ const provider = providerFromId(model.provider);
1609
+ if (provider && isProviderRoute(provider, model.baseUrl)) return { provider, credential: "provider" };
1610
+ const host = routeHost(model.baseUrl);
1611
+ const gateway = host === undefined ? undefined : GATEWAY_PROVIDERS.find((candidate) => isProviderHost(candidate, host));
1612
+ return gateway ? { provider: gateway, credential: "model" } : null;
1613
+ }
1614
+
1501
1615
  export function detectProvider(
1502
- model: { provider?: string } | string | undefined | null,
1616
+ model: { provider?: string; baseUrl?: string } | string | undefined | null,
1503
1617
  ): ProviderKey | null {
1504
- if (!model || typeof model === "string") return null;
1505
- switch ((model.provider || "").toLowerCase()) {
1618
+ return detectProviderRoute(model)?.provider ?? null;
1619
+ }
1620
+
1621
+ function providerFromId(providerId: string | undefined): ProviderKey | null {
1622
+ switch ((providerId || "").toLowerCase()) {
1506
1623
  case "openai-codex": return "codex";
1507
1624
  case "anthropic": return "claude";
1508
1625
  case "zai": return "zai";
@@ -1547,6 +1664,48 @@ export function clampPercent(value: number): number {
1547
1664
  return Math.max(0, Math.min(100, Math.round(value)));
1548
1665
  }
1549
1666
 
1667
+ export function formatPercent(value: number): string {
1668
+ if (Number.isFinite(value) && value > 0 && value < 0.5) return "<1%";
1669
+ return `${clampPercent(value)}%`;
1670
+ }
1671
+
1672
+ export function formatFinancialAmount(amount: number, unit: string): string {
1673
+ if (/^[A-Z]{3}$/.test(unit)) {
1674
+ return new Intl.NumberFormat("en-US", {
1675
+ style: "currency",
1676
+ currency: unit,
1677
+ minimumFractionDigits: 2,
1678
+ maximumFractionDigits: 5,
1679
+ }).format(amount);
1680
+ }
1681
+ const formatted = new Intl.NumberFormat("en-US", { maximumFractionDigits: 2 }).format(amount);
1682
+ return `${formatted} ${unit}`;
1683
+ }
1684
+
1685
+ function formatQuotaAmount(amount: number, unit: string | undefined, compact: boolean): string {
1686
+ const currency = unit !== undefined && /^[A-Z]{3}$/.test(unit) ? unit : undefined;
1687
+ if (!compact) {
1688
+ if (currency) return formatFinancialAmount(amount, currency);
1689
+ const formatted = new Intl.NumberFormat("en-US", { maximumFractionDigits: 2 }).format(amount);
1690
+ return unit ? `${formatted} ${unit}` : formatted;
1691
+ }
1692
+ const options: Intl.NumberFormatOptions = Math.abs(amount) >= 10_000
1693
+ ? { notation: "compact", maximumFractionDigits: 1 }
1694
+ : { maximumFractionDigits: 2 };
1695
+ if (currency) {
1696
+ return new Intl.NumberFormat("en-US", { ...options, style: "currency", currency, minimumFractionDigits: 0 })
1697
+ .format(amount);
1698
+ }
1699
+ const formatted = new Intl.NumberFormat("en-US", options).format(amount);
1700
+ return unit ? `${formatted} ${unit}` : formatted;
1701
+ }
1702
+
1703
+ export function formatQuota(quota: AccountQuota, compact = false): string {
1704
+ const separator = compact ? "/" : " / ";
1705
+ return formatQuotaAmount(quota.used, quota.unit, compact) + separator +
1706
+ formatQuotaAmount(quota.limit, quota.unit, compact);
1707
+ }
1708
+
1550
1709
  export function colorForPercent(value: number): "success" | "warning" | "error" {
1551
1710
  if (value >= 90) return "error";
1552
1711
  if (value >= 70) return "warning";
@@ -19,7 +19,7 @@ import {
19
19
  import {
20
20
  clampPercent,
21
21
  colorForPercent,
22
- detectProvider,
22
+ detectProviderRoute,
23
23
  fetchAllUsages,
24
24
  fetchBasetenUsage,
25
25
  fetchClaudeUsageWithFallback,
@@ -33,12 +33,17 @@ import {
33
33
  fetchVercelCredits,
34
34
  fetchXaiUsage,
35
35
  fetchZaiUsage,
36
+ formatFinancialAmount,
37
+ formatPercent,
38
+ formatQuota,
36
39
  providerToPiProviderId,
37
40
  resolveUsageEndpoints,
38
41
  type AccountBalance,
39
42
  type AccountSpend,
43
+ type FetchLike,
40
44
  type ProviderKey,
41
45
  type UsageByProvider,
46
+ type UsageCredentialSource,
42
47
  type UsageData,
43
48
  type UsageTokens,
44
49
  XAI_MANAGEMENT_PROVIDER_ID,
@@ -87,19 +92,6 @@ const PROVIDER_LABELS: Record<ProviderKey, string> = {
87
92
  xai: "xAI",
88
93
  };
89
94
 
90
- function formatFinancialAmount(amount: number, unit: string): string {
91
- if (/^[A-Z]{3}$/.test(unit)) {
92
- return new Intl.NumberFormat("en-US", {
93
- style: "currency",
94
- currency: unit,
95
- minimumFractionDigits: 2,
96
- maximumFractionDigits: 5,
97
- }).format(amount);
98
- }
99
- const formatted = new Intl.NumberFormat("en-US", { maximumFractionDigits: 2 }).format(amount);
100
- return `${formatted} ${unit}`;
101
- }
102
-
103
95
  function formatAccountBalance(balance: AccountBalance): string {
104
96
  return `${balance.label} · ${formatFinancialAmount(balance.amount, balance.unit)}`;
105
97
  }
@@ -309,7 +301,9 @@ class UsageSelectorComponent extends Container implements Focusable {
309
301
  if (!item.data.sessionHidden) {
310
302
  this.listContainer.addChild(new Text(
311
303
  indent + theme.fg("muted", sessionLabel) + this.renderBar(session) + " " +
312
- theme.fg(colorForPercent(session), `${session}%`.padStart(4)) + sessionReset,
304
+ theme.fg(colorForPercent(session), formatPercent(item.data.session).padStart(4)) +
305
+ (item.data.sessionQuota ? theme.fg("muted", ` ${formatQuota(item.data.sessionQuota)}`) : "") +
306
+ sessionReset,
313
307
  0,
314
308
  0,
315
309
  ));
@@ -317,7 +311,9 @@ class UsageSelectorComponent extends Container implements Focusable {
317
311
  if (!item.data.weeklyHidden) {
318
312
  this.listContainer.addChild(new Text(
319
313
  indent + theme.fg("muted", weeklyLabel) + this.renderBar(weekly) + " " +
320
- theme.fg(colorForPercent(weekly), `${weekly}%`.padStart(4)) + weeklyReset,
314
+ theme.fg(colorForPercent(weekly), formatPercent(item.data.weekly).padStart(4)) +
315
+ (item.data.weeklyQuota ? theme.fg("muted", ` ${formatQuota(item.data.weeklyQuota)}`) : "") +
316
+ weeklyReset,
321
317
  0,
322
318
  0,
323
319
  ));
@@ -459,10 +455,23 @@ class UsageSelectorComponent extends Container implements Focusable {
459
455
 
460
456
  interface UsageState extends UsageByProvider {
461
457
  activeProvider: ProviderKey | null;
458
+ activeCredential: UsageCredentialSource;
459
+ activeModel: ExtensionContext["model"];
462
460
  available: Partial<Record<ProviderKey, boolean>>;
461
+ // The credential that produced each provider's footer data, so data fetched
462
+ // with one key is never shown for a route that uses another.
463
+ dataCredential: Partial<Record<ProviderKey, string>>;
464
+ }
465
+
466
+ // Optional seams for tests and embedders. Pi calls the extension with the API
467
+ // only, so every dependency falls back to the real implementation.
468
+ export interface UsageBarsDependencies {
469
+ fetchFn?: FetchLike;
470
+ env?: NodeJS.ProcessEnv;
471
+ cacheFile?: string;
463
472
  }
464
473
 
465
- export default function (pi: ExtensionAPI): void {
474
+ export default function (pi: ExtensionAPI, dependencies: UsageBarsDependencies = {}): void {
466
475
  // xAI exposes billing only through a separate Management Key. Register a
467
476
  // model-less provider so Pi owns secret prompting, storage, and resolution;
468
477
  // the key can never be selected for or sent to inference.
@@ -485,7 +494,8 @@ export default function (pi: ExtensionAPI): void {
485
494
  default: false,
486
495
  });
487
496
 
488
- const endpoints = resolveUsageEndpoints();
497
+ const endpoints = resolveUsageEndpoints(dependencies.env);
498
+ const requestConfig = { endpoints, fetchFn: dependencies.fetchFn, cacheFile: dependencies.cacheFile };
489
499
  const state: UsageState = {
490
500
  codex: null,
491
501
  claude: null,
@@ -503,7 +513,10 @@ export default function (pi: ExtensionAPI): void {
503
513
  fireworks: null,
504
514
  xai: null,
505
515
  activeProvider: null,
516
+ activeCredential: "provider",
517
+ activeModel: undefined,
506
518
  available: {},
519
+ dataCredential: {},
507
520
  };
508
521
 
509
522
  let pollTimer: ReturnType<typeof setInterval> | undefined;
@@ -514,8 +527,7 @@ export default function (pi: ExtensionAPI): void {
514
527
  let providerPollController: AbortController | undefined;
515
528
 
516
529
  const renderPercent = (theme: Theme, value: number) => {
517
- const percent = clampPercent(value);
518
- return theme.fg(colorForPercent(percent), `${percent}%`);
530
+ return theme.fg(colorForPercent(clampPercent(value)), formatPercent(value));
519
531
  };
520
532
 
521
533
  const renderBar = (theme: Theme, value: number) => {
@@ -530,12 +542,14 @@ export default function (pi: ExtensionAPI): void {
530
542
  const ctx = currentContext;
531
543
  if (!ctx || ctx.mode !== "tui") return;
532
544
  const provider = state.activeProvider;
533
- if (!provider || state.available[provider] === false) {
545
+ const current = provider !== null &&
546
+ state.dataCredential[provider] === credentialKey(state.activeCredential, state.activeModel);
547
+ if (!provider || (current && state.available[provider] === false)) {
534
548
  ctx.ui.setStatus(STATUS_KEY, undefined);
535
549
  return;
536
550
  }
537
551
 
538
- const data = state[provider];
552
+ const data = current ? state[provider] : null;
539
553
  const theme = ctx.ui.theme;
540
554
  const label = PROVIDER_LABELS[provider];
541
555
  if (!data) {
@@ -574,13 +588,15 @@ export default function (pi: ExtensionAPI): void {
574
588
  const quotaLanes: string[] = [];
575
589
  if (!data.sessionHidden) {
576
590
  quotaLanes.push(
577
- theme.fg("muted", sessionPrefix) + renderBar(theme, session) + " " + renderPercent(theme, session) +
591
+ theme.fg("muted", sessionPrefix) + renderBar(theme, session) + " " + renderPercent(theme, data.session) +
592
+ (data.sessionQuota ? theme.fg("muted", ` ${formatQuota(data.sessionQuota, true)}`) : "") +
578
593
  (data.sessionResetsIn ? theme.fg("dim", ` ⟳ ${data.sessionResetsIn}`) : ""),
579
594
  );
580
595
  }
581
596
  if (!data.weeklyHidden) {
582
597
  quotaLanes.push(
583
- theme.fg("muted", "W ") + renderBar(theme, weekly) + " " + renderPercent(theme, weekly) +
598
+ theme.fg("muted", "W ") + renderBar(theme, weekly) + " " + renderPercent(theme, data.weekly) +
599
+ (data.weeklyQuota ? theme.fg("muted", ` ${formatQuota(data.weeklyQuota, true)}`) : "") +
584
600
  (data.weeklyResetsIn ? theme.fg("dim", ` ⟳ ${data.weeklyResetsIn}`) : ""),
585
601
  );
586
602
  }
@@ -596,10 +612,18 @@ export default function (pi: ExtensionAPI): void {
596
612
  ctx.ui.setStatus(STATUS_KEY, status);
597
613
  }
598
614
 
615
+ function credentialKey(credential: UsageCredentialSource, model: ExtensionContext["model"]): string {
616
+ return credential === "model" ? `model:${model?.provider ?? ""}/${model?.id ?? ""}` : "provider";
617
+ }
618
+
599
619
  function updateProviderFrom(model: ExtensionContext["model"]): boolean {
600
- const previous = state.activeProvider;
601
- state.activeProvider = detectProvider(model);
602
- if (previous !== state.activeProvider) {
620
+ const previousProvider = state.activeProvider;
621
+ const previousKey = credentialKey(state.activeCredential, state.activeModel);
622
+ const route = detectProviderRoute(model);
623
+ state.activeProvider = route?.provider ?? null;
624
+ state.activeCredential = route?.credential ?? "provider";
625
+ state.activeModel = model;
626
+ if (previousProvider !== state.activeProvider || previousKey !== credentialKey(state.activeCredential, model)) {
603
627
  providerPollController?.abort();
604
628
  updateStatus();
605
629
  return true;
@@ -608,8 +632,8 @@ export default function (pi: ExtensionAPI): void {
608
632
  }
609
633
 
610
634
  function isClaudeSubscriptionAuth(source: string | undefined): boolean {
611
- // Pi 0.84 exposes AuthResult.source as a human-readable label rather than a
612
- // credential-type discriminator. Keep the compatibility assumption in one
635
+ // Pi exposes AuthResult.source as a human-readable label rather than a
636
+ // credential-type discriminator. Keep this source-label assumption in one
613
637
  // place until ModelRegistry exposes the resolved credential type directly.
614
638
  return source === "OAuth";
615
639
  }
@@ -637,50 +661,70 @@ export default function (pi: ExtensionAPI): void {
637
661
  }
638
662
  }
639
663
 
664
+ async function resolveModelCredential(
665
+ ctx: ExtensionContext,
666
+ model: ExtensionContext["model"],
667
+ ): Promise<CredentialResolution> {
668
+ if (!model) return {};
669
+ try {
670
+ const resolved = await ctx.modelRegistry.getApiKeyAndHeaders(model);
671
+ if (!resolved.ok) return { error: resolved.error };
672
+ if (resolved.apiKey) return { token: resolved.apiKey };
673
+ const authorization = resolved.headers?.Authorization ?? resolved.headers?.authorization;
674
+ if (typeof authorization === "string" && authorization.startsWith("Bearer ")) {
675
+ return { token: authorization.slice("Bearer ".length) };
676
+ }
677
+ return {};
678
+ } catch (error) {
679
+ return { error: error instanceof Error ? error.message : String(error) };
680
+ }
681
+ }
682
+
683
+ function fetchUsageWithToken(provider: ProviderKey, token: string, signal: AbortSignal): Promise<UsageData> {
684
+ const config = { ...requestConfig, signal };
685
+ switch (provider) {
686
+ case "codex": return fetchCodexUsage(token, config);
687
+ case "claude": return fetchClaudeUsageWithFallback(token, config);
688
+ case "zai": return fetchZaiUsage(token, "zai", config);
689
+ case "zai-cn": return fetchZaiUsage(token, "zai-cn", config);
690
+ case "kimi": return fetchKimiUsage(token, config);
691
+ case "minimax": return fetchMiniMaxUsage(token, "minimax", config);
692
+ case "minimax-cn": return fetchMiniMaxUsage(token, "minimax-cn", config);
693
+ case "openrouter": return fetchOpenRouterUsage(token, config);
694
+ case "deepseek": return fetchDeepSeekBalance(token, config);
695
+ case "moonshot": return fetchMoonshotBalance(token, "moonshot", config);
696
+ case "moonshot-cn": return fetchMoonshotBalance(token, "moonshot-cn", config);
697
+ case "baseten": return fetchBasetenUsage(token, config);
698
+ case "vercel": return fetchVercelCredits(token, config);
699
+ case "fireworks": return fetchFireworksUsage(token, config);
700
+ case "xai": return fetchXaiUsage(token, config);
701
+ }
702
+ }
703
+
640
704
  async function fetchProvider(
641
705
  ctx: ExtensionContext,
642
706
  provider: ProviderKey,
643
707
  signal: AbortSignal,
708
+ credentialSource: UsageCredentialSource = "provider",
644
709
  ): Promise<void> {
645
- const credential = await resolveCredential(ctx, provider);
710
+ const model = state.activeModel;
711
+ const credential = credentialSource === "model"
712
+ ? await resolveModelCredential(ctx, model)
713
+ : await resolveCredential(ctx, provider);
646
714
  if (signal.aborted) return;
647
- state.available[provider] = Boolean(credential.token || credential.error);
648
- if (credential.error) {
649
- state[provider] = { session: 0, weekly: 0, error: `auth resolution failed (${credential.error})` };
650
- return;
651
- }
652
- if (!credential.token) {
653
- state[provider] = null;
654
- return;
655
- }
656
715
 
657
- if (provider === "codex") state.codex = await fetchCodexUsage(credential.token, { signal });
658
- if (provider === "claude") state.claude = await fetchClaudeUsageWithFallback(credential.token, { signal });
659
- if (provider === "zai") state.zai = await fetchZaiUsage(credential.token, "zai", { endpoints, signal });
660
- if (provider === "zai-cn") state["zai-cn"] = await fetchZaiUsage(credential.token, "zai-cn", { endpoints, signal });
661
- if (provider === "kimi") state.kimi = await fetchKimiUsage(credential.token, { endpoints, signal });
662
- if (provider === "minimax") {
663
- state.minimax = await fetchMiniMaxUsage(credential.token, "minimax", { endpoints, signal });
664
- }
665
- if (provider === "minimax-cn") {
666
- state["minimax-cn"] = await fetchMiniMaxUsage(credential.token, "minimax-cn", { endpoints, signal });
667
- }
668
- if (provider === "openrouter") {
669
- state.openrouter = await fetchOpenRouterUsage(credential.token, { endpoints, signal });
670
- }
671
- if (provider === "deepseek") {
672
- state.deepseek = await fetchDeepSeekBalance(credential.token, { endpoints, signal });
673
- }
674
- if (provider === "moonshot") {
675
- state.moonshot = await fetchMoonshotBalance(credential.token, "moonshot", { endpoints, signal });
676
- }
677
- if (provider === "moonshot-cn") {
678
- state["moonshot-cn"] = await fetchMoonshotBalance(credential.token, "moonshot-cn", { endpoints, signal });
716
+ let data: UsageData | null = null;
717
+ if (credential.error) {
718
+ data = { session: 0, weekly: 0, error: `auth resolution failed (${credential.error})` };
719
+ } else if (credential.token) {
720
+ data = await fetchUsageWithToken(provider, credential.token, signal);
721
+ if (signal.aborted) return;
679
722
  }
680
- if (provider === "baseten") state.baseten = await fetchBasetenUsage(credential.token, { endpoints, signal });
681
- if (provider === "vercel") state.vercel = await fetchVercelCredits(credential.token, { endpoints, signal });
682
- if (provider === "fireworks") state.fireworks = await fetchFireworksUsage(credential.token, { endpoints, signal });
683
- if (provider === "xai") state.xai = await fetchXaiUsage(credential.token, { endpoints, signal });
723
+ // Commit the data together with the credential that produced it, so a
724
+ // fetch for a previous route can never be shown for the current one.
725
+ state[provider] = data;
726
+ state.available[provider] = Boolean(credential.token || credential.error);
727
+ state.dataCredential[provider] = credentialKey(credentialSource, model);
684
728
  }
685
729
 
686
730
  async function runPoll(): Promise<void> {
@@ -696,7 +740,7 @@ export default function (pi: ExtensionAPI): void {
696
740
  providerPollController = controller;
697
741
  const signal = AbortSignal.any([sessionSignal, controller.signal]);
698
742
  try {
699
- await fetchProvider(ctx, provider, signal);
743
+ await fetchProvider(ctx, provider, signal, state.activeCredential);
700
744
  if (signal.aborted) return;
701
745
  const data = state[provider];
702
746
  if (data && !data.error) pi.events.emit(USAGE_UPDATE_EVENT, { provider, ...data });
@@ -732,7 +776,7 @@ export default function (pi: ExtensionAPI): void {
732
776
  if (resolution.error) authErrors[provider] = resolution.error;
733
777
  }
734
778
 
735
- const results = await fetchAllUsages(tokens, { endpoints, signal });
779
+ const results = await fetchAllUsages(tokens, { ...requestConfig, signal });
736
780
  for (const provider of PROVIDERS) {
737
781
  const error = authErrors[provider];
738
782
  if (error) results[provider] = { session: 0, weekly: 0, error: `auth resolution failed (${error})` };
@@ -754,7 +798,7 @@ export default function (pi: ExtensionAPI): void {
754
798
  if (!provider) {
755
799
  console.log(JSON.stringify({ extension: EXTENSION_ID, status: "unsupported", provider: ctx.model?.provider }));
756
800
  } else {
757
- await fetchProvider(ctx, provider, sessionController.signal);
801
+ await fetchProvider(ctx, provider, sessionController.signal, state.activeCredential);
758
802
  const data = state[provider];
759
803
  console.log(JSON.stringify({
760
804
  extension: EXTENSION_ID,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hk_net/pi-usage-bars",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Quota, balance, and spend indicators for current Pi providers",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -45,6 +45,7 @@
45
45
  "test": "bun test tests",
46
46
  "typecheck": "tsc --noEmit",
47
47
  "check": "npm run typecheck && npm test",
48
+ "verify:tarball": "node scripts/verify-tarball.mjs",
48
49
  "prepublishOnly": "npm run check"
49
50
  },
50
51
  "engines": {
@@ -67,10 +68,10 @@
67
68
  }
68
69
  },
69
70
  "devDependencies": {
70
- "@earendil-works/pi-ai": "0.87.1",
71
- "@earendil-works/pi-coding-agent": "0.87.1",
72
- "@earendil-works/pi-tui": "0.87.1",
73
- "@types/bun": "1.3.14",
71
+ "@earendil-works/pi-ai": "1.5.2",
72
+ "@earendil-works/pi-coding-agent": "1.5.2",
73
+ "@earendil-works/pi-tui": "1.5.2",
74
+ "@types/bun": "1.4.3",
74
75
  "@types/node": "24.13.3",
75
76
  "typescript": "5.9.3"
76
77
  },