paseo-plugin-account-switcher 0.4.0 → 0.6.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.
@@ -82,7 +82,11 @@ of the NFC-normalized home. `CLAUDE_SECURESTORAGE_CONFIG_DIR` overrides
82
82
  system CLI may have separate settings and credential homes; quota collection
83
83
  uses its effective credential home, including an empty override for the default.
84
84
  There is no global profile search. Only the OAuth usage GET endpoint is requested; no
85
- 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
86
90
  must still match the credential hash used to verify a known account identity.
87
91
  Enterprise seats return every plan window as `null` and report an enabled
88
92
  `extra_usage` monthly spend allowance in minor currency units. It becomes a
@@ -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(); }
@@ -88,3 +88,11 @@ export function parseClaudeUsage(payload: unknown): CollectedUsage {
88
88
  }
89
89
  return { identityKey: null, plan: null, windows };
90
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
+ }
@@ -48,6 +48,8 @@ export const UsageSnapshotSchema = z.object({
48
48
  accountId: z.string(), provider: ProviderSchema,
49
49
  status: z.enum(["ok", "stale", "needs_auth", "unavailable"]),
50
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(),
51
53
  fetchedAt: z.string().nullable(), checkedAt: z.string(), nextRetryAt: z.string().nullable(),
52
54
  error: z.string().nullable(),
53
55
  });