@hk_net/pi-usage-bars 0.6.0 → 0.7.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,22 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## [0.7.0] - 2026-09-24
6
+
7
+ ### Added
8
+
9
+ - Added Vercel AI Gateway balance and lifetime-spend reporting through its documented key-authenticated Credits API.
10
+ - Added Fireworks AI current-month account spend reporting through its documented key-authenticated billing API, with explicit account selection when a key can access multiple accounts.
11
+ - Added xAI prepaid-balance and current-cycle-spend reporting through its documented Management API, with a model-less Pi `/login` provider for securely storing the separate read-only Management Key.
12
+
13
+ ### Changed
14
+
15
+ - Updated the development and test baseline to Pi SDK 0.87.1.
16
+
17
+ ### Fixed
18
+
19
+ - Retry transient Fireworks `429`, `502`, `503`, and `504` responses once, respecting `Retry-After` and request cancellation.
20
+
5
21
  ## [0.6.0] - 2026-08-29
6
22
 
7
23
  ### Added
package/README.md CHANGED
@@ -25,10 +25,13 @@ It adds:
25
25
  | Moonshot/Kimi API (Global) | `moonshotai` | Moonshot Global API key |
26
26
  | Moonshot/Kimi API (China) | `moonshotai-cn` | Moonshot China API key |
27
27
  | Baseten | `baseten` | Baseten API key |
28
+ | Vercel AI Gateway | `vercel-ai-gateway` | AI Gateway API key |
29
+ | Fireworks AI | `fireworks` | Fireworks API key |
30
+ | xAI | `xai` | Separate read-only xAI Management Key |
28
31
 
29
32
  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.
30
33
 
31
- 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.
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.
32
35
 
33
36
  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.
34
37
 
@@ -36,11 +39,19 @@ Google Gemini CLI and Google Antigravity are not supported because Pi removed th
36
39
 
37
40
  ## Requirements
38
41
 
39
- - Pi 0.84.2 or newer (tested with the current Pi 0.84.4 release)
42
+ - Pi 0.84.2 or newer (tested with the current Pi 0.87.1 release)
40
43
  - Node.js 22.19 or newer when using the npm-distributed Pi CLI
41
44
 
42
45
  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.
43
46
 
47
+ xAI keeps inference and billing credentials separate. After authenticating Pi's normal `xai` provider, configure usage reporting with a read-only, team-scoped Management Key:
48
+
49
+ ```text
50
+ /login pi-usage-bars-xai-management
51
+ ```
52
+
53
+ Select **xAI Management (pi-usage-bars)** and paste the key into Pi's secret prompt. For headless or CI use, `XAI_MANAGEMENT_KEY` is also accepted from the environment. Organization-scoped Management Keys are not selected or aggregated automatically.
54
+
44
55
  ## Install
45
56
 
46
57
  Install the npm package:
@@ -77,7 +88,7 @@ Usage refresh runs in interactive TUI sessions every two minutes. It does not ru
77
88
 
78
89
  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.
79
90
 
