paseo-plugin-account-switcher 0.3.4 → 0.5.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.
@@ -66,6 +66,9 @@ OAuth credentials; this module performs no custom refresh or forced refresh. The
66
66
  quota response account ID is checked against a known profile identity. If an older
67
67
  response omits that ID and credentials rotated during the call, it cannot replace
68
68
  the previous snapshot. The process is terminated on success, failure or cancellation.
69
+ Usage-based workspace plans (for example `enterprise_cbp_usage_based`) report no
70
+ `primary` or `secondary` window; their bucket's `individualLimit` monthly credit
71
+ allowance becomes a window with `usedPercent = 100 - remainingPercent`.
69
72
 
70
73
  **Claude:** on macOS the exact Keychain service/account is preferred. A missing
71
74
  or inaccessible item falls back only to `.credentials.json` in the supplied home,
@@ -79,8 +82,16 @@ of the NFC-normalized home. `CLAUDE_SECURESTORAGE_CONFIG_DIR` overrides
79
82
  system CLI may have separate settings and credential homes; quota collection
80
83
  uses its effective credential home, including an empty override for the default.
81
84
  There is no global profile search. Only the OAuth usage GET endpoint is requested; no
82
- token refresh or inference request is sent. Before HTTP, the actual selected token
85
+ token refresh or inference request is sent by this module. An access token that
86
+ expires within a minute, with a refresh token present, is handed to the official
87
+ CLI first: `renewExpiredClaudeToken` runs `claude -p /usage --no-session-persistence`
88
+ under the account, a local command with no model turn and no saved session. The
89
+ controller calls it before identity verification, at most every 10 minutes per account. Before HTTP, the actual selected token
83
90
  must still match the credential hash used to verify a known account identity.
91
+ Enterprise seats return every plan window as `null` and report an enabled
92
+ `extra_usage` monthly spend allowance in minor currency units. It becomes a
93
+ "Monthly spend" window from `utilization`; when no plan window has a value, the
94
+ empty plan windows are dropped.
84
95
 
85
96
  Tests use synthetic credentials and a synthetic stdio CLI. They establish local
86
97
  protocol, parsing, isolation, scheduling and cache behavior. They do not establish
@@ -1,8 +1,8 @@
1
1
  import { createHash } from "node:crypto";
2
- import { execFile } from "node:child_process";
2
+ import { execFile, spawn } from "node:child_process";
3
3
  import { readFile } from "node:fs/promises";
4
4
  import { join } from "node:path";
5
- import { homedir } from "node:os";
5
+ import { homedir, tmpdir } from "node:os";
6
6
  import { UsageError, type CollectedUsage, type QuotaAccount } from "./index";
7
7
  import { object, parseClaudeUsage, string } from "./parsers";
8
8
  import { credentialHash } from "./credential-hash";
@@ -14,7 +14,10 @@ export type ClaudeDependencies = {
14
14
  readKeychain?: (target: KeychainTarget, signal?: AbortSignal) => Promise<string | null>;
15
15
  fetch?: (url: string, init: RequestInit) => Promise<Response>;
16
16
  now?: () => number;
17
+ run?: (command: string[], env: NodeJS.ProcessEnv) => Promise<void>;
17
18
  };
19
+ // The usage request must not race a token that expires while it is in flight.
20
+ const RENEWAL_MARGIN = 60_000;
18
21
  export function claudeKeychainTarget(account: QuotaAccount): KeychainTarget {
19
22
  const custom = account.env.CLAUDE_SECURESTORAGE_CONFIG_DIR ?? account.env.CLAUDE_CONFIG_DIR;
20
23
  // Verified against Claude Code 2.1.263's embedded secure-storage implementation.
@@ -52,6 +55,27 @@ function keychain(target: KeychainTarget, signal?: AbortSignal): Promise<string
52
55
  });
53
56
  });
54
57
  }
