@cad0p/pi-usage 0.11.5 → 0.11.6-20261107.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.
@@ -41,6 +41,9 @@ const ANTIGRAVITY_OAUTH_SOURCES = [
41
41
  join(homedir(), ".pi", "agent", "npm", "node_modules", "pi-antigravity", "dist", "auth", "oauth.js"),
42
42
  ];
43
43
 
44
+ /** Renewed Google access tokens live only in this process, until shortly before expiry. */
45
+ const renewedAccessTokens = new Map();
46
+
44
47
  /**
45
48
  * Recover the two `atob("..." + "...")` literals from the installed package.
46
49
  *
@@ -89,11 +92,15 @@ export function resolveOAuthClient(options = {}) {
89
92
  }
90
93
 
91
94
  /**
92
- * @param {{ client?: { clientId: string, clientSecret: string }, fetchFn?: typeof fetch, timeoutMs?: number }} [options]
95
+ * Describe the OAuth client a refresh used, resolved the same way the refresh
96
+ * resolved it: a description of the environment's client while the request went
97
+ * out with the installed package's would name the wrong credential source.
98
+ *
99
+ * @param {{ client?: { clientId: string, clientSecret: string }, env?: Record<string, string | undefined>, sourcePath?: string }} [options]
93
100
  * @returns {string}
94
101
  */
95
102
  export function describeOAuthClient(options = {}) {
96
- const client = options.client ?? resolveOAuthClient();
103
+ const client = options.client ?? resolveOAuthClient({ env: options.env, sourcePath: options.sourcePath });
97
104
  return client.source === "env"
98
105
  ? "client from ANTIGRAVITY_CLIENT_ID/SECRET"
99
106
  : client.source === "pi-antigravity"
@@ -108,12 +115,16 @@ export function describeOAuthClient(options = {}) {
108
115
  * fetchFn?: typeof fetch,
109
116
  * timeoutMs?: number,
110
117
  * now?: number,
118
+ * env?: Record<string, string | undefined>,
119
+ * sourcePath?: string,
111
120
  * }} [options]
112
121
  * @returns {Promise<{ access: string, refresh: string, expires: number } | { error: string }>}
113
122
  */