80
- ![/usage command]
91
+ ![/usage command](https://raw.githubusercontent.com/hknet/pi-usage-bars/main/assets/usage-command.png)
81
92
 
82
93
  ### `--usage`
83
94
 
@@ -87,7 +98,7 @@ Pass `--usage` to print one JSON line for the active model provider and exit wit
87
98
  pi --no-extensions -e C:\hk\code\pi-usage-bars\extensions\usage-bars\index.ts --usage
88
99
  ```
89
100
 
90
- The result has `status` set to `ok`, `unconfigured`, `unsupported`, or `error`. No credential is included in the output.(https://raw.githubusercontent.com/hknet/pi-usage-bars/main/assets/usage-command.png)
101
+ The result has `status` set to `ok`, `unconfigured`, `unsupported`, or `error`. No credential is included in the output.
91
102
 
92
103
  ## Endpoint configuration
93
104
 
@@ -108,14 +119,18 @@ First-party monitoring endpoints can be overridden:
108
119
  | `PI_MOONSHOT_BALANCE_ENDPOINT` | `https://api.moonshot.ai/v1/users/me/balance` |
109
120
  | `PI_MOONSHOT_CN_BALANCE_ENDPOINT` | `https://api.moonshot.cn/v1/users/me/balance` |
110
121
  | `PI_BASETEN_USAGE_ENDPOINT` | `https://api.baseten.co/v1/billing/usage_summary` |
122
+ | `PI_VERCEL_AI_GATEWAY_CREDITS_ENDPOINT` | `https://ai-gateway.vercel.sh/v1/credits` |
123
+ | `PI_FIREWORKS_API_ENDPOINT` | `https://api.fireworks.ai/v1` |
124
+ | `PI_FIREWORKS_ACCOUNT_ID` | Automatically discovered when exactly one account is accessible |
125
+ | `PI_XAI_MANAGEMENT_API_ENDPOINT` | `https://management-api.x.ai` |
111
126
 
112
- **Security:** the corresponding provider token is sent as a bearer token to the configured endpoint. Only override these variables with an endpoint you trust.
127
+ **Security:** the corresponding provider token is sent as a bearer token to the configured endpoint. Only override endpoint variables with an endpoint you trust. `PI_FIREWORKS_ACCOUNT_ID` selects an account already returned by Fireworks account discovery; it may be either the account slug or its `accounts/<slug>` resource name. When a key can access multiple accounts, this variable is required rather than guessing or aggregating across accounts.
113
128
 
114
129
  The Codex and Claude usage endpoints are fixed to their first-party services. Claude responses are cached briefly in the system temporary directory to coordinate multiple Pi processes and reduce rate limiting. The cache contains usage values, not credentials.
115
130
 
116
131
  ## Financial metrics roadmap
117
132
 
118
- Quota percentages and monetary account data have different meaning and color semantics. OpenRouter, DeepSeek, Moonshot, and MiniMax financial data are rendered as neutral account values; percentages are used only when an actual limit exists.
133
+ Quota percentages and monetary account data have different meaning and color semantics. OpenRouter, DeepSeek, Moonshot, MiniMax, Vercel AI Gateway, Fireworks, and xAI financial data are rendered as neutral account values; percentages are used only when an actual limit exists.
119
134
 
120
135
  ### Future: Qwen Token Plan
121
136
 
@@ -28,6 +28,40 @@ Pi's `baseten` provider resolves `BASETEN_API_KEY`. Baseten documents `GET https
28
28
 
29
29
  **Recheck when:** Baseten publishes a first-party balance, budget, or quota API that permits a more complete account indicator.
30
30
 
31
+ ## Vercel AI Gateway
32
+
33
+ **Status:** Supported as of 2026-09-24.
34
+
35
+ Pi's `vercel-ai-gateway` provider resolves `AI_GATEWAY_API_KEY`. Vercel documents `GET https://ai-gateway.vercel.sh/v1/credits`, authenticated with the same API key as a bearer token. The response reports the team's remaining AI Gateway Credits balance and total lifetime spend in USD.
36
+
37
+ **Recheck when:** Vercel adds defined-period spend or budget fields that provide more actionable detail than lifetime spend.
38
+
39
+ ## Fireworks
40
+
41
+ **Status:** Supported as of 2026-09-24.
42
+
43
+ Fireworks documents bearer-key-authenticated account discovery through `GET https://api.fireworks.ai/v1/accounts` and account-wide rated costs through `GET /v1/accounts/{account_id}/billing/summary`. Fireworks states that any key on the target account can use the API. A live redacted test with an ordinary user API key resolved through Pi's `fireworks` provider returned HTTP 200 for account discovery, billing summary, quotas, and the self-scoped usage-cost query. It exposed one accessible account; no credential, account identifier, or raw response was retained.
44
+
45
+ The extension reports rated spend for the current UTC calendar month from the billing summary. It does not use the `monthly-spend-usd` quota as a budget percentage because validation observed a `9,999,999` default that appears to mean effectively unlimited rather than an actionable budget. Exactly one accessible account is selected automatically. When a key can access multiple accounts, `PI_FIREWORKS_ACCOUNT_ID` must match one of the discovered account IDs; the extension does not guess or aggregate accounts.
46
+
47
+ **Recheck when:** Fireworks documents an account credit balance or a reliable distinction between explicit spend budgets and effectively unlimited quota values.
48
+
49
+ ## xAI
50
+
51
+ **Status:** Supported as of 2026-09-24.
52
+
53
+ xAI documents its billing APIs at `https://management-api.x.ai`, authenticated with a Management Key that is deliberately separate from the normal inference API key or subscription OAuth credential used by Pi's `xai` provider. The extension registers the model-less `pi-usage-bars-xai-management` provider so `/login` can prompt for and store a read-only Management Key through Pi's credential system. `XAI_MANAGEMENT_KEY` remains an optional environment fallback.
54
+
55
+ A live redacted test with a read-only, team-scoped key returned HTTP 200 for key validation, prepaid balance, current invoice preview, and postpaid spending limits. The extension validates `SCOPE_TEAM`, obtains the team ID internally, and reports the prepaid accounting total as a positive available balance plus `coreInvoice.totalWithCorr` as current billing-cycle spend. It never logs the key, team ID, ACL contents, or raw response. Organization-scoped keys are rejected rather than guessing or aggregating teams.
56
+
57
+ **Recheck when:** xAI adds team discovery for organization-scoped Management Keys or exposes billing through the ordinary inference credential.
58
+
59
+ ## Meta Muse
60
+
61
+ **Status:** Blocked — no documented account-usage API found as of 2026-09-24.
62
+
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
+
31
65
  ## Acceptance criteria for a new provider
32
66
 
33
67
  A provider is suitable when a documented first-party API or response header supplies at least one meaningful account-level value:
@@ -14,7 +14,10 @@ export type ProviderKey =
14
14
  | "deepseek"
15
15
  | "moonshot"
16
16
  | "moonshot-cn"
17
- | "baseten";
17
+ | "baseten"
18
+ | "vercel"
19
+ | "fireworks"
20
+ | "xai";
18
21
  export type PiProviderId =
19
22
  | "openai-codex"
20
23
  | "anthropic"
@@ -27,7 +30,10 @@ export type PiProviderId =
27
30
  | "deepseek"
28
31
  | "moonshotai"
29
32
  | "moonshotai-cn"
30
- | "baseten";
33
+ | "baseten"
34
+ | "vercel-ai-gateway"
35
+ | "fireworks"
36
+ | "pi-usage-bars-xai-management";
31
37
 
32
38
  export interface AccountBalance {
33
39
  amount: number;
@@ -85,6 +91,10 @@ export interface UsageEndpoints {
85
91
  moonshotBalance: string;
86
92
  moonshotCnBalance: string;
87
93
  basetenUsage: string;
94
+ vercelCredits: string;
95
+ fireworksApi: string;
96
+ fireworksAccountId?: string;
97
+ xaiManagementApi: string;
88
98
  }
89
99
 
90
100
  export interface HeadersLike {
@@ -125,6 +135,10 @@ export interface BasetenUsageFetchConfig extends FetchConfig {
125
135
  nowMs?: number;
126
136
  }
127
137
 
138
+ export interface FireworksUsageFetchConfig extends FetchConfig {
139
+ nowMs?: number;
140
+ }
141
+
128
142
  interface JsonRequestSuccess {
129
143
  ok: true;
130
144
  data: unknown;
@@ -182,6 +196,10 @@ export const DEFAULT_DEEPSEEK_BALANCE_ENDPOINT = "https://api.deepseek.com/user/
182
196
  export const DEFAULT_MOONSHOT_BALANCE_ENDPOINT = "https://api.moonshot.ai/v1/users/me/balance";
183
197
  export const DEFAULT_MOONSHOT_CN_BALANCE_ENDPOINT = "https://api.moonshot.cn/v1/users/me/balance";
184
198
  export const DEFAULT_BASETEN_USAGE_ENDPOINT = "https://api.baseten.co/v1/billing/usage_summary";
199
+ export const DEFAULT_VERCEL_CREDITS_ENDPOINT = "https://ai-gateway.vercel.sh/v1/credits";
200
+ export const DEFAULT_FIREWORKS_API_ENDPOINT = "https://api.fireworks.ai/v1";
201
+ export const DEFAULT_XAI_MANAGEMENT_API_ENDPOINT = "https://management-api.x.ai";
202
+ export const XAI_MANAGEMENT_PROVIDER_ID = "pi-usage-bars-xai-management";
185
203
 
186
204
  export function resolveUsageEndpoints(env: NodeJS.ProcessEnv = process.env): UsageEndpoints {
187
205
  const configured = (value: string | undefined, fallback: string) => {
@@ -203,6 +221,10 @@ export function resolveUsageEndpoints(env: NodeJS.ProcessEnv = process.env): Usa
203
221
  moonshotBalance: configured(env.PI_MOONSHOT_BALANCE_ENDPOINT, DEFAULT_MOONSHOT_BALANCE_ENDPOINT),
204
222
  moonshotCnBalance: configured(env.PI_MOONSHOT_CN_BALANCE_ENDPOINT, DEFAULT_MOONSHOT_CN_BALANCE_ENDPOINT),
205
223
  basetenUsage: configured(env.PI_BASETEN_USAGE_ENDPOINT, DEFAULT_BASETEN_USAGE_ENDPOINT),
224
+ vercelCredits: configured(env.PI_VERCEL_AI_GATEWAY_CREDITS_ENDPOINT, DEFAULT_VERCEL_CREDITS_ENDPOINT),
225
+ fireworksApi: configured(env.PI_FIREWORKS_API_ENDPOINT, DEFAULT_FIREWORKS_API_ENDPOINT),
226
+ fireworksAccountId: env.PI_FIREWORKS_ACCOUNT_ID?.trim() || undefined,
227
+ xaiManagementApi: configured(env.PI_XAI_MANAGEMENT_API_ENDPOINT, DEFAULT_XAI_MANAGEMENT_API_ENDPOINT),
206
228
  };
207
229
  }
208
230
 
@@ -1131,6 +1153,258 @@ export async function fetchBasetenUsage(token: string, config: BasetenUsageFetch
1131
1153
  };
1132
1154
  }
1133
1155
 
1156
+ interface FireworksMoney {
1157
+ currencyCode: string;
1158
+ amount: number;
1159
+ }
1160
+
1161
+ function parseFireworksMoney(value: unknown): FireworksMoney | null {
1162
+ const raw = asObject(value);
1163
+ if (!raw || typeof raw.currencyCode !== "string" || !raw.currencyCode.trim()) return null;
1164
+ const parsedUnits = readNumber(raw.units);
1165
+ const parsedNanos = readNumber(raw.nanos);
1166
+ if ((raw.units !== undefined && parsedUnits === null) || (raw.nanos !== undefined && parsedNanos === null)) {
1167
+ return null;
1168
+ }
1169
+ const units = parsedUnits ?? 0;
1170
+ const nanos = parsedNanos ?? 0;
1171
+ if (!Number.isInteger(nanos) || Math.abs(nanos) >= 1_000_000_000) return null;
1172
+ return {
1173
+ currencyCode: raw.currencyCode.trim().toUpperCase(),
1174
+ amount: units + nanos / 1_000_000_000,
1175
+ };
1176
+ }
1177
+
1178
+ export function extractFireworksSpendFromPayload(payload: unknown): UsageData | null {
1179
+ const root = asObject(payload);
1180
+ if (!root || !Array.isArray(root.lineItems)) return null;
1181
+ const amounts: FireworksMoney[] = [];
1182
+ for (const value of root.lineItems) {
1183
+ const item = asObject(value);
1184
+ const parsed = parseFireworksMoney(item?.totalCost);
1185
+ if (!parsed) return null;
1186
+ amounts.push(parsed);
1187
+ }
1188
+ const currencies = new Set(amounts.map((amount) => amount.currencyCode));
1189
+ if (currencies.size > 1) return null;
1190
+ const unit = amounts[0]?.currencyCode ?? "USD";
1191
+ const monthly = amounts.reduce((sum, amount) => sum + amount.amount, 0);
1192
+ return {
1193
+ session: 0,
1194
+ weekly: 0,
1195
+ quotaHidden: true,
1196
+ accountSpend: { unit, monthly: Number(monthly.toFixed(6)) },
1197
+ };
1198
+ }
1199
+
1200
+ function fireworksMonthRange(nowMs: number): { startTime: string; endTime: string } {
1201
+ const now = new Date(nowMs);
1202
+ return {
1203
+ startTime: new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)).toISOString(),
1204
+ // Fireworks treats the end date as exclusive and aggregates by UTC date.
1205
+ endTime: new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() + 1)).toISOString(),
1206
+ };
1207
+ }
1208
+
1209
+ function normalizeFireworksAccountId(value: string): string | null {
1210
+ const normalized = value.trim().replace(/^accounts\//, "");
1211
+ return /^[A-Za-z0-9._-]+$/.test(normalized) ? normalized : null;
1212
+ }
1213
+
1214
+ async function requestFireworksJson(
1215
+ url: string,
1216
+ init: RequestInit,
1217
+ config: RequestConfig,
1218
+ ): Promise<JsonRequestResult> {
1219
+ const first = await requestJson(url, init, config);
1220
+ if (first.ok || ![429, 502, 503, 504].includes(first.status ?? 0)) return first;
1221
+
1222
+ const retryAfterMs = parseRetryAfterMs(getHeader(first.headers, "retry-after"));
1223
+ try {
1224
+ await sleep(Math.min(retryAfterMs ?? 250, 2_000), config.signal);
1225
+ } catch {
1226
+ return { ok: false, error: "request cancelled", status: null };
1227
+ }
1228
+ return requestJson(url, init, config);
1229
+ }
1230
+
1231
+ export async function fetchFireworksUsage(
1232
+ token: string,
1233
+ config: FireworksUsageFetchConfig = {},
1234
+ ): Promise<UsageData> {
1235
+ const endpoints = config.endpoints ?? resolveUsageEndpoints(config.env);
1236
+ const headers = { Authorization: `Bearer ${token}`, Accept: "application/json" };
1237
+ const apiBase = endpoints.fireworksApi.replace(/\/+$/, "");
1238
+ const accountsResult = await requestFireworksJson(`${apiBase}/accounts?pageSize=200`, { headers }, config);
1239
+ if (!accountsResult.ok) {
1240
+ return { session: 0, weekly: 0, error: `account discovery: ${accountsResult.error}` };
1241
+ }
1242
+
1243
+ const root = asObject(accountsResult.data);
1244
+ const accounts = Array.isArray(root?.accounts) ? root.accounts.map(asObject).filter(Boolean) : [];
1245
+ const accountIds = accounts.flatMap((account) => {
1246
+ const name = typeof account?.name === "string" ? account.name : "";
1247
+ const id = normalizeFireworksAccountId(name);
1248
+ return id ? [id] : [];
1249
+ });
1250
+ const totalSize = readNumber(root?.totalSize);
1251
+ const configuredId = endpoints.fireworksAccountId
1252
+ ? normalizeFireworksAccountId(endpoints.fireworksAccountId)
1253
+ : null;
1254
+ if (endpoints.fireworksAccountId && !configuredId) {
1255
+ return { session: 0, weekly: 0, error: "invalid PI_FIREWORKS_ACCOUNT_ID" };
1256
+ }
1257
+
1258
+ let accountId: string | undefined;
1259
+ if (configuredId) {
1260
+ if (!accountIds.includes(configuredId)) {
1261
+ return { session: 0, weekly: 0, error: "PI_FIREWORKS_ACCOUNT_ID is not accessible with this key" };
1262
+ }
1263
+ accountId = configuredId;
1264
+ } else if (accountIds.length === 1 && (totalSize === null || totalSize <= 1)) {
1265
+ // Fireworks may return totalSize: 0 alongside one account, so trust the
1266
+ // usable resource list unless totalSize explicitly reports more accounts.
1267
+ accountId = accountIds[0];
1268
+ } else if (accountIds.length === 0) {
1269
+ return { session: 0, weekly: 0, error: "no accessible Fireworks account" };
1270
+ } else {
1271
+ return {
1272
+ session: 0,
1273
+ weekly: 0,
1274
+ error: "multiple Fireworks accounts; set PI_FIREWORKS_ACCOUNT_ID",
1275
+ };
1276
+ }
1277
+
1278
+ const { startTime, endTime } = fireworksMonthRange(config.nowMs ?? Date.now());
1279
+ const query = new URLSearchParams({ startTime, endTime });
1280
+ const result = await requestFireworksJson(
1281
+ `${apiBase}/accounts/${encodeURIComponent(accountId)}/billing/summary?${query}`,
1282
+ { headers },
1283
+ config,
1284
+ );
1285
+ if (!result.ok) return { session: 0, weekly: 0, error: `billing summary: ${result.error}` };
1286
+ return extractFireworksSpendFromPayload(result.data) ?? {
1287
+ session: 0,
1288
+ weekly: 0,
1289
+ error: "unrecognized billing summary response shape",
1290
+ };
1291
+ }
1292
+
1293
+ function readXaiUsdCents(value: unknown): number | null {
1294
+ const raw = asObject(value);
1295
+ const cents = readNumber(raw?.val ?? value);
1296
+ return cents === null ? null : Number((cents / 100).toFixed(6));
1297
+ }
1298
+
1299
+ export function extractXaiBillingFromPayloads(
1300
+ prepaidPayload: unknown,
1301
+ invoicePreviewPayload: unknown,
1302
+ ): UsageData | null {
1303
+ const prepaid = asObject(prepaidPayload);
1304
+ const preview = asObject(invoicePreviewPayload);
1305
+ const accountingBalance = readXaiUsdCents(prepaid?.total);
1306
+ const currentCycleTotal = readXaiUsdCents(asObject(preview?.coreInvoice)?.totalWithCorr);
1307
+ if (accountingBalance === null && currentCycleTotal === null) return null;
1308
+
1309
+ return {
1310
+ session: 0,
1311
+ weekly: 0,
1312
+ quotaHidden: true,
1313
+ // xAI represents purchases as negative and spend as positive in its
1314
+ // prepaid accounting ledger, so the available balance is the negated total.
1315
+ accountBalance: accountingBalance === null
1316
+ ? undefined
1317
+ : { amount: -accountingBalance, unit: "USD", label: "Prepaid balance" },
1318
+ accountSpend: currentCycleTotal === null
1319
+ ? undefined
1320
+ : { unit: "USD", monthly: currentCycleTotal },
1321
+ };
1322
+ }
1323
+
1324
+ export async function fetchXaiUsage(token: string, config: FetchConfig = {}): Promise<UsageData> {
1325
+ const endpoints = config.endpoints ?? resolveUsageEndpoints(config.env);
1326
+ const apiBase = endpoints.xaiManagementApi.replace(/\/+$/, "");
1327
+ const headers = { Authorization: `Bearer ${token}`, Accept: "application/json" };
1328
+ const validation = await requestJson(`${apiBase}/auth/management-keys/validation`, { headers }, config);
1329
+ if (!validation.ok) return { session: 0, weekly: 0, error: `key validation: ${validation.error}` };
1330
+
1331
+ const validationBody = asObject(validation.data);
1332
+ const scope = typeof validationBody?.scope === "string" ? validationBody.scope : "";
1333
+ if (scope !== "SCOPE_TEAM") {
1334
+ return {
1335
+ session: 0,
1336
+ weekly: 0,
1337
+ error: "xAI Management Key must be team-scoped",
1338
+ };
1339
+ }
1340
+ const teamId = typeof validationBody?.scopeId === "string" && validationBody.scopeId.trim()
1341
+ ? validationBody.scopeId.trim()
1342
+ : typeof validationBody?.teamId === "string" ? validationBody.teamId.trim() : "";
1343
+ if (!teamId) return { session: 0, weekly: 0, error: "key validation did not return a team ID" };
1344
+
1345
+ const team = encodeURIComponent(teamId);
1346
+ const [prepaid, preview] = await Promise.all([
1347
+ requestJson(`${apiBase}/v1/billing/teams/${team}/prepaid/balance`, { headers }, config),
1348
+ requestJson(`${apiBase}/v1/billing/teams/${team}/postpaid/invoice/preview`, { headers }, config),
1349
+ ]);
1350
+ const usage = extractXaiBillingFromPayloads(
1351
+ prepaid.ok ? prepaid.data : undefined,
1352
+ preview.ok ? preview.data : undefined,
1353
+ );
1354
+ if (!usage) {
1355
+ const errors = [
1356
+ prepaid.ok ? undefined : `prepaid balance: ${prepaid.error}`,
1357
+ preview.ok ? undefined : `invoice preview: ${preview.error}`,
1358
+ ].filter((error): error is string => Boolean(error));
1359
+ return {
1360
+ session: 0,
1361
+ weekly: 0,
1362
+ error: errors.length > 0 ? errors.join("; ") : "unrecognized xAI billing response shape",
1363
+ };
1364
+ }
1365
+ const partialErrors = [
1366
+ prepaid.ok ? undefined : `prepaid balance unavailable (${prepaid.error})`,
1367
+ preview.ok ? undefined : `invoice preview unavailable (${preview.error})`,
1368
+ ].filter((error): error is string => Boolean(error));
1369
+ return { ...usage, warning: partialErrors.length > 0 ? partialErrors.join("; ") : undefined };
1370
+ }
1371
+
1372
+ export function extractVercelCreditsFromPayload(payload: unknown): UsageData | null {
1373
+ const root = asObject(payload);
1374
+ if (!root) return null;
1375
+ const balance = readNumber(root.balance);
1376
+ const totalUsed = readNumber(root.total_used ?? root.totalUsed);
1377
+ if (balance === null && totalUsed === null) return null;
1378
+
1379
+ return {
1380
+ session: 0,
1381
+ weekly: 0,
1382
+ quotaHidden: true,
1383
+ accountBalance: balance === null
1384
+ ? undefined
1385
+ : { amount: balance, unit: "USD", label: "Balance" },
1386
+ accountSpend: totalUsed === null
1387
+ ? undefined
1388
+ : { unit: "USD", lifetime: totalUsed },
1389
+ warning: balance !== null && balance <= 0
1390
+ ? "Balance exhausted; inference requests may be rejected"
1391
+ : undefined,
1392
+ };
1393
+ }
1394
+
1395
+ export async function fetchVercelCredits(token: string, config: FetchConfig = {}): Promise<UsageData> {
1396
+ const endpoints = config.endpoints ?? resolveUsageEndpoints(config.env);
1397
+ const result = await requestJson(endpoints.vercelCredits, {
1398
+ headers: { Authorization: `Bearer ${token}`, Accept: "application/json" },
1399
+ }, config);
1400
+ if (!result.ok) return { session: 0, weekly: 0, error: result.error };
1401
+ return extractVercelCreditsFromPayload(result.data) ?? {
1402
+ session: 0,
1403
+ weekly: 0,
1404
+ error: "unrecognized response shape",
1405
+ };
1406
+ }
1407
+
1134
1408
  export function extractMoonshotBalanceFromPayload(
1135
1409
  payload: unknown,
1136
1410
  provider: "moonshot" | "moonshot-cn" = "moonshot",
@@ -1241,6 +1515,9 @@ export function detectProvider(
1241
1515
  case "moonshotai": return "moonshot";
1242
1516
  case "moonshotai-cn": return "moonshot-cn";
1243
1517
  case "baseten": return "baseten";
1518
+ case "vercel-ai-gateway": return "vercel";
1519
+ case "fireworks": return "fireworks";
1520
+ case "xai": return "xai";
1244
1521
  default: return null;
1245
1522
  }
1246
1523
  }
@@ -1259,6 +1536,9 @@ export function providerToPiProviderId(provider: ProviderKey): PiProviderId {
1259
1536
  case "moonshot": return "moonshotai";
1260
1537
  case "moonshot-cn": return "moonshotai-cn";
1261
1538
  case "baseten": return "baseten";
1539
+ case "vercel": return "vercel-ai-gateway";
1540
+ case "fireworks": return "fireworks";
1541
+ case "xai": return XAI_MANAGEMENT_PROVIDER_ID;
1262
1542
  }
1263
1543
  }
