@cad0p/pi-usage 0.0.0-stage → 0.11.2-20261102.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.
Files changed (43) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +519 -2
  3. package/bin/piquota.js +207 -0
  4. package/extensions/quota-panel.ts +1074 -0
  5. package/package.json +59 -4
  6. package/src/auth/claude-code-auth.js +490 -0
  7. package/src/auth/jwt.js +84 -0
  8. package/src/auth/pi-auth.js +424 -0
  9. package/src/browser/cookies.js +557 -0
  10. package/src/browser/history.js +173 -0
  11. package/src/cache.js +235 -0
  12. package/src/cli/args.js +154 -0
  13. package/src/cli/commands/auth.js +216 -0
  14. package/src/cli/commands/gentle-pi.js +44 -0
  15. package/src/cli/commands/omarchy.js +75 -0
  16. package/src/cli/explain.js +99 -0
  17. package/src/cli/output.js +34 -0
  18. package/src/engine.js +426 -0
  19. package/src/exec.js +31 -0
  20. package/src/gentle-pi/rail-patch.js +335 -0
  21. package/src/http.js +182 -0
  22. package/src/model.js +332 -0
  23. package/src/omarchy/assets/antigravity.svg +3 -0
  24. package/src/omarchy/assets/claude.svg +1 -0
  25. package/src/omarchy/assets/codex.svg +1 -0
  26. package/src/omarchy/assets/github-actions.svg +3 -0
  27. package/src/omarchy/assets/opencode-go.svg +3 -0
  28. package/src/omarchy/publish.js +152 -0
  29. package/src/omarchy/record.js +462 -0
  30. package/src/opencode/dashboard.js +337 -0
  31. package/src/opencode/session.js +485 -0
  32. package/src/providers/antigravity-oauth.js +173 -0
  33. package/src/providers/antigravity.js +225 -0
  34. package/src/providers/backoff.js +146 -0
  35. package/src/providers/claude.js +194 -0
  36. package/src/providers/codex.js +151 -0
  37. package/src/providers/error-kind.js +128 -0
  38. package/src/providers/github-actions.js +379 -0
  39. package/src/providers/opencode-go.js +274 -0
  40. package/src/refresh.js +292 -0
  41. package/src/render/panel.js +411 -0
  42. package/src/render/theme.js +102 -0
  43. package/src/sticky.js +319 -0