58
+ /** Lets the official CLI renew an expired access token; the plugin never refreshes tokens itself.
59
+ * Returns whether a renewal was attempted. A failed renewal leaves the usage request to report sign-in. */
60
+ export async function renewExpiredClaudeToken(account: QuotaAccount, dependencies: ClaudeDependencies = {}): Promise<boolean> {
61
+ let oauth: Record<string, unknown> | null;
62
+ try {oauth = object(object(JSON.parse((await readClaudeCredentials(account, dependencies)).raw))?.claudeAiOauth);}
63
+ catch {return false;}
64
+ const expiresAt = oauth?.expiresAt;
65
+ if (typeof expiresAt !== "number" || !string(oauth?.refreshToken)) return false;
66
+ if (expiresAt - RENEWAL_MARGIN > (dependencies.now ?? Date.now)()) return false;
67
+ // `/usage` is a local command: it renews the token without a model turn, and nothing is saved to history.
68
+ await (dependencies.run ?? runCli)([...account.command, "-p", "/usage", "--no-session-persistence"], account.env).catch(() => {});
69
+ return true;
70
+ }
71
+ function runCli(command: string[], env: NodeJS.ProcessEnv): Promise<void> {
72
+ return new Promise((resolve, reject) => {
73
+ // Closed stdin: print mode otherwise waits for piped input.
74
+ const child = spawn(command[0], command.slice(1), { env, cwd: tmpdir(), stdio: "ignore", timeout: 60_000, windowsHide: true });
75
+ child.once("error", reject);
76
+ child.once("exit", code => code === 0 ? resolve() : reject(new Error(`exit ${code}`)));
77
+ });
78
+ }
55
79
  export function retryAfter(value: string | null, now: number): number | undefined {
56
80
  if (!value) return undefined;
57
81
  const seconds = Number(value);
@@ -1,6 +1,6 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { UsageError, type CollectedUsage, type QuotaAccount } from "./index";
3
- import { object, parseCodexUsage, string } from "./parsers";
3
+ import { object, parseCodexModels, parseCodexUsage, string } from "./parsers";
4
4
 
5
5
  /** A short-lived native app-server session. No thread, prompt, login or forced refresh. */
6
6
  export async function collectCodexUsage(account: QuotaAccount, signal?: AbortSignal): Promise<CollectedUsage> {
@@ -48,6 +48,18 @@ export async function collectCodexUsage(account: QuotaAccount, signal?: AbortSig
48
48
  const id = ++sequence;
49
49
  return new Promise((resolve, reject) => { pending.set(id,{resolve,reject}); child.stdin.write(`${JSON.stringify({id,method,params})}\n`); });
50
50
  }
51
+ // Plans differ in the models they offer; switching an agent to a plan without its model fails the next turn.
52
+ async function listModels(): Promise<string[] | null> {
53
+ const models: string[] = [];
54
+ let cursor: string | null = null;
55
+ for (let page = 0; page < 10; page++) {
56
+ const parsed = parseCodexModels(await request("model/list", cursor ? {cursor} : {}));
57
+ if (!parsed) return null;
58
+ models.push(...parsed.models);
59
+ if (!(cursor = parsed.nextCursor)) return models;
60
+ }
61
+ return null;
62
+ }
51
63
  try {
52
64
  if (signal?.aborted) throw new UsageError("unavailable", "cancelled");
53
65
  await request("initialize", {clientInfo:{name:"paseo_account_switcher",version:"0.1.0"}});
@@ -59,7 +71,7 @@ export async function collectCodexUsage(account: QuotaAccount, signal?: AbortSig
59
71
  const usage = parseCodexUsage(await request("account/rateLimits/read", {}));
60
72
  if (account.identityKey && usage.identityKey && account.identityKey !== usage.identityKey) throw new UsageError("needs_auth", "identity_changed");
61
73
  if (!usage.windows.length) throw new UsageError("unavailable", "invalid_payload");
62
- return {...usage, plan:usage.plan ?? string(signedIn.planType)};
74
+ return {...usage, plan:usage.plan ?? string(signedIn.planType), models:await listModels().catch(() => null)};
63
75
  } catch (error) {
64
76
  if (error instanceof UsageError) throw error;
65
77
  throw new UsageError("unavailable", "cli_failed");
@@ -8,7 +8,7 @@ import { object } from "./parsers";
8
8
 
9
9
  export type QuotaAccount = { id: string; provider: Provider; home: string; command: string[]; env: NodeJS.ProcessEnv; identityKey: string | null; generation: number; credentialVersion?: string; identityCredentialVersion?: string; requireIdentityVerification?: boolean };
10
10
  export { readCredentialVersion } from "./credentials";
11
- export type CollectedUsage = { identityKey: string | null; plan: string | null; windows: UsageWindow[] };
11
+ export type CollectedUsage = { identityKey: string | null; plan: string | null; windows: UsageWindow[]; models?: string[] | null };
12
12
  export type FetchUsage = (account: QuotaAccount, signal?: AbortSignal) => Promise<CollectedUsage>;
13
13
  export type AccountReadOptions = { verifyAccountId?: string };
14
14
  export type UsageOptions = { getAccounts: (input?: AccountReadOptions) => Promise<QuotaAccount[]>; fetchUsage?: FetchUsage; cachePath?: string; now?: () => number };
@@ -161,7 +161,7 @@ export function createUsageService(options: UsageOptions) {
161
161
  if(requested&&account.credentialVersion!==verified.credentialVersion&&(!identityProven(account)||!identityProven(verified)||result?.identityKey!==account.identityKey))failure??=new UsageError("unavailable","response_identity_unverified");
162
162
  const checkedAt = new Date(now()).toISOString();
163
163
  if (result && !failure) {
164
- const snapshot: UsageSnapshot = {accountId:account.id,provider:account.provider,status:"ok",plan:result.plan,windows:result.windows,fetchedAt:checkedAt,checkedAt,nextRetryAt:null,error:null};
164
+ const snapshot: UsageSnapshot = {accountId:account.id,provider:account.provider,status:"ok",plan:result.plan,windows:result.windows,models:result.models??null,fetchedAt:checkedAt,checkedAt,nextRetryAt:null,error:null};
165
165
  entry.snapshot=snapshot;entry.success=account.identityKey===null?undefined:snapshot;entry.attempts=0;entry.retryAt=0;
166
166
  } else {
167
167
  const error=failure??new UsageError("unavailable","request_failed");
@@ -170,7 +170,7 @@ export function createUsageService(options: UsageOptions) {
170
170
  entry.retryAt=now()+backoff;
171
171
  if (error.status==="needs_auth") entry.success=undefined;
172
172
  const previous=entry.success;
173
- entry.snapshot={accountId:account.id,provider:account.provider,status:error.status==="needs_auth"?"needs_auth":previous?"stale":"unavailable",plan:previous?.plan??null,windows:previous?.windows??[],fetchedAt:previous?.fetchedAt??null,checkedAt,nextRetryAt:new Date(entry.retryAt).toISOString(),error:error.message};
173
+ entry.snapshot={accountId:account.id,provider:account.provider,status:error.status==="needs_auth"?"needs_auth":previous?"stale":"unavailable",plan:previous?.plan??null,windows:previous?.windows??[],models:previous?.models??null,fetchedAt:previous?.fetchedAt??null,checkedAt,nextRetryAt:new Date(entry.retryAt).toISOString(),error:error.message};
174
174
  }
175
175
  await persist();
176
176
  } finally { release(); }
@@ -11,6 +11,11 @@ function date(value: unknown, seconds = false): string | null {
11
11
  const time = seconds ? (value as number) * 1000 : Date.parse(value as string);
12
12
  return Number.isFinite(time) && Math.abs(time) <= 8.64e15 ? new Date(time).toISOString() : null;
13
13
  }
14
+ function amount(value: unknown): number | null {
15
+ const parsed = typeof value === "string" && value.trim() ? Number(value) : NaN;
16
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : null;
17
+ }
18
+ const credits = (value: number) => Math.round(value).toLocaleString("en-US");
14
19
  function durationLabel(minutes: number | null, fallback: string): string {
15
20
  if (minutes === null) return fallback;
16
21
  if (minutes % 1440 === 0) return `${minutes / 1440} days`;
@@ -34,6 +39,15 @@ export function parseCodexUsage(payload: unknown): CollectedUsage {
34
39
  const duration = numeric(window.windowDurationMins);
35
40
  windows.push({ id: `${id}:${key}`, label: `${string(bucket.limitName) ?? id} · ${durationLabel(duration, key)}`, usedPercent: numeric(window.usedPercent), windowDurationMins: duration, resetsAt: date(window.resetsAt, true) });
36
41
  }
42
+ // Usage-based workspaces (e.g. enterprise_cbp_usage_based) report a monthly credit allowance instead of windows.
43
+ const spend = object(bucket.individualLimit);
44
+ const remaining = numeric(spend?.remainingPercent);
45
+ if (spend && remaining !== null) {
46
+ const limit = amount(spend.limit);
47
+ const used = amount(spend.used);
48
+ windows.push({ id: `${id}:individual`, label: `${string(bucket.limitName) ?? id} · monthly credits`, usedPercent: 100 - Math.min(100, remaining), windowDurationMins: null, resetsAt: date(spend.resetsAt, true),
49
+ detail: limit !== null && used !== null ? `${credits(Math.max(0, limit - used))} of ${credits(limit)} credits left` : null });
50
+ }
37
51
  }
38
52
  return { identityKey: string(root.accountId), plan, windows };
39
53
  }
@@ -59,5 +73,26 @@ export function parseClaudeUsage(payload: unknown): CollectedUsage {
59
73
  if (!labels.length) continue;
60
74
  windows.push({ id: `weekly_scoped:${index}`, label: `Weekly · ${labels.join(" · ")}`, usedPercent: numeric(row.percent), windowDurationMins: 10080, resetsAt: date(row.resets_at) });
61
75
  }
76
+ // Enterprise seats report a monthly spend allowance; amounts are in minor units of `currency`.
77
+ const extra = object(root.extra_usage);
78
+ const limit = numeric(extra?.monthly_limit);
79
+ const used = numeric(extra?.used_credits);
80
+ if (extra?.is_enabled === true && limit) {
81
+ const scale = 10 ** (numeric(extra.decimal_places) ?? 2);
82
+ const currency = string(extra.currency) ?? "USD";
83
+ const money = (value: number) => { try { return (value / scale).toLocaleString("en-US", { style: "currency", currency }); } catch { return `${(value / scale).toFixed(2)} ${currency}`; } };
84
+ const spend: UsageWindow = { id: "extra_usage", label: "Monthly spend", usedPercent: numeric(extra.utilization) ?? (used === null ? null : used / limit * 100), windowDurationMins: null, resetsAt: null,
85
+ detail: used === null ? null : `${money(Math.max(0, limit - used))} of ${money(limit)} left` };
86
+ // Without any plan limits the empty plan rows are noise; the spend allowance is the only quota.
87
+ return { identityKey: null, plan: null, windows: windows.some((quota) => quota.usedPercent !== null) ? [...windows, spend] : [spend] };
88
+ }
62
89
  return { identityKey: null, plan: null, windows };
63
90
  }
91
+ /** One `model/list` page: the model IDs the account's plan offers, or null when the page is unreadable. */
92
+ export function parseCodexModels(payload: unknown): { models: string[]; nextCursor: string | null } | null {
93
+ const page = object(payload);
94
+ if (!Array.isArray(page?.data)) return null;
95
+ const models = page.data.map(entry => string(object(entry)?.model));
96
+ if (models.some(model => model === null)) return null;
97
+ return { models: models as string[], nextCursor: string(page.nextCursor) };
98
+ }
@@ -40,12 +40,16 @@ export type AccountState = z.infer<typeof StateSchema>;
40
40
  export const UsageWindowSchema = z.object({
41
41
  id: z.string(), label: z.string(), usedPercent: z.number().nullable(),
42
42
  windowDurationMins: z.number().nullable(), resetsAt: z.string().nullable(),
43
+ // Provider-reported amounts behind the percentage, such as "3,765 of 5,000 credits left".
44
+ detail: z.string().nullable().optional(),
43
45
  });
44
46
  export type UsageWindow = z.infer<typeof UsageWindowSchema>;
45
47
  export const UsageSnapshotSchema = z.object({
46
48
  accountId: z.string(), provider: ProviderSchema,
47
49
  status: z.enum(["ok", "stale", "needs_auth", "unavailable"]),
48
50
  plan: z.string().nullable(), windows: z.array(UsageWindowSchema),
51
+ // Model IDs the account's plan offers; null or absent when the provider does not list them.
52
+ models: z.array(z.string()).nullable().optional(),
49
53
  fetchedAt: z.string().nullable(), checkedAt: z.string(), nextRetryAt: z.string().nullable(),
50
54
  error: z.string().nullable(),
51
55
  });