1264
1544
 
@@ -1291,6 +1571,9 @@ export async function fetchAllUsages(
1291
1571
  moonshot: null,
1292
1572
  "moonshot-cn": null,
1293
1573
  baseten: null,
1574
+ vercel: null,
1575
+ fireworks: null,
1576
+ xai: null,
1294
1577
  };
1295
1578
  const tasks: Promise<void>[] = [];
1296
1579
 
@@ -1324,6 +1607,11 @@ export async function fetchAllUsages(
1324
1607
  assign("moonshot-cn", fetchMoonshotBalance(tokens["moonshot-cn"], "moonshot-cn", { ...config, endpoints }));
1325
1608
  }
1326
1609
  if (tokens.baseten) assign("baseten", fetchBasetenUsage(tokens.baseten, { ...config, endpoints }));
1610
+ if (tokens.vercel) assign("vercel", fetchVercelCredits(tokens.vercel, { ...config, endpoints }));
1611
+ if (tokens.fireworks) {
1612
+ assign("fireworks", fetchFireworksUsage(tokens.fireworks, { ...config, endpoints, nowMs: config.nowMs }));
1613
+ }
1614
+ if (tokens.xai) assign("xai", fetchXaiUsage(tokens.xai, { ...config, endpoints }));
1327
1615
 
1328
1616
  await Promise.all(tasks);
1329
1617
 
@@ -7,6 +7,7 @@ import {
7
7
  type KeybindingsManager,
8
8
  type Theme,
9
9
  } from "@earendil-works/pi-coding-agent";
10
+ import { createProvider, envApiKeyAuth } from "@earendil-works/pi-ai";
10
11
  import {
11
12
  Container,
12
13
  Input,
@@ -24,10 +25,13 @@ import {
24
25
  fetchClaudeUsageWithFallback,
25
26
  fetchCodexUsage,
26
27
  fetchDeepSeekBalance,
28
+ fetchFireworksUsage,
27
29
  fetchKimiUsage,
28
30
  fetchMiniMaxUsage,
29
31
  fetchMoonshotBalance,
30
32
  fetchOpenRouterUsage,
33
+ fetchVercelCredits,
34
+ fetchXaiUsage,
31
35
  fetchZaiUsage,
32
36
  providerToPiProviderId,
33
37
  resolveUsageEndpoints,
@@ -37,12 +41,16 @@ import {
37
41
  type UsageByProvider,
38
42
  type UsageData,
39
43
  type UsageTokens,
44
+ XAI_MANAGEMENT_PROVIDER_ID,
40
45
  } from "./core";
41
46
 
47
+ export { XAI_MANAGEMENT_PROVIDER_ID } from "./core";
48
+
42
49
  const POLL_INTERVAL_MS = 2 * 60 * 1000;
43
50
  const EXTENSION_ID = "@hk_net/pi-usage-bars";
44
51
  const STATUS_KEY = EXTENSION_ID;
45
52
  const USAGE_UPDATE_EVENT = `${EXTENSION_ID}:update`;
53
+ const XAI_MANAGEMENT_PROVIDER_NAME = "xAI Management (pi-usage-bars)";
46
54
  const PROVIDERS: readonly ProviderKey[] = [
47
55
  "codex",
48
56
  "claude",
@@ -56,6 +64,9 @@ const PROVIDERS: readonly ProviderKey[] = [
56
64
  "moonshot",
57
65
  "moonshot-cn",
58
66
  "baseten",
67
+ "vercel",
68
+ "fireworks",
69
+ "xai",
59
70
  ];
60
71
 
61
72
  const PROVIDER_LABELS: Record<ProviderKey, string> = {
@@ -71,6 +82,9 @@ const PROVIDER_LABELS: Record<ProviderKey, string> = {
71
82
  moonshot: "Moonshot/Kimi API (Global)",
72
83
  "moonshot-cn": "Moonshot/Kimi API (China)",
73
84
  baseten: "Baseten",
85
+ vercel: "Vercel AI Gateway",
86
+ fireworks: "Fireworks",
87
+ xai: "xAI",
74
88
  };
75
89
 
76
90
  function formatFinancialAmount(amount: number, unit: string): string {
@@ -449,6 +463,22 @@ interface UsageState extends UsageByProvider {
449
463
  }
450
464
 
451
465
  export default function (pi: ExtensionAPI): void {
466
+ // xAI exposes billing only through a separate Management Key. Register a
467
+ // model-less provider so Pi owns secret prompting, storage, and resolution;
468
+ // the key can never be selected for or sent to inference.
469
+ pi.registerProvider(createProvider({
470
+ id: XAI_MANAGEMENT_PROVIDER_ID,
471
+ name: XAI_MANAGEMENT_PROVIDER_NAME,
472
+ auth: {
473
+ apiKey: envApiKeyAuth("xAI read-only Management Key", ["XAI_MANAGEMENT_KEY"]),
474
+ },
475
+ models: [],
476
+ api: {
477
+ stream() { throw new Error("Credential-only provider does not support inference"); },
478
+ streamSimple() { throw new Error("Credential-only provider does not support inference"); },
479
+ },
480
+ }));
481
+
452
482
  pi.registerFlag("usage", {
453
483
  description: "Print one-line usage for the active provider and exit",
454
484
  type: "boolean",
@@ -469,6 +499,9 @@ export default function (pi: ExtensionAPI): void {
469
499
  moonshot: null,
470
500
  "moonshot-cn": null,
471
501
  baseten: null,
502
+ vercel: null,
503
+ fireworks: null,
504
+ xai: null,
472
505
  activeProvider: null,
473
506
  available: {},
474
507
  };
@@ -645,6 +678,9 @@ export default function (pi: ExtensionAPI): void {
645
678
  state["moonshot-cn"] = await fetchMoonshotBalance(credential.token, "moonshot-cn", { endpoints, signal });
646
679
  }
647
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 });
648
684
  }
649
685
 
650
686
  async function runPoll(): Promise<void> {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hk_net/pi-usage-bars",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Quota, balance, and spend indicators for current Pi providers",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -15,7 +15,10 @@
15
15
  "openrouter",
16
16
  "deepseek",
17
17
  "moonshot",
18
- "baseten"
18
+ "baseten",
19
+ "vercel",
20
+ "fireworks",
21
+ "xai"
19
22
  ],
20
23
  "license": "MIT",
21
24
  "repository": {
@@ -48,10 +51,14 @@
48
51
  "node": ">=22.19.0"
49
52
  },
50
53
  "peerDependencies": {
54
+ "@earendil-works/pi-ai": "*",
51
55
  "@earendil-works/pi-coding-agent": "*",
52
56
  "@earendil-works/pi-tui": "*"
53
57
  },
54
58
  "peerDependenciesMeta": {
59
+ "@earendil-works/pi-ai": {
60
+ "optional": true
61
+ },
55
62
  "@earendil-works/pi-coding-agent": {
56
63
  "optional": true
57
64
  },
@@ -60,8 +67,9 @@
60
67
  }
61
68
  },
62
69
  "devDependencies": {
63
- "@earendil-works/pi-coding-agent": "0.84.4",
64
- "@earendil-works/pi-tui": "0.84.4",
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",
65
73
  "@types/bun": "1.3.14",
66
74
  "@types/node": "24.13.3",
67
75
  "typescript": "5.9.3"