package/src/engine.js ADDED
@@ -0,0 +1,426 @@
1
+ /**
2
+ * Quota collection engine.
3
+ *
4
+ * Loads Pi credentials (read-only), asks each provider for its windows and
5
+ * returns one normalized report. Providers never throw: a failure becomes a
6
+ * degraded result with an actionable message.
7
+ */
8
+
9
+ import { checkFreshness, LABEL_BY_FAMILY, loadPiCredentials, resolveAuthPaths } from "./auth/pi-auth.js";
10
+ import { loadClaudeCodeCredential } from "./auth/claude-code-auth.js";
11
+ import { degradedResult, displayIdentity, selectPrimaryWindow } from "./model.js";
12
+ import { backoffState, clearBackoff, isAuthFailure, isThrottled, recordBackoff, retryAfterFromError } from "./providers/backoff.js";
13
+ import { fetchQuota as fetchClaude } from "./providers/claude.js";
14
+ import { fetchQuota as fetchCodex } from "./providers/codex.js";
15
+ import { fetchQuota as fetchAntigravity } from "./providers/antigravity.js";
16
+ import { fetchQuota as fetchOpenCodeGo } from "./providers/opencode-go.js";
17
+ import { fetchQuota as fetchGithubActions } from "./providers/github-actions.js";
18
+
19
+ /** Canonical family order used by every surface. */
20
+ export const FAMILIES = ["claude", "codex", "antigravity", "opencode-go", "github-actions"];
21
+
22
+ /**
23
+ * Return the ordered families enabled for a run.
24
+ *
25
+ * GitHub Actions joins a default family list only when the env flag is truthy.
26
+ * A positional family selection sets `explicit` to record user consent directly,
27
+ * independent of whether the requested array has been copied or transformed.
28
+ *
29
+ * @param {{ env?: Record<string, string | undefined>, requested?: string[], explicit?: boolean }} [input]
30
+ * @returns {string[]}
31
+ */
32
+ export function enabledFamilies(input = {}) {
33
+ const env = input.env ?? process.env;
34
+ const requested = input.requested;
35
+ const families = requested ?? FAMILIES;
36
+ const explicit = input.explicit ?? false;
37
+ const includeGithubActions = isTruthyFlag(env.PI_QUOTA_GITHUB_ACTIONS) || explicit;
38
+ return families.filter((family) => family !== "github-actions" || includeGithubActions);
39
+ }
40
+ const GH_CLI_CREDENTIAL = {
41
+ family: "github-actions",
42
+ label: "GitHub Actions",
43
+ source: "gh CLI",
44
+ identity: "GitHub CLI",
45
+ expiresAtMs: null,
46
+ };
47
+
48
+ /** @param {string | undefined} value */
49
+ function isTruthyFlag(value) {
50
+ return typeof value === "string" && /^(1|true|yes|on)$/i.test(value.trim());
51
+ }
52
+
53
+ /**
54
+ * Claude has two possible sources, and a user may have either or both.
55
+ *
56
+ * `auto` prefers the Claude Code CLI, because the plugin that drives it is what a
57
+ * user reaches for when Pi's own `anthropic` token cannot serve requests. The
58
+ * choice is a preference, never a fallback: only the selected source is tried, so
59
+ * a broken preferred source is reported instead of silently masked by the other.
60
+ */
61
+ export const CLAUDE_SOURCE_MODES = ["auto", "claude-code", "pi"];
62
+
63
+ /**
64
+ * @param {unknown} value
65
+ * @returns {"auto" | "claude-code" | "pi"}
66
+ */
67
+ export function normalizeClaudeSourceMode(value) {
68
+ const text = typeof value === "string" ? value.trim().toLowerCase() : "";
69
+ if (text === "claude-code" || text === "claude" || text === "cli") return "claude-code";
70
+ if (text === "pi" || text === "anthropic" || text === "oauth") return "pi";
71
+ return "auto";
72
+ }
73
+
74
+ /**
75
+ * Pick the Claude credential set for this run.
76
+ *
77
+ * @param {{
78
+ * credentials: import("./auth/pi-auth.js").PiCredential[],
79
+ * env: Record<string, string | undefined>,
80
+ * home?: string,
81
+ * platform?: string,
82
+ * usersRoot?: string,
83
+ * claudeCodePaths?: string[] | null,
84
+ * }} input
85
+ * @returns {{ credentials: import("./auth/pi-auth.js").PiCredential[], mode: string, unavailable: string | null, claudeCodePaths: string[] }}
86
+ */
87
+ export function resolveClaudeCredentials(input) {
88
+ const mode = normalizeClaudeSourceMode(input.env.PI_QUOTA_CLAUDE_SOURCE);
89
+ const fromPi = input.credentials.filter((credential) => credential.family === "claude");
90
+ const claudeCodePaths = input.claudeCodePaths === undefined ? undefined : input.claudeCodePaths;
91
+
92
+ if (mode === "pi") return { credentials: fromPi, mode, unavailable: null, claudeCodePaths: claudeCodePaths ?? [], recoveredLock: null };
93
+
94
+ const claudeCode = loadClaudeCodeCredential({
95
+ env: input.env,
96
+ home: input.home,
97
+ platform: input.platform,
98
+ usersRoot: input.usersRoot,
99
+ paths: claudeCodePaths ?? undefined,
100
+ now: input.now,
101
+ });
102
+
103
+ // `auto` prefers the Claude Code CLI only while its token is still usable. A
104
+ // leftover store from an uninstalled CLI never refreshes again, so once it has
105
+ // expired Pi's own login is the better source whenever Pi still has a fresh one.
106
+ if (claudeCode.ok && mode === "auto" && !checkFreshness(claudeCode.credential, input.now ?? Date.now()).fresh) {
107
+ const freshPi = fromPi.filter((credential) => checkFreshness(credential, input.now ?? Date.now()).fresh);
108
+ if (freshPi.length > 0) {
109
+ const expiredMin = Math.abs(checkFreshness(claudeCode.credential, input.now ?? Date.now()).expiresInMin ?? 0);
110
+ return {
111
+ credentials: freshPi,
112
+ mode: "pi",
113
+ unavailable: null,
114
+ // Said out loud so the switch is never silent: the report names the source
115
+ // it used and why the preferred one was passed over.
116
+ notice: `claude: the Claude Code token expired ${expiredMin}m ago; using Pi's anthropic login instead`,
117
+ claudeCodePaths: claudeCode.paths,
118
+ recoveredLock: claudeCode.recoveredLock ?? null,
119
+ };
120
+ }
121
+ }
122
+
123
+ if (claudeCode.ok) {
124
+ return {
125
+ credentials: [claudeCode.credential],
126
+ mode: "claude-code",
127
+ unavailable: null,
128
+ claudeCodePaths: claudeCode.paths,
129
+ recoveredLock: claudeCode.recoveredLock ?? null,
130
+ };
131
+ }
132
+ if (mode === "claude-code") {
133
+ return {
134
+ credentials: [],
135
+ mode,
136
+ unavailable: claudeCode.error,
137
+ claudeCodePaths: claudeCode.paths,
138
+ recoveredLock: claudeCode.recoveredLock ?? null,
139
+ };
140
+ }
141
+ return {
142
+ credentials: fromPi,
143
+ mode: "pi",
144
+ unavailable: null,
145
+ claudeCodePaths: claudeCode.paths,
146
+ recoveredLock: claudeCode.recoveredLock ?? null,
147
+ };
148
+ }
149
+
150
+ /** @type {Record<string, (credential: any, options?: any) => Promise<import("./model.js").QuotaResult>>} */
151
+ const PROVIDERS = {
152
+ claude: fetchClaude,
153
+ codex: fetchCodex,
154
+ antigravity: fetchAntigravity,
155
+ "opencode-go": fetchOpenCodeGo,
156
+ "github-actions": fetchGithubActions,
157
+ };
158
+
159
+ /**
160
+ * @typedef {Object} PiQuotaReport
161
+ * @property {string} engine
162
+ * @property {number} schemaVersion
163
+ * @property {true} readOnly
164
+ * @property {string} generatedAt
165
+ * @property {string[]} sources Pi auth stores that were read.
166
+ * @property {string[]} warnings
167
+ * @property {import("./model.js").QuotaResult[]} providers Flattened, family-ordered.
168
+ * @property {Record<string, import("./model.js").QuotaResult[]>} byFamily
169
+ */
170
+
171
+ /**
172
+ * @param {{
173
+ * families?: string[],
174
+ * explicit?: boolean,
175
+ * env?: Record<string, string | undefined>,
176
+ * home?: string,
177
+ * platform?: string,
178
+ * usersRoot?: string,
179
+ * paths?: string[],
180
+ * now?: number,
181
+ * fetchFn?: typeof fetch,
182
+ * runCommand?: typeof import("./exec.js").runCommand,
183
+ * timeoutMs?: number,
184
+ * refresh?: boolean,
185
+ * force?: boolean,
186
+ * stores?: import("./browser/cookies.js").CookieStore[],
187
+ * allowBrowser?: boolean,
188
+ * claudeCodePaths?: string[] | null,
189
+ * }} [options]
190
+ * @returns {Promise<PiQuotaReport>}
191
+ */
192
+ export async function collectQuota(options = {}) {
193
+ const env = options.env ?? process.env;
194
+ const now = options.now ?? Date.now();
195
+ const families = enabledFamilies({ env, requested: options.families, explicit: options.explicit });
196
+
197
+ const loaded = loadPiCredentials({
198
+ env,
199
+ home: options.home,
200
+ platform: options.platform,
201
+ usersRoot: options.usersRoot,
202
+ paths: options.paths,
203
+ });
204
+
205
+ // Claude is the one family with a second, non-Pi source, so it is resolved
206
+ // before the per-family loop and then treated exactly like any other credential.
207
+ const claude = resolveClaudeCredentials({
208
+ credentials: loaded.credentials,
209
+ env,
210
+ home: options.home,
211
+ platform: options.platform,
212
+ usersRoot: options.usersRoot,
213
+ claudeCodePaths: options.claudeCodePaths,
214
+ now,
215
+ });
216
+
217
+ /**
218
+ * @param {string} family
219
+ * @returns {import("./auth/pi-auth.js").PiCredential[]}
220
+ */
221
+ const credentialsFor = (family) => {
222
+ if (family === "claude") return claude.credentials;
223
+ if (family === "github-actions") return [GH_CLI_CREDENTIAL];
224
+ return loaded.credentials.filter((credential) => credential.family === family);
225
+ };
226
+
227
+ /** @type {Record<string, import("./model.js").QuotaResult[]>} */
228
+ const byFamily = {};
229
+ /** @type {string[]} */
230
+ const warnings = [...loaded.warnings];
231
+ if (claude.notice) warnings.push(claude.notice);
232
+ if (claude.recoveredLock) {
233
+ warnings.push(
234
+ `claude: removed abandoned OAuth refresh lock (${Math.round((claude.recoveredLock.ageMs ?? 0) / 1000)}s old) at ${claude.recoveredLock.lockPath}`,
235
+ );
236
+ }
237
+ /** @type {Record<string, string[]>} */
238
+ const familyWarnings = {};
239
+
240
+ const hasOpenAi = loaded.rawProviders?.includes("openai") || Boolean(env.OPENAI_API_KEY);
241
+
242
+ await Promise.all(
243
+ families.map(async (family) => {
244
+ const credentials = credentialsFor(family);
245
+ if (credentials.length === 0) {
246
+ // `notConfigured` is stated rather than inferred: the message now names a
247
+ // second source, and every renderer keys off this flag to avoid painting a
248
+ // failure icon for a provider the user simply does not use.
249
+ byFamily[family] = [
250
+ degradedResult({
251
+ family,
252
+ label: LABEL_BY_FAMILY[family] ?? family,
253
+ error: claude.unavailable && family === "claude" ? claude.unavailable : missingCredentialMessage(family, { hasOpenAi }),
254
+ notConfigured: true,
255
+ source: loaded.paths[0] ?? resolveAuthPaths({ env, home: options.home })[0] ?? "~/.pi/agent/auth.json",
256
+ now,
257
+ }),
258
+ ];
259
+ return;
260
+ }
261
+
262
+ // A family that is currently throttled is skipped entirely, so the
263
+ // caller's sticky layer can republish the previous good snapshot instead
264
+ // of adding more pressure to a rate-limited endpoint.
265
+ //
266
+ // Authentication failures supersede throttling: if any credential for this
267
+ // family is already known to be expired, waiting out a rate limit is useless
268
+ // and misleading. We clear backoff immediately so the auth failure surfaces.
269
+ const hasExpiredToken = credentials.some((credential) => {
270
+ const freshness = checkFreshness(credential, now);
271
+ return !freshness.fresh;
272
+ });
273
+ if (hasExpiredToken || options.force) {
274
+ clearBackoff(family, { env, home: options.home });
275
+ }
276
+
277
+ const throttle = backoffState(family, { now, env, home: options.home });
278
+ if (throttle.active && !options.force) {
279
+ byFamily[family] = [
280
+ degradedResult({
281
+ family,
282
+ label: LABEL_BY_FAMILY[family] ?? family,
283
+ // Keep the identity visible while paused: "unknown" on screen is
284
+ // worse than a stale-but-labelled account.
285
+ account: displayIdentity(credentials[0]),
286
+ error: `backing off after a throttle: next attempt in ${throttle.secondsLeft}s`,
287
+ source: credentials[0].source,
288
+ now,
289
+ }),
290
+ ];
291
+ return;
292
+ }
293
+
294
+ /** @type {import("./model.js").QuotaResult[]} */
295
+ const results = [];
296
+ const familyWarnList = [];
297
+ for (const credential of credentials) {
298
+ const freshness = checkFreshness(credential, now);
299
+ if (!freshness.fresh) {
300
+ familyWarnList.push(
301
+ `${family}: the ${expiredTokenName(credential)} expired ${Math.abs(freshness.expiresInMin ?? 0)}m ago; ${refreshHint(credential)}`,
302
+ );
303
+ }
304
+ const fetchQuota = PROVIDERS[family];
305
+ try {
306
+ const result = await fetchQuota(credential, {
307
+ now,
308
+ fetchFn: options.fetchFn,
309
+ runCommand: options.runCommand,
310
+ timeoutMs: options.timeoutMs,
311
+ expiresInMin: freshness.expiresInMin,
312
+ env,
313
+ home: options.home,
314
+ refresh: options.refresh,
315
+ stores: options.stores,
316
+ allowBrowser: options.allowBrowser,
317
+ });
318
+ // The renderers group siblings by family; the record builder needs the
319
+ // slot to label each account without re-parsing its display string.
320
+ result.slot = credential.slot ?? null;
321
+ if (isThrottled(result.error)) {
322
+ const seconds = recordBackoff(family, {
323
+ retryAfterSec: retryAfterFromError(result.error),
324
+ now,
325
+ env,
326
+ home: options.home,
327
+ }).seconds;
328
+ familyWarnList.push(`${family}: throttled upstream; pausing that family for ${seconds}s`);
329
+ } else if (result.ok || isAuthFailure(result.error)) {
330
+ clearBackoff(family, { env, home: options.home });
331
+ }
332
+ results.push(result);
333
+ } catch (error) {
334
+ // A provider must never take the whole report down.
335
+ const crashed = degradedResult({
336
+ family,
337
+ label: credential.label,
338
+ account: credential.email ?? credential.accountId ?? "unknown",
339
+ error: `provider crashed: ${/** @type {{ message?: string }} */ (error)?.message ?? String(error)}`,
340
+ source: credential.source,
341
+ now,
342
+ expiresInMin: freshness.expiresInMin,
343
+ });
344
+ crashed.slot = credential.slot ?? null;
345
+ results.push(crashed);
346
+ }
347
+ }
348
+ byFamily[family] = results;
349
+ familyWarnings[family] = familyWarnList;
350
+ }),
351
+ );
352
+
353
+ for (const family of families) {
354
+ if (familyWarnings[family]) {
355
+ warnings.push(...familyWarnings[family]);
356
+ }
357
+ }
358
+
359
+ const providers = families.flatMap((family) => byFamily[family] ?? []);
360
+
361
+ // Stamp the primary window so the terminal, the Pi TUI and the Moshi adapter
362
+ // all agree on which window represents a provider, with no duplicated rules.
363
+ for (const provider of providers) {
364
+ provider.primaryWindowId = selectPrimaryWindow(provider.windows ?? [])?.id ?? null;
365
+ }
366
+
367
+ return {
368
+ engine: "pi-quota",
369
+ schemaVersion: 1,
370
+ readOnly: true,
371
+ generatedAt: new Date(now).toISOString(),
372
+ sources: loaded.paths,
373
+ // Named so `piquota --explain` can state which Claude source was chosen and
374
+ // every surface agrees, instead of each one guessing.
375
+ claudeSource: { mode: claude.mode, paths: claude.claudeCodePaths, unavailable: claude.unavailable },
376
+ warnings,
377
+ providers,
378
+ byFamily,
379
+ };
380
+ }
381
+
382
+ /**
383
+ * @param {string} family
384
+ * @param {{ hasOpenAi?: boolean }} [context]
385
+ * @returns {string}
386
+ */
387
+ function missingCredentialMessage(family, context = {}) {
388
+ if (family === "claude") {
389
+ return "no claude credential in the Pi store or from the Claude Code CLI";
390
+ }
391
+ if (family === "github-actions") {
392
+ return "GitHub Actions uses the authenticated gh CLI; no Pi-store credential is required";
393
+ }
394
+ if (family === "codex" && context.hasOpenAi) {
395
+ return "no codex credential in the Pi store (found 'openai' API; run /login openai-codex in Pi for subscription quota)";
396
+ }
397
+ return `no ${family} credential in the Pi store`;
398
+ }
399
+
400
+ /**
401
+ * @param {{ sourceKind?: string }} credential
402
+ * @returns {string}
403
+ */
404
+ function expiredTokenName(credential) {
405
+ return credential.sourceKind === "claude-code" ? "Claude Code token" : "Pi token";
406
+ }
407
+
408
+ /**
409
+ * @param {{ sourceKind?: string }} credential
410
+ * @returns {string}
411
+ */
412
+ function refreshHint(credential) {
413
+ return credential.sourceKind === "claude-code"
414
+ ? "run `claude` once to refresh it"
415
+ : "use that provider in Pi to refresh it";
416
+ }
417
+
418
+ /**
419
+ * Convenience accessor used by the renderers.
420
+ *
421
+ * @param {PiQuotaReport} report
422
+ * @returns {import("./model.js").QuotaResult | null}
423
+ */
424
+ export function firstForFamily(report, family) {
425
+ return report.byFamily[family]?.[0] ?? null;
426
+ }
package/src/exec.js ADDED
@@ -0,0 +1,31 @@
1
+ /**
2
+ * The one place that spawns foreign binaries.
3
+ *
4
+ * piQuota delegates GitHub API requests to the user's authenticated `gh` CLI.
5
+ * Callers must degrade on missing binaries, non-zero exits and timeouts;
6
+ * external commands must never make quota collection throw.
7
+ */
8
+
9
+ import { spawnSync } from "node:child_process";
10
+
11
+ export const DEFAULT_TIMEOUT_MS = 15_000;
12
+
13
+ /**
14
+ * @param {string} command
15
+ * @param {string[]} [args]
16
+ * @param {{ timeoutMs?: number, env?: Record<string, string | undefined> }} [options]
17
+ * @returns {{ status: number | null, stdout: string, stderr: string, error: string | null }}
18
+ */
19
+ export function runCommand(command, args = [], options = {}) {
20
+ const result = spawnSync(command, args, {
21
+ encoding: "utf-8",
22
+ timeout: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
23
+ env: options.env ?? process.env,
24
+ });
25
+ return {
26
+ status: typeof result.status === "number" ? result.status : null,
27
+ stdout: typeof result.stdout === "string" ? result.stdout : "",
28
+ stderr: typeof result.stderr === "string" ? result.stderr : "",
29
+ error: result.error ? result.error.message : null,
30
+ };
31
+ }