114
123
  export async function refreshAccessToken(refreshToken, options = {}) {
115
124
  if (!refreshToken) return { error: "no refresh token available" };
116
- const client = options.client ?? resolveOAuthClient();
125
+ // The caller's environment and package source decide the client. Keep these
126
+ // resolution inputs aligned with describeOAuthClient for an accurate failure.
127
+ const client = options.client ?? resolveOAuthClient({ env: options.env, sourcePath: options.sourcePath });
117
128
 
118
129
  const response = await requestJson(GOOGLE_TOKEN_URL, {
119
130
  method: "POST",
@@ -152,12 +163,30 @@ export async function refreshAccessToken(refreshToken, options = {}) {
152
163
  * now?: number,
153
164
  * bufferMs?: number,
154
165
  * enabled?: boolean,
166
+ * env?: Record<string, string | undefined>,
167
+ * sourcePath?: string,
168
+ * cacheKey?: string,
155
169
  * }} [options]
156
170
  * @returns {Promise<{ ok: boolean, refreshed: boolean, error?: string }>}
157
171
  */
158
172
  export async function ensureFreshAccessToken(account, options = {}) {
159
173
  const now = options.now ?? Date.now();
160
174
  const bufferMs = options.bufferMs ?? 5 * 60 * 1000;
175
+ const cacheKey = options.cacheKey;
176
+ if (cacheKey) {
177
+ const cached = renewedAccessTokens.get(cacheKey);
178
+ if (cached && cached.expiresAtMs - bufferMs > now) {
179
+ account.access = cached.access;
180
+ account.expiresAtMs = cached.expiresAtMs;
181
+ return { ok: true, refreshed: true };
182
+ }
183
+ if (cached) {
184
+ clearTimeout(cached.timer);
185
+ cached.access = "";
186
+ renewedAccessTokens.delete(cacheKey);
187
+ }
188
+ }
189
+
161
190
  const expiring = !account.expiresAtMs || account.expiresAtMs - bufferMs <= now;
162
191
  if (!expiring) return { ok: true, refreshed: false };
163
192
  if (options.enabled === false) return { ok: Boolean(account.access), refreshed: false, error: "refresh disabled" };
@@ -169,5 +198,16 @@ export async function ensureFreshAccessToken(account, options = {}) {
169
198
  account.access = result.access;
170
199
  account.refresh = result.refresh;
171
200
  account.expiresAtMs = result.expires;
201
+ if (cacheKey) {
202
+ const entry = { access: result.access, expiresAtMs: result.expires, timer: null };
203
+ const clearAfterMs = Math.max(1, result.expires - bufferMs - now);
204
+ entry.timer = setTimeout(() => {
205
+ if (renewedAccessTokens.get(cacheKey) !== entry) return;
206
+ entry.access = "";
207
+ renewedAccessTokens.delete(cacheKey);
208
+ }, clearAfterMs);
209
+ entry.timer.unref?.();
210
+ renewedAccessTokens.set(cacheKey, entry);
211
+ }
172
212
  return { ok: true, refreshed: true };
173
213
  }
@@ -11,11 +11,11 @@
11
11
  * Response shape: `groups[].buckets[]` with
12
12
  * `{ bucketId, displayName, window, resetTime, remainingFraction, description }`.
13
13
  *
14
- * Google does not rotate this refresh token, but Pi owns the credential and this
15
- * project is read-only, so no refresh is performed here either.
14
+ * Google does not rotate this refresh token, so an expired access token may be
15
+ * renewed in memory. The renewed value is cached only for this process lifetime.
16
16
  */
17
17
 
18
- import { buildWindow, clampPercent, degradedResult, displayIdentity, finiteNumber, stringValue, windowFromName } from "../model.js";
18
+ import { buildWindow, clampPercent, degradedResult, displayIdentity, finiteNumber, identityKind, stringValue, windowFromName } from "../model.js";
19
19
  import { requestJson } from "../http.js";
20
20
  import { describeOAuthClient, ensureFreshAccessToken } from "./antigravity-oauth.js";
21
21
 
@@ -109,6 +109,24 @@ function windowFromBucket(bucket, context, now) {
109
109
  });
110
110
  }
111
111
 
112
+ /**
113
+ * The account line for a resolved project.
114
+ *
115
+ * Pi stores no e-mail for Antigravity, so the project id *is* the display
116
+ * identity; appending it again printed "project rising-f… · rising-f…". An
117
+ * account that has a better identity (an e-mail or an id) still gets the
118
+ * project, because the same login can hold several.
119
+ *
120
+ * @param {import("../auth/pi-auth.js").PiCredential} credential
121
+ * @param {string | null} projectId
122
+ * @returns {string}
123
+ */
124
+ function accountLabel(credential, projectId) {
125
+ const identity = displayIdentity(credential);
126
+ if (!projectId || identityKind(credential) === "projectId") return identity;
127
+ return `${identity} · ${projectId.slice(0, 8)}…`;
128
+ }
129
+
112
130
  /**
113
131
  * @param {import("../auth/pi-auth.js").PiCredential} credential
114
132
  * @param {{ now?: number, fetchFn?: typeof fetch, timeoutMs?: number, expiresInMin?: number | null, env?: Record<string, string | undefined>, refresh?: boolean }} [options]
@@ -139,7 +157,20 @@ export async function fetchQuota(credential, options = {}) {
139
157
  timeoutMs: options.timeoutMs,
140
158
  now,
141
159
  enabled: options.refresh,
160
+ env: options.env,
161
+ cacheKey: `${credential.source}\\u0000${credential.identity}`,
142
162
  });
163
+ // `expiresInMin` arrives from the engine as the freshness of the *stored*
164
+ // credential, and that is only the truth about this run when the refresh
165
+ // above did not happen: a token renewed in memory expires in an hour, so
166
+ // repeating the stored value made every surface print "token expired" (and
167
+ // the engine warn about it) next to healthy windows. A refresh that failed
168
+ // keeps the stored value — then the expiry claim is what the user must see.
169
+ const renewed = freshness.refreshed === true;
170
+ const expiresInMin = renewed ? null : options.expiresInMin ?? null;
171
+ // Present only when a renewal happened: an always-false field would be one
172
+ // more thing the JSON feed promises to keep.
173
+ const renewal = renewed ? { tokenRenewedInMemory: true } : {};
143
174
  let projectId = credential.projectId ?? null;
144
175
 
145
176
  /** @type {string | null} */
@@ -211,7 +242,9 @@ export async function fetchQuota(credential, options = {}) {
211
242
 
212
243
  return {
213
244
  ...base,
214
- account: projectId ? `${displayIdentity(credential)} · ${projectId.slice(0, 8)}…` : displayIdentity(credential),
245
+ account: accountLabel(credential, projectId),
246
+ expiresInMin,
247
+ ...renewal,
215
248
  plan: stringValue(body.paidTier) ?? stringValue(body.currentTier),
216
249
  windows,
217
250
  error: null,
@@ -221,5 +254,11 @@ export async function fetchQuota(credential, options = {}) {
221
254
  }
222
255
 
223
256
  const suffix = authFailed ? ` (${describeOAuthClient({ env: options.env })})` : "";
224
- return degradedResult({ ...base, error: `${lastError ?? "Antigravity quota unavailable"}${suffix}` });
257
+ return degradedResult({
258
+ ...base,
259
+ account: accountLabel(credential, projectId),
260
+ expiresInMin,
261
+ ...renewal,
262
+ error: `${lastError ?? "Antigravity quota unavailable"}${suffix}`,
263
+ });
225
264
  }
@@ -0,0 +1,251 @@
1
+ /**
2
+ * Mistral quota.
3
+ *
4
+ * Pi's built-in `mistral` provider stores an API key (a Vibe key or a
5
+ * la Plateforme key; Mistral accepts either on the same API). The plan's usage
6
+ * is served by Mistral's public billing API, the same two reads the Vibe CLI
7
+ * makes for its footer gauge (`vibe/app_server/_billing.py`):
8
+ *
9
+ * GET /v1/billing/subscription -> plan_name, payg_enabled, vibe_payg_enabled
10
+ * GET /v1/billing/budget -> vibe_budget, api_budget: usage_percentage,
11
+ * initial_budget, currency, reset_at, payg_enabled
12
+ *
13
+ * Both are read-only GETs that cost no tokens. `/budget` needs the
14
+ * `see_org_inference_usage` permission, so a member without it still gets the
15
+ * plan, with a note instead of windows. The key is sent only as a Bearer header
16
+ * to api.mistral.ai and never appears in a result.
17
+ */
18
+
19
+ import { buildWindow, clampPercent, degradedResult, stringValue } from "../model.js";
20
+ import { requestJson } from "../http.js";
21
+
22
+ const API_BASE = "https://api.mistral.ai/v1";
23
+ const SUBSCRIPTION_URL = `${API_BASE}/billing/subscription`;
24
+ const BUDGET_URL = `${API_BASE}/billing/budget`;
25
+
26
+ /** A monthly budget, in the order every surface lists them. */
27
+ const BUDGETS = [
28
+ { field: "vibe_budget", id: "vibe", label: "Vibe monthly" },
29
+ { field: "api_budget", id: "api", label: "API monthly" },
30
+ ];
31
+
32
+ const MONTH_SECONDS = 2_592_000;
33
+ const PAYG = "pay-as-you-go";
34
+
35
+ /**
36
+ * @param {unknown} value
37
+ * @returns {Record<string, unknown> | null}
38
+ */
39
+ function record(value) {
40
+ return value && typeof value === "object" && !Array.isArray(value)
41
+ ? /** @type {Record<string, unknown>} */ (value)
42
+ : null;
43
+ }
44
+
45
+ /**
46
+ * The account label shown by every surface: the base auth.json entry has no
47
+ * numeric suffix, so it gets no number; a sibling slot is `#<slot>`.
48
+ *
49
+ * @param {{ slot?: string | null }} credential
50
+ * @returns {string}
51
+ */
52
+ function accountLabel(credential) {
53
+ return credential.slot ? `#${credential.slot}` : "";
54
+ }
55
+
56
+ /**
57
+ * "127.50 EUR", or null when the budget carries no usable amount.
58
+ *
59
+ * @param {unknown} amount
60
+ * @param {unknown} currency
61
+ * @returns {string | null}
62
+ */
63
+ function money(amount, currency) {
64
+ const value = typeof amount === "number" ? amount : typeof amount === "string" && amount.trim() !== "" ? Number(amount) : NaN;
65
+ // A budget is a few hundred euros; anything absurd is not printed as 1e+308.
66
+ if (!Number.isFinite(value) || value < 0 || value >= 1e9) return null;
67
+ const code = stringValue(currency);
68
+ const safeCode = code && /^[A-Za-z]{3}$/.test(code) ? ` ${code.toUpperCase()}` : "";
69
+ return `${value.toFixed(2)}${safeCode}`;
70
+ }
71
+
72
+ /**
73
+ * Map a `/billing/budget` body onto canonical windows.
74
+ *
75
+ * Mistral also repeats one budget at the top level of the body (today the API
76
+ * one); it is read only when neither named budget is present, so an older or
77
+ * smaller answer still shows something and a full answer never shows a budget
78
+ * twice.
79
+ *
80
+ * A budget that does not say whether pay-as-you-go is on falls back to the
81
+ * subscription's flag for it (`vibe_payg_enabled` for Vibe, `payg_enabled`
82
+ * for the API).
83
+ *
84
+ * @param {unknown} body
85
+ * @param {number} now
86
+ * @param {{ vibe?: boolean | null, api?: boolean | null }} [payg] From `/billing/subscription`.
87
+ * @returns {import("../model.js").QuotaWindow[]}
88
+ */
89
+ export function parseBudgetWindows(body, now = Date.now(), payg = {}) {
90
+ const root = record(body);
91
+ if (!root) return [];
92
+
93
+ /** @type {Array<{ id: string, label: string, entry: Record<string, unknown> }>} */
94
+ const named = [];
95
+ for (const spec of BUDGETS) {
96
+ const entry = record(root[spec.field]);
97
+ if (entry) named.push({ id: spec.id, label: spec.label, entry });
98
+ }
99
+ const windows = toWindows(named, now, payg);
100
+ // The top-level copy stands in only when no named budget produced a window,
101
+ // so a full answer never shows a budget twice and an unreadable named one
102
+ // does not hide a readable top-level one.
103
+ if (windows.length === 0 && root.usage_percentage !== undefined) {
104
+ return toWindows([{ id: "budget", label: "Monthly budget", entry: root }], now, payg);
105
+ }
106
+ return windows;
107
+ }
108
+
109
+ /**
110
+ * @param {Array<{ id: string, label: string, entry: Record<string, unknown> }>} budgets
111
+ * @param {number} now
112
+ * @param {{ vibe?: boolean | null, api?: boolean | null }} payg
113
+ * @returns {import("../model.js").QuotaWindow[]}
114
+ */
115
+ function toWindows(budgets, now, payg) {
116
+ /** @type {import("../model.js").QuotaWindow[]} */
117
+ const windows = [];
118
+ for (const { id, label, entry } of budgets) {
119
+ // No readable percentage, no window: "n/a" must not become an empty bar.
120
+ if (clampPercent(entry.usage_percentage) === null) continue;
121
+ const notes = [];
122
+ const amount = money(entry.initial_budget, entry.currency);
123
+ if (amount) notes.push(`of ${amount}`);
124
+ const paygOn = typeof entry.payg_enabled === "boolean" ? entry.payg_enabled : (id === "vibe" ? payg.vibe : payg.api) === true;
125
+ if (paygOn) notes.push(PAYG);
126
+ windows.push(
127
+ buildWindow({
128
+ id,
129
+ label,
130
+ usedPercent: entry.usage_percentage,
131
+ resetsAt: entry.reset_at ?? null,
132
+ windowSeconds: MONTH_SECONDS,
133
+ note: notes.length > 0 ? notes.join(" · ") : null,
134
+ now,
135
+ }),
136
+ );
137
+ }
138
+ return windows;
139
+ }
140
+
141
+ /**
142
+ * The pay-as-you-go flags of a `/billing/subscription` body.
143
+ *
144
+ * @param {unknown} body
145
+ * @returns {{ vibe: boolean | null, api: boolean | null }}
146
+ */
147
+ export function parsePayg(body) {
148
+ const root = record(body);
149
+ const flag = (value) => (typeof value === "boolean" ? value : null);
150
+ return { vibe: flag(root?.vibe_payg_enabled), api: flag(root?.payg_enabled) };
151
+ }
152
+
153
+ /**
154
+ * The plan's name from a `/billing/subscription` body, or null.
155
+ *
156
+ * @param {unknown} body
157
+ * @returns {string | null}
158
+ */
159
+ export function parsePlanName(body) {
160
+ const name = stringValue(record(body)?.plan_name);
161
+ if (!name) return null;
162
+ // A display string only: keep it short and free of control characters.
163
+ const clean = name.replace(/[\u0000-\u001f\u007f-\u009f]/g, "").trim().slice(0, 40);
164
+ return clean === "" ? null : clean;
165
+ }
166
+
167
+ /**
168
+ * @param {import("../http.js").HttpResult} response
169
+ * @param {string} what
170
+ * @returns {string}
171
+ */
172
+ function failureMessage(response, what) {
173
+ if (response.status === 401) return "Mistral key rejected (401); run /login mistral in Pi";
174
+ if (response.status === 403) return `Mistral ${what} not readable with this key (403)`;
175
+ if (response.status === 404) return `Mistral billing API not served (404 on ${what})`;
176
+ return `Mistral ${what} request failed: ${response.error ?? `HTTP ${response.status}`}`;
177
+ }
178
+
179
+ /**
180
+ * @param {import("../auth/pi-auth.js").PiCredential} credential
181
+ * @param {{
182
+ * now?: number,
183
+ * fetchFn?: typeof fetch,
184
+ * timeoutMs?: number,
185
+ * expiresInMin?: number | null,
186
+ * }} [options]
187
+ * @returns {Promise<import("../model.js").QuotaResult>}
188
+ */
189
+ export async function fetchQuota(credential, options = {}) {
190
+ const now = options.now ?? Date.now();
191
+ const base = {
192
+ family: "mistral",
193
+ label: "Mistral (Pi)",
194
+ account: accountLabel(credential),
195
+ source: credential.source,
196
+ sourceKind: credential.sourceKind ?? "pi",
197
+ expiresInMin: options.expiresInMin ?? null,
198
+ };
199
+
200
+ if (!credential.key) {
201
+ return degradedResult({ ...base, error: "no key stored for mistral in the Pi store; run /login mistral in Pi", now });
202
+ }
203
+
204
+ const request = (url) =>
205
+ requestJson(url, {
206
+ headers: { Authorization: `Bearer ${credential.key}`, Accept: "application/json" },
207
+ fetchFn: options.fetchFn,
208
+ timeoutMs: options.timeoutMs,
209
+ });
210
+ const [subscription, budget] = await Promise.all([request(SUBSCRIPTION_URL), request(BUDGET_URL)]);
211
+
212
+ const plan = subscription.ok ? parsePlanName(subscription.body) : null;
213
+ const payg = subscription.ok ? parsePayg(subscription.body) : { vibe: null, api: null };
214
+
215
+ // A rejected key is a statement about the credential: report it once, as an
216
+ // auth failure, whichever read noticed it.
217
+ if (subscription.status === 401 || budget.status === 401) {
218
+ return degradedResult({ ...base, plan, error: failureMessage({ status: 401 }, "billing"), now });
219
+ }
220
+
221
+ if (budget.ok) {
222
+ const windows = parseBudgetWindows(budget.body, now, payg);
223
+ if (windows.length === 0) {
224
+ return degradedResult({ ...base, plan, error: "Mistral budget endpoint returned no budgets", now });
225
+ }
226
+ return {
227
+ ...base,
228
+ plan,
229
+ windows,
230
+ error: null,
231
+ ok: true,
232
+ updatedAt: new Date(now).toISOString(),
233
+ };
234
+ }
235
+
236
+ // Without the usage permission the plan is still worth showing: the account
237
+ // works, it just cannot see the organisation's budget.
238
+ if (budget.status === 403 && subscription.ok) {
239
+ return {
240
+ ...base,
241
+ plan,
242
+ windows: [],
243
+ note: `budget needs the see_org_inference_usage permission${payg.vibe === true || payg.api === true ? ` · ${PAYG} on` : ""}`,
244
+ error: null,
245
+ ok: true,
246
+ updatedAt: new Date(now).toISOString(),
247
+ };
248
+ }
249
+
250
+ return degradedResult({ ...base, plan, error: failureMessage(budget, "budget"), now });
251
+ }
package/src/refresh.js CHANGED
@@ -278,7 +278,10 @@ export async function collectWithCadence(options) {
278
278
  : null;
279
279
 
280
280
  const report = mergeReports([cachedPart, fresh], { families, now, reused });
281
- writeCache(report, { path: cachePath, now });
281
+ // The cache carries the same per-family clocks this layer decided on, so a
282
+ // reader that only sees the cache (the CLI, the extension's first frame)
283
+ // judges each family by the time it was actually fetched.
284
+ writeCache(report, { path: cachePath, now, fetchedAtMs });
282
285
  writeRefreshState({ fetchedAtMs }, { statePath });
283
286
 
284
287
  /** @type {Record<string, number>} */
@@ -15,6 +15,7 @@ const FAMILY_SHORT = {
15
15
  codex: "X",
16
16
  antigravity: "A",
17
17
  "opencode-go": "G",
18
+ mistral: "M",
18
19
  "github-actions": "GH",
19
20
  };
20
21
 
@@ -23,6 +24,7 @@ const FAMILY_TITLE = {
23
24
  codex: "Codex (Pi)",
24
25
  antigravity: "Antigravity (Pi)",
25
26
  "opencode-go": "OpenCode Go (Pi)",
27
+ mistral: "Mistral (Pi)",
26
28
  "github-actions": "GitHub Actions",
27
29
  };
28
30
 
@@ -218,6 +220,8 @@ export function renderProviderLines(provider, paint, contentWidth = MAX_WIDTH, o
218
220
  }
219
221
 
220
222
  if ((provider.windows ?? []).length === 0) {
223
+ // A provider that answered but cannot show windows says why in its note.
224
+ if (provider.note) lines.push(` ${paint("warning", `~ ${clip(provider.note, contentWidth - 4)}`)}`);
221
225
  lines.push(` ${paint("dim", "no rate-limit windows reported")}`);
222
226
  return lines;
223
227
  }
@@ -285,6 +289,11 @@ export function renderBoxWidget(providers, paint, totalWidth = typeof process?.s
285
289
  { label: "Agy C/G:", ...windowFor("antigravity", (window) => window.id === "claude-gpt-5h" || (/(claude|gpt|3p)/i.test(window.id) && isFiveHour(window))) },
286
290
  { label: "OP-Go: ", ...windowFor("opencode-go") },
287
291
  ];
292
+ // Mistral joins the compact widget only when it is configured, so a user
293
+ // without it never sees a permanent "not configured" row.
294
+ if (providerFor("mistral") && providerFor("mistral").notConfigured !== true) {
295
+ rows.push({ label: "Mistral:", ...windowFor("mistral", (window) => window.id === "vibe") });
296
+ }
288
297
  if (providerFor("github-actions")) {
289
298
  rows.push({ label: "GH Actions:", ...windowFor("github-actions", (window) => window.id === "monthly") });
290
299
  }