paseo-plugin-account-switcher 0.2.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.
@@ -0,0 +1,79 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { readFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { BindingSchema, type Binding, type Provider } from "../shared/contracts";
5
+ import { AccountStore, accountFrom, type StoredBinding } from "./store";
6
+
7
+ export interface SwitchDependencies {
8
+ store:AccountStore;
9
+ inspect:(agentId:string)=>Promise<{provider:string;busy:boolean;archived:boolean}>;
10
+ checkAccount:(accountId:string)=>Promise<{authStatus:string}>;
11
+ reload:(agentId:string)=>Promise<void>;
12
+ applying?:Set<string>;
13
+ }
14
+ export class SwitchService {
15
+ private applying:Set<string>;
16
+ constructor(private readonly deps:SwitchDependencies){this.applying=deps.applying??new Set();}
17
+ async prepare(agentId:string,accountId:string|null):Promise<Binding>{
18
+ if(this.applying.has(agentId))throw new Error("An account switch is already in progress.");
19
+ const agent=await this.deps.inspect(agentId);
20
+ if(agent.archived)throw new Error("The agent is archived.");
21
+ if(agent.provider!=="claude"&&agent.provider!=="codex")throw new Error("Only Claude and Codex are supported.");
22
+ return BindingSchema.parse(await this.deps.store.prepare(agentId,agent.provider,accountId));
23
+ }
24
+ async apply(agentId:string):Promise<Binding>{
25
+ if(this.applying.has(agentId))throw new Error("An account switch is already in progress.");
26
+ this.applying.add(agentId);
27
+ let previous:StoredBinding|undefined;
28
+ const token=randomUUID();
29
+ try {
30
+ const {store}=this.deps, state=await store.read();
31
+ if(!state.integration.enabled)throw new Error("Enable account integration first.");
32
+ const selected=state.bindings.find(b=>b.agentId===agentId);
33
+ if(!selected?.pendingAccountId)throw new Error("Select an account first.");
34
+ const target=accountFrom(state,selected.pendingAccountId);
35
+ if(target.loginToken)throw new Error("Finish signing in to the selected account first.");
36
+ const assertIdle=async()=>{const agent=await this.deps.inspect(agentId);if(agent.archived)throw new Error("The agent is archived.");if(agent.provider!==target.provider)throw new Error("The agent provider changed.");if(agent.busy)throw new Error("Wait for the agent to finish its response.");};
37
+ await assertIdle();
38
+ if((await this.deps.checkAccount(target.id)).authStatus!=="ready")throw new Error("Sign in to the selected account first.");
39
+ await assertIdle();
40
+ previous=await store.change(r=>{const b=r.bindings.find(b=>b.agentId===agentId);if(!r.integration.enabled||!b||b.pendingAccountId!==target.id||b.status==="switching")throw new Error("The account selection changed; try again.");if(accountFrom(r,target.id).loginToken)throw new Error("Account sign-in is still in progress.");const old=structuredClone(b);b.status="switching";b.error=null;b.launchAccountId=target.id;b.launchToken=token;return old;});
41
+ await this.deps.reload(agentId);
42
+ const receipt=JSON.parse(await readFile(join(store.root,"receipts",encodeURIComponent(agentId)+".json"),"utf8"));
43
+ if(receipt.accountId!==target.id||receipt.launchToken!==token)throw new Error("The new account did not confirm its launch.");
44
+ return await store.change(r=>{const b=r.bindings.find(b=>b.agentId===agentId);if(!r.integration.enabled||!b||b.launchToken!==token)throw new Error("The account switch state changed.");b.currentAccountId=target.id;b.pendingAccountId=null;b.status="ready";b.error=null;b.launchToken=null;b.registrationObserved=true;return BindingSchema.parse(b);});
45
+ } catch(error) {
46
+ if(previous){
47
+ const rollback=previous,rollbackToken=randomUUID();
48
+ const claimed=await this.deps.store.change(r=>{const b=r.bindings.find(b=>b.agentId===agentId);if(b?.launchToken!==token)return false;b.currentAccountId=null;b.launchAccountId=rollback.currentAccountId??b.launchAccountId;b.launchToken=rollbackToken;b.status="switching";return true;});
49
+ if(!claimed)throw error;
50
+ let restored=false;
51
+ if(rollback.currentAccountId){
52
+ try{
53
+ const agent=await this.deps.inspect(agentId);if(agent.busy||agent.archived)throw new Error("Agent is busy");
54
+ await this.deps.reload(agentId);
55
+ const receipt=JSON.parse(await readFile(join(this.deps.store.root,"receipts",encodeURIComponent(agentId)+".json"),"utf8"));
56
+ restored=receipt.accountId===rollback.currentAccountId&&receipt.launchToken===rollbackToken;
57
+ }catch{/* Keep the account unknown unless rollback launch is confirmed. */}
58
+ }
59
+ await this.deps.store.change(r=>{const b=r.bindings.find(b=>b.agentId===agentId);if(b?.launchToken===rollbackToken){b.currentAccountId=restored?rollback.currentAccountId:null;b.pendingAccountId=rollback.pendingAccountId;b.status="error";b.launchToken=null;b.error=restored?"The account switch failed. The previous account was restored.":"Account not confirmed for the running session. Select an account and apply it again.";}});
60
+ }
61
+ throw error;
62
+ } finally {this.applying.delete(agentId);}
63
+ }
64
+ async bindNewAgent(agentId:string,provider:Provider):Promise<void>{
65
+ const state=await this.deps.store.read();
66
+ if(!state.integration.enabled||state.bindings.some(b=>b.agentId===agentId))return;
67
+ const selected=state.defaults[provider];if(!selected)return;
68
+ const account=accountFrom(state,selected);
69
+ if(account.provider!==provider)throw new Error("The default account belongs to another provider.");
70
+ if(account.loginToken)throw new Error("Default account sign-in is still in progress.");
71
+ if((await this.deps.checkAccount(selected)).authStatus!=="ready")throw new Error("The default account requires authentication. Sign in or select another default account.");
72
+ await this.deps.store.change(r=>{
73
+ if(!r.integration.enabled||r.bindings.some(b=>b.agentId===agentId))return;
74
+ const accountId=r.defaults[provider];if(accountId!==selected)throw new Error("The default account changed; create the agent again.");
75
+ if(accountFrom(r,accountId).loginToken)throw new Error("Default account sign-in is still in progress.");
76
+ r.bindings.push({agentId,provider,currentAccountId:null,pendingAccountId:null,launchAccountId:accountId,launchToken:randomUUID(),status:"ready",error:null,registrationObserved:false});
77
+ });
78
+ }
79
+ }
@@ -0,0 +1,89 @@
1
+ # Account quota monitoring
2
+
3
+ `createUsageService({ getAccounts, fetchUsage?, cachePath?, now? })` reads quota
4
+ windows for every configured account. `getAccounts` supplies the real provider CLI
5
+ command, isolated home, exact environment, identity key and an authentication
6
+ generation. Normal `getAccounts()` calls read stored metadata only: they must not
7
+ start a provider CLI or read Keychain credentials. The scheduler calls
8
+ `getAccounts({ verifyAccountId })` for one account immediately before and after an
9
+ actual quota request. Expensive checks therefore follow the quota cadence; idle
10
+ five-second timer ticks and UI list calls do not spawn credential readers.
11
+
12
+ For known identities the controller sets `requireIdentityVerification: true`.
13
+ Its targeted check reads the credential hash, probes the official CLI, then reads
14
+ the hash again. Only a successful identity probe between equal `present:` hashes
15
+ sets `identityCredentialVersion`. A changing hash gets one bounded retry; failed
16
+ or unstable probes supply no proof. The scheduler compares this proof with
17
+ `credentialVersion`, so previously stored identity metadata cannot establish that
18
+ replacement credentials belong to the same account. Existing account probes are
19
+ drained before the targeted verification begins.
20
+
21
+ `readCredentialVersion(account)` returns only `present:<sha256>`, `absent`, or
22
+ `unavailable`. Preserve the prior version on `unavailable`, but revoke its proof:
23
+ inaccessible storage does not establish a signed-out account. Credential reads
24
+ use only the selected profile, including the exact Claude Keychain item.
25
+ Codex identity keys are ChatGPT `account_id` values; Claude identities
26
+ are supplied by the profile owner because its usage response has no account ID.
27
+
28
+ - Call `start()` once. Polling begins immediately, then runs every five minutes.
29
+ - `list({ visible: true })` extends a 90-second visible lease; during that lease
30
+ polling runs every 60 seconds. Listing returns available cached data immediately.
31
+ - `refresh(accountId?)` requests one or all accounts. Provider backoff also applies
32
+ to manual refresh and is checked before expensive verification. There are at
33
+ most two account workflows in flight and one per account; each slot includes
34
+ the before-probe, quota request and after-probe.
35
+ - `invalidate(accountId)` clears saved identity data and cancels its current read.
36
+ `close()` stops polling, cancels collectors and waits for pending cache writes.
37
+ - A successful response retains every reported quota window. Temporary failures
38
+ preserve the last successful snapshot as `stale`. Missing authentication clears
39
+ old data. A passed reset timestamp never invents a new quota value.
40
+ A reported reset triggers one new read (within five seconds), respecting backoff.
41
+ - HTTP 429 respects `Retry-After`; otherwise repeated errors back off from one
42
+ minute to at most 30 minutes. HTTP 401 needs authentication; 403 is unavailable.
43
+ - Credential rotation preserves last-success data and retry deadlines only when
44
+ both credential versions are proven to belong to the same identity. A native
45
+ successful response survives such rotation when its identity is bound to the
46
+ request. Unproven replacement credentials clear old quota data. A new account
47
+ identity or generation always invalidates the previous response.
48
+ - With `cachePath`, only last-success snapshots and identity fingerprints are saved
49
+ using atomic replacement with mode `0600`. Restored data is marked stale. Tokens,
50
+ environment variables, raw commands and provider error bodies are never cached.
51
+ After controller restart, the cache remains hidden and staged until targeted
52
+ identity verification can match it. An offline quota request can then retain
53
+ the verified cached data as stale. Retry deadlines are in memory, not persisted
54
+ across server restarts.
55
+ When profile identity cannot be verified (for example, a system Codex Keychain
56
+ login without a profile `auth.json`), only fresh responses are shown: no saved
57
+ quota is restored or retained after a failure for that unknown identity.
58
+
59
+ ## Provider behavior
60
+
61
+ **Codex:** a short-lived instance of the supplied real CLI runs `app-server` with
62
+ the exact account environment. It sends `initialize`, `initialized`,
63
+ `account/read` (`refreshToken: false`), then `account/rateLimits/read`. It never
64
+ creates a thread or sends a prompt. The native quota operation can itself refresh
65
+ OAuth credentials; this module performs no custom refresh or forced refresh. The
66
+ quota response account ID is checked against a known profile identity. If an older
67
+ response omits that ID and credentials rotated during the call, it cannot replace
68
+ the previous snapshot. The process is terminated on success, failure or cancellation.
69
+
70
+ **Claude:** on macOS the exact Keychain service/account is preferred. A missing
71
+ or inaccessible item falls back only to `.credentials.json` in the supplied home,
72
+ matching the native CLI's read behavior. Inaccessible Keychain plus a missing file
73
+ remains `unavailable`, since that does not prove the user is signed out. Existing Keychain
74
+ credentials with no OAuth token do not fall through to a different file identity.
75
+ The installed Claude Code 2.1.263 source was checked for its directory hash and
76
+ credential precedence: a custom directory uses the first eight SHA-256 hex digits
77
+ of the NFC-normalized home. `CLAUDE_SECURESTORAGE_CONFIG_DIR` overrides
78
+ `CLAUDE_CONFIG_DIR`; profile preparation must remove or correctly bind it. The
79
+ system CLI may have separate settings and credential homes; quota collection
80
+ uses its effective credential home, including an empty override for the default.
81
+ 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
83
+ must still match the credential hash used to verify a known account identity.
84
+
85
+ Tests use synthetic credentials and a synthetic stdio CLI. They establish local
86
+ protocol, parsing, isolation, scheduling and cache behavior. They do not establish
87
+ live access to a user's subscription or real multi-account acceptance.
88
+
89
+ Protocol reference: [OpenAI Codex app-server account types](https://github.com/openai/codex/blob/main/codex-rs/app-server-protocol/src/protocol/v2/account.rs).
@@ -0,0 +1,95 @@
1
+ import { createHash } from "node:crypto";
2
+ import { execFile } from "node:child_process";
3
+ import { readFile } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { homedir } from "node:os";
6
+ import { UsageError, type CollectedUsage, type QuotaAccount } from "./index";
7
+ import { object, parseClaudeUsage, string } from "./parsers";
8
+ import { credentialHash } from "./credential-hash";
9
+
10
+ type KeychainTarget = { service: string; account: string };
11
+ export type ClaudeDependencies = {
12
+ platform?: string;
13
+ readFile?: (path: string) => Promise<string>;
14
+ readKeychain?: (target: KeychainTarget, signal?: AbortSignal) => Promise<string | null>;
15
+ fetch?: (url: string, init: RequestInit) => Promise<Response>;
16
+ now?: () => number;
17
+ };
18
+ export function claudeKeychainTarget(account: QuotaAccount): KeychainTarget {
19
+ const custom = account.env.CLAUDE_SECURESTORAGE_CONFIG_DIR ?? account.env.CLAUDE_CONFIG_DIR;
20
+ // Verified against Claude Code 2.1.263's embedded secure-storage implementation.
21
+ const resolvedHome = custom || join(account.env.HOME || homedir(),".claude");
22
+ if (resolvedHome.normalize("NFC") !== account.home.normalize("NFC")) throw new UsageError("unavailable", "home_mismatch");
23
+ const suffix = custom ? `-${createHash("sha256").update(account.home.normalize("NFC")).digest("hex").slice(0,8)}` : "";
24
+ const user = account.env.USER;
25
+ return { service: `Claude Code-credentials${suffix}`, account: user && /^[a-zA-Z0-9._-]+$/.test(user) ? user : "claude-code-user" };
26
+ }
27
+ /** Internal resolver shared by collection and credential-version checks. */
28
+ export async function readClaudeCredentials(account: QuotaAccount, dependencies: ClaudeDependencies = {}, signal?: AbortSignal): Promise<{raw:string;source:string}> {
29
+ const target = claudeKeychainTarget(account);
30
+ let keychainUnavailable=false;
31
+ if ((dependencies.platform ?? process.platform) === "darwin") {
32
+ let raw:string|null=null;
33
+ try {raw = await (dependencies.readKeychain ?? keychain)(target, signal);}
34
+ catch {keychainUnavailable=true;}
35
+ if(signal?.aborted)throw new UsageError("unavailable","cancelled");
36
+ if(raw) {
37
+ try {if(JSON.parse(raw)!==null)return {raw,source:"keychain"};} catch { /* Native CLI falls back for corrupt Keychain JSON. */ }
38
+ }
39
+ }
40
+ try {return {raw:await (dependencies.readFile ?? (p=>readFile(p,"utf8")))(join(account.home,".credentials.json")),source:"file"};}
41
+ catch(error) {
42
+ const missing=["ENOENT","ENOTDIR"].includes((error as NodeJS.ErrnoException)?.code??"");
43
+ throw new UsageError(missing&&!keychainUnavailable?"needs_auth":"unavailable",missing&&!keychainUnavailable?"missing_credentials":"credential_read_failed");
44
+ }
45
+ }
46
+ function keychain(target: KeychainTarget, signal?: AbortSignal): Promise<string | null> {
47
+ return new Promise((resolve, reject) => {
48
+ execFile("/usr/bin/security", ["find-generic-password", "-a", target.account, "-w", "-s", target.service], { timeout: 3000, maxBuffer: 1024 * 1024, signal }, (error, stdout) => {
49
+ if (!error) resolve(stdout.trim() || null);
50
+ else if ((error as {code?: number | string}).code === 44) resolve(null);
51
+ else reject(new UsageError("unavailable", "keychain_unavailable"));
52
+ });
53
+ });
54
+ }
55
+ export function retryAfter(value: string | null, now: number): number | undefined {
56
+ if (!value) return undefined;
57
+ const seconds = Number(value);
58
+ if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1000;
59
+ const date = Date.parse(value);
60
+ return Number.isFinite(date) ? Math.max(0, date - now) : undefined;
61
+ }
62
+ export async function collectClaudeUsage(account: QuotaAccount, dependencies: ClaudeDependencies = {}, signal?: AbortSignal): Promise<CollectedUsage> {
63
+ const controller = new AbortController();
64
+ const abort = () => controller.abort();
65
+ if (signal?.aborted) abort();
66
+ signal?.addEventListener("abort", abort, {once:true});
67
+ const timeout = setTimeout(abort,15000);
68
+ timeout.unref();
69
+ try {
70
+ const resolved=await readClaudeCredentials(account,dependencies,signal);
71
+ if(account.requireIdentityVerification&&credentialHash(resolved.source,resolved.raw)!==account.identityCredentialVersion)throw new UsageError("unavailable","credentials_changed");
72
+ let stored:unknown;
73
+ try {stored=JSON.parse(resolved.raw);} catch {throw new UsageError("needs_auth","invalid_credentials");}
74
+ const oauth = object(object(stored)?.claudeAiOauth);
75
+ const token = string(oauth?.accessToken);
76
+ if (!token) throw new UsageError("needs_auth", "missing_oauth");
77
+ const response = await (dependencies.fetch ?? fetch)("https://api.anthropic.com/api/oauth/usage", {
78
+ method: "GET", headers: { Authorization: `Bearer ${token}`, "anthropic-beta": "oauth-2025-04-20", Accept: "application/json" },
79
+ signal: controller.signal,
80
+ redirect: "error",
81
+ });
82
+ if (response.status === 401) throw new UsageError("needs_auth", "unauthorized");
83
+ if (response.status === 429) throw new UsageError("unavailable", "rate_limited", retryAfter(response.headers.get("retry-after"), (dependencies.now ?? Date.now)()));
84
+ if (!response.ok) throw new UsageError("unavailable", response.status === 403 ? "forbidden" : "http_error");
85
+ const result = parseClaudeUsage(await response.json());
86
+ if (!result.windows.length) throw new UsageError("unavailable", "invalid_payload");
87
+ return { ...result, identityKey: account.identityKey, plan: string(oauth?.subscriptionType) };
88
+ } catch (error) {
89
+ if (error instanceof UsageError) throw error;
90
+ throw new UsageError("unavailable", "request_failed");
91
+ } finally {
92
+ clearTimeout(timeout);
93
+ signal?.removeEventListener("abort",abort);
94
+ }
95
+ }
@@ -0,0 +1,79 @@
1
+ import { spawn } from "node:child_process";
2
+ import { UsageError, type CollectedUsage, type QuotaAccount } from "./index";
3
+ import { object, parseCodexUsage, string } from "./parsers";
4
+
5
+ /** A short-lived native app-server session. No thread, prompt, login or forced refresh. */
6
+ export async function collectCodexUsage(account: QuotaAccount, signal?: AbortSignal): Promise<CollectedUsage> {
7
+ const [executable, ...args] = account.command;
8
+ if (!executable) throw new UsageError("unavailable", "missing_cli");
9
+ const child = spawn(executable, [...args, "app-server"], { cwd: account.home, env: account.env, stdio: ["pipe", "pipe", "ignore"] });
10
+ let sequence = 0;
11
+ let buffer = "";
12
+ let failed: UsageError | null = null;
13
+ const pending = new Map<number, {resolve: (value: unknown) => void; reject: (error: UsageError) => void}>();
14
+ const fail = (code: string) => {
15
+ failed = new UsageError("unavailable", code);
16
+ for (const request of pending.values()) request.reject(failed);
17
+ pending.clear();
18
+ };
19
+ child.on("error", () => fail("cli_start_failed"));
20
+ child.on("exit", () => fail("cli_exited"));
21
+ child.stdin.on("error", () => fail("cli_pipe_failed"));
22
+ const abort = () => { fail("cancelled"); child.kill(); };
23
+ signal?.addEventListener("abort", abort, {once:true});
24
+ const timeout = setTimeout(() => { fail("cli_timeout"); child.kill(); }, 15000);
25
+ timeout.unref();
26
+ child.stdout.setEncoding("utf8");
27
+ child.stdout.on("data", (chunk: string) => {
28
+ buffer += chunk;
29
+ if (buffer.length > 2 * 1024 * 1024) { fail("cli_output_limit"); child.kill(); return; }
30
+ let newline: number;
31
+ while ((newline = buffer.indexOf("\n")) >= 0) {
32
+ const line = buffer.slice(0,newline); buffer = buffer.slice(newline + 1);
33
+ let message: Record<string, unknown> | null;
34
+ try { message = object(JSON.parse(line)); } catch { continue; }
35
+ if (!message) continue;
36
+ const request = pending.get(message.id as number);
37
+ if (!request) continue;
38
+ pending.delete(message.id as number);
39
+ if (message.error) {
40
+ const raw = object(message.error);
41
+ const status = raw?.code === 401 || /unauthorized|not authenticated|not logged in|authentication required/i.test(string(raw?.message) ?? "") ? "needs_auth" : "unavailable";
42
+ request.reject(new UsageError(status, "cli_request_failed"));
43
+ } else request.resolve(message.result);
44
+ }
45
+ });
46
+ function request(method: string, params: unknown): Promise<unknown> {
47
+ if (failed) return Promise.reject(failed);
48
+ const id = ++sequence;
49
+ return new Promise((resolve, reject) => { pending.set(id,{resolve,reject}); child.stdin.write(`${JSON.stringify({id,method,params})}\n`); });
50
+ }
51
+ try {
52
+ if (signal?.aborted) throw new UsageError("unavailable", "cancelled");
53
+ await request("initialize", {clientInfo:{name:"paseo_account_switcher",version:"0.1.0"}});
54
+ child.stdin.write(`${JSON.stringify({method:"initialized",params:{}})}\n`);
55
+ const identity = object(await request("account/read", {refreshToken:false}));
56
+ const signedIn = object(identity?.account);
57
+ if (!signedIn) throw new UsageError("needs_auth", "missing_auth");
58
+ if (signedIn.type !== "chatgpt") throw new UsageError("unavailable", "subscription_required");
59
+ const usage = parseCodexUsage(await request("account/rateLimits/read", {}));
60
+ if (account.identityKey && usage.identityKey && account.identityKey !== usage.identityKey) throw new UsageError("needs_auth", "identity_changed");
61
+ if (!usage.windows.length) throw new UsageError("unavailable", "invalid_payload");
62
+ return {...usage, plan:usage.plan ?? string(signedIn.planType)};
63
+ } catch (error) {
64
+ if (error instanceof UsageError) throw error;
65
+ throw new UsageError("unavailable", "cli_failed");
66
+ } finally {
67
+ clearTimeout(timeout);
68
+ signal?.removeEventListener("abort", abort);
69
+ child.stdin.end();
70
+ child.kill();
71
+ // Do not leave an uncooperative CLI running after the request has completed.
72
+ if (child.exitCode === null && child.signalCode === null) {
73
+ await new Promise<void>(resolve => {
74
+ const force = setTimeout(() => { child.kill("SIGKILL"); resolve(); }, 500);
75
+ child.once("close", () => { clearTimeout(force); resolve(); });
76
+ });
77
+ }
78
+ }
79
+ }
@@ -0,0 +1,4 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ export const credentialHash = (source:string,raw:string):string =>
4
+ `present:${createHash("sha256").update(source).update("\0").update(raw).digest("hex")}`;
@@ -0,0 +1,18 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { readClaudeCredentials, type ClaudeDependencies } from "./claude";
4
+ import { UsageError, type QuotaAccount } from "./index";
5
+ import { credentialHash } from "./credential-hash";
6
+
7
+ /** Hashes only the selected provider profile. Never returns credential contents.
8
+ * Keep the previous version on `unavailable`; only `absent` establishes auth loss.
9
+ */
10
+ export async function readCredentialVersion(account: QuotaAccount, dependencies: ClaudeDependencies = {}): Promise<string> {
11
+ try {
12
+ const resolved=account.provider==="claude" ? await readClaudeCredentials(account,dependencies) : {source:"file",raw:await (dependencies.readFile??(path=>readFile(path,"utf8")))(join(account.home,"auth.json"))};
13
+ return credentialHash(resolved.source,resolved.raw);
14
+ } catch(error) {
15
+ if(error instanceof UsageError)return error.status==="needs_auth"?"absent":"unavailable";
16
+ return ["ENOENT","ENOTDIR"].includes((error as NodeJS.ErrnoException)?.code??"")?"absent":"unavailable";
17
+ }
18
+ }
@@ -0,0 +1,225 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
3
+ import { dirname } from "node:path";
4
+ import { UsageSnapshotSchema, type Provider, type UsageSnapshot, type UsageWindow } from "../../shared/contracts";
5
+ import { collectClaudeUsage } from "./claude";
6
+ import { collectCodexUsage } from "./codex";
7
+ import { object } from "./parsers";
8
+
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
+ export { readCredentialVersion } from "./credentials";
11
+ export type CollectedUsage = { identityKey: string | null; plan: string | null; windows: UsageWindow[] };
12
+ export type FetchUsage = (account: QuotaAccount, signal?: AbortSignal) => Promise<CollectedUsage>;
13
+ export type AccountReadOptions = { verifyAccountId?: string };
14
+ export type UsageOptions = { getAccounts: (input?: AccountReadOptions) => Promise<QuotaAccount[]>; fetchUsage?: FetchUsage; cachePath?: string; now?: () => number };
15
+ export class UsageError extends Error {
16
+ constructor(public readonly status: "needs_auth" | "unavailable", public readonly code: string, public readonly retryAfterMs?: number) {
17
+ super(status === "needs_auth" ? "Sign in again to retrieve limits." : "The limits service is temporarily unavailable.");
18
+ }
19
+ }
20
+ type Entry = { fingerprint: string; accountFingerprint: string; provenIdentity: boolean; snapshot: UsageSnapshot; success?: UsageSnapshot; attempts: number; attemptedAt: number | null; retryAt: number };
21
+ type Flight = { entry: Entry; promise: Promise<void>; controller: AbortController };
22
+ const BACKGROUND = 300000;
23
+ const VISIBLE = 60000;
24
+ const LEASE = 90000;
25
+ const MAX_BACKOFF = 1800000;
26
+
27
+ function fingerprint(account: QuotaAccount, includeCredentials=true): string {
28
+ return createHash("sha256").update(JSON.stringify([account.provider, account.home, account.identityKey, account.generation, account.command, includeCredentials?account.credentialVersion:undefined])).digest("hex");
29
+ }
30
+ const identityProven = (account:QuotaAccount) => account.identityKey!==null&&!!account.credentialVersion?.startsWith("present:")&&account.credentialVersion===account.identityCredentialVersion;
31
+ const fetchProvider: FetchUsage = (account, signal) => account.provider === "codex" ? collectCodexUsage(account, signal) : collectClaudeUsage(account, {}, signal);
32
+
33
+ export function createUsageService(options: UsageOptions) {
34
+ const entries = new Map<string, Entry>();
35
+ const flights = new Map<string, Flight>();
36
+ const invalidated = new Set<string>();
37
+ const cached = new Map<string, {fingerprint: string; accountFingerprint?: string; snapshot: UsageSnapshot}>();
38
+ const now = options.now ?? Date.now;
39
+ const fetchUsage = options.fetchUsage ?? fetchProvider;
40
+ let visibleUntil = -1;
41
+ let timer: ReturnType<typeof setInterval> | undefined;
42
+ let closed = false;
43
+ let running = 0;
44
+ const queue: (() => void)[] = [];
45
+ let writes: Promise<void> = Promise.resolve();
46
+ const initialized = (async () => {
47
+ if (!options.cachePath) return;
48
+ try {
49
+ const raw = await readFile(options.cachePath,"utf8");
50
+ if (raw.length > 4 * 1024 * 1024) return;
51
+ const rows = object(JSON.parse(raw))?.entries;
52
+ if (!Array.isArray(rows)) return;
53
+ for (const value of rows) {
54
+ const row = object(value);
55
+ const parsed = UsageSnapshotSchema.safeParse(row?.snapshot);
56
+ if (parsed.success && parsed.data.status === "ok" && parsed.data.fetchedAt && typeof row?.fingerprint === "string") cached.set(parsed.data.accountId,{fingerprint:row.fingerprint,accountFingerprint:typeof row.accountFingerprint==="string"?row.accountFingerprint:undefined,snapshot:parsed.data});
57
+ }
58
+ } catch { /* A missing or corrupt optional cache never blocks quota reads. */ }
59
+ })();
60
+ function persist(): Promise<void> {
61
+ if (!options.cachePath) return Promise.resolve();
62
+ const path = options.cachePath;
63
+ writes = writes.then(async () => {
64
+ const rows = [...cached.values(),...[...entries.values()].flatMap(entry=>entry.success?[{fingerprint:entry.fingerprint,accountFingerprint:entry.accountFingerprint,snapshot:entry.success}]:[])];
65
+ const temporary = `${path}.${randomUUID()}.tmp`;
66
+ try {
67
+ await mkdir(dirname(path),{recursive:true,mode:0o700});
68
+ await writeFile(temporary,JSON.stringify({version:1,entries:rows}),{mode:0o600,flag:"wx"});
69
+ await rename(temporary,path);
70
+ } finally { await rm(temporary,{force:true}).catch(()=>{}); }
71
+ }).catch(()=>{});
72
+ return writes;
73
+ }
74
+ function empty(account: QuotaAccount): UsageSnapshot {
75
+ return {accountId:account.id,provider:account.provider,status:"unavailable",plan:null,windows:[],fetchedAt:null,checkedAt:new Date(now()).toISOString(),nextRetryAt:null,error:null};
76
+ }
77
+ async function sync(input?: AccountReadOptions): Promise<QuotaAccount[]> {
78
+ await initialized;
79
+ if(closed)return [];
80
+ let accounts: QuotaAccount[];
81
+ try {accounts = await options.getAccounts(input);} catch {throw new UsageError("unavailable","account_discovery_failed");}
82
+ if(closed)return [];
83
+ const ids = new Set(accounts.map(account=>account.id));
84
+ let changed = false;
85
+ for(const id of cached.keys())if(!ids.has(id)){cached.delete(id);changed=true;}
86
+ for (const id of entries.keys()) if (!ids.has(id)) { entries.delete(id); cached.delete(id); flights.get(id)?.controller.abort(); changed=true; }
87
+ for (const account of accounts) {
88
+ const signature = fingerprint(account);
89
+ const previous=entries.get(account.id);
90
+ const provenIdentity=identityProven(account);
91
+ const accountFingerprint=fingerprint(account,false);
92
+ const prior=cached.get(account.id);
93
+ const canRestore=account.identityKey!==null&&!invalidated.has(account.id)&&(!account.requireIdentityVerification||provenIdentity);
94
+ const success=canRestore&&(prior?.fingerprint===signature||provenIdentity&&prior?.accountFingerprint===accountFingerprint)?prior!.snapshot:undefined;
95
+ // Cold controller snapshots intentionally have no credential proof yet.
96
+ // Keep their disk cache staged without making it visible or overwriting it.
97
+ if(account.identityKey===null||invalidated.has(account.id)||canRestore){if(cached.delete(account.id))changed=true;}
98
+ if (previous?.fingerprint === signature) {
99
+ previous.provenIdentity||=provenIdentity;
100
+ if(success&&!previous.success){previous.success=success;previous.snapshot={...success,status:"stale",error:"Saved limits; waiting for an update."};changed=true;}
101
+ continue;
102
+ }
103
+ const sameAccount=previous?.accountFingerprint===accountFingerprint;
104
+ if(previous&&sameAccount&&previous.provenIdentity&&provenIdentity){
105
+ previous.fingerprint=signature;
106
+ if(previous.snapshot.status==="ok")previous.snapshot={...previous.snapshot,status:"stale",error:"Credentials changed; waiting to verify limits."};
107
+ cached.delete(account.id);changed=true;continue;
108
+ }
109
+ const snapshot = success ? {...success,status:"stale" as const,error:"Saved limits; waiting for an update."} : empty(account);
110
+ entries.set(account.id,{fingerprint:signature,accountFingerprint,provenIdentity,snapshot,success,attempts:sameAccount?previous.attempts:0,attemptedAt:sameAccount?previous.attemptedAt:null,retryAt:sameAccount?previous.retryAt:0});
111
+ changed=true;
112
+ }
113
+ if (changed && options.cachePath) void persist();
114
+ return accounts;
115
+ }
116
+ async function acquire() {
117
+ if (running < 2) {running++;return;}
118
+ await new Promise<void>(resolve=>queue.push(resolve));
119
+ }
120
+ function release() {const next=queue.shift();if(next)next();else running--;}
121
+ async function refreshOne(account: QuotaAccount): Promise<void> {
122
+ let entry = entries.get(account.id);
123
+ if (closed || !entry || fingerprint(account) !== entry.fingerprint || now() < entry.retryAt) return;
124
+ const inFlight = flights.get(account.id);
125
+ if (inFlight) {
126
+ await inFlight.promise;
127
+ if (inFlight.entry !== entry && !closed) {
128
+ const current = (await sync()).find(value=>value.id===account.id);
129
+ if(current)return refreshOne(current);
130
+ }
131
+ return;
132
+ }
133
+ const controller = new AbortController();
134
+ const promise = (async () => {
135
+ await acquire();
136
+ try {
137
+ if (closed || entries.get(account.id) !== entry) return;
138
+ entry.attemptedAt = now();
139
+ let result: CollectedUsage | undefined;
140
+ let failure: UsageError | undefined;
141
+ let requested=false;
142
+ try {
143
+ const verified=(await sync({verifyAccountId:account.id})).find(value=>value.id===account.id);
144
+ if(!verified||closed||controller.signal.aborted)return;
145
+ entry=entries.get(account.id);
146
+ if(!entry)return;
147
+ const flight=flights.get(account.id);if(flight)flight.entry=entry;
148
+ entry.attemptedAt=now();
149
+ account=verified;
150
+ if(account.requireIdentityVerification&&!identityProven(account))throw new UsageError(account.credentialVersion==="absent"?"needs_auth":"unavailable","identity_unverified");
151
+ requested=true;
152
+ result = await fetchUsage(account,controller.signal);
153
+ if (account.identityKey && result.identityKey && account.identityKey !== result.identityKey) throw new UsageError("needs_auth","identity_changed");
154
+ } catch (error) {failure=error instanceof UsageError?error:new UsageError("unavailable","request_failed");}
155
+ let current:QuotaAccount[]|undefined;
156
+ try {current=await sync(requested?{verifyAccountId:account.id}:undefined);}
157
+ catch {failure??=new UsageError("unavailable","account_discovery_failed");}
158
+ if (closed || !entry || current&&!current.some(a=>a.id===account.id) || entries.get(account.id) !== entry) return;
159
+ const verified=current?.find(a=>a.id===account.id)??account;
160
+ if(requested&&verified.requireIdentityVerification&&!identityProven(verified))failure??=new UsageError(verified.credentialVersion==="absent"?"needs_auth":"unavailable","identity_unverified");
161
+ if(requested&&account.credentialVersion!==verified.credentialVersion&&(!identityProven(account)||!identityProven(verified)||result?.identityKey!==account.identityKey))failure??=new UsageError("unavailable","response_identity_unverified");
162
+ const checkedAt = new Date(now()).toISOString();
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};
165
+ entry.snapshot=snapshot;entry.success=account.identityKey===null?undefined:snapshot;entry.attempts=0;entry.retryAt=0;
166
+ } else {
167
+ const error=failure??new UsageError("unavailable","request_failed");
168
+ entry.attempts++;
169
+ const backoff = error.retryAfterMs !== undefined && Number.isFinite(error.retryAfterMs) ? Math.max(0,error.retryAfterMs) : Math.min(MAX_BACKOFF,60000*2**Math.min(entry.attempts-1,5));
170
+ entry.retryAt=now()+backoff;
171
+ if (error.status==="needs_auth") entry.success=undefined;
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};
174
+ }
175
+ await persist();
176
+ } finally { release(); }
177
+ })();
178
+ flights.set(account.id,{entry,promise,controller});
179
+ try {await promise;} finally {if(flights.get(account.id)?.promise===promise)flights.delete(account.id);}
180
+ }
181
+ const snapshots = (accounts: QuotaAccount[]) => accounts.map(a=>structuredClone(entries.get(a.id)?.snapshot??empty(a)));
182
+ async function refresh(accountId?: string): Promise<UsageSnapshot[]> {
183
+ const accounts=await sync();
184
+ await Promise.all(accounts.filter(account=>!accountId||account.id===accountId).map(refreshOne));
185
+ return snapshots(await sync());
186
+ }
187
+ async function tick(): Promise<void> {
188
+ if(closed)return;
189
+ const accounts=await sync();
190
+ const cadence=now()<visibleUntil?VISIBLE:BACKGROUND;
191
+ await Promise.all(accounts.filter(account=>{
192
+ const entry=entries.get(account.id)!;
193
+ if(entry.attemptedAt===null||now()-entry.attemptedAt>=cadence)return true;
194
+ return entry.snapshot.windows.some(window=>{
195
+ const reset=window.resetsAt?Date.parse(window.resetsAt):NaN;
196
+ return Number.isFinite(reset)&&reset<=now()&&reset>entry.attemptedAt!;
197
+ });
198
+ }).map(refreshOne));
199
+ }
200
+ async function list(input: {visible?:boolean} = {}): Promise<UsageSnapshot[]> {
201
+ if(input.visible)visibleUntil=now()+LEASE;
202
+ const accounts=await sync();
203
+ if(timer)void tick().catch(()=>{});
204
+ return snapshots(accounts);
205
+ }
206
+ function start() {
207
+ if(timer||closed)return;
208
+ timer=setInterval(()=>{void tick().catch(()=>{});},5000);
209
+ timer.unref();
210
+ void tick().catch(()=>{});
211
+ }
212
+ function invalidate(accountId: string) {
213
+ if(closed)return;
214
+ invalidated.add(accountId);cached.delete(accountId);entries.delete(accountId);flights.get(accountId)?.controller.abort();void persist();
215
+ }
216
+ async function close() {
217
+ closed=true;
218
+ if(timer)clearInterval(timer);
219
+ timer=undefined;
220
+ for(const flight of flights.values())flight.controller.abort();
221
+ await Promise.allSettled([...flights.values()].map(flight=>flight.promise));
222
+ await writes;
223
+ }
224
+ return {list,refresh,start,close,invalidate};
225
+ }