UNPKG

@phren/cli

Version:

Knowledge layer for AI agents - CLI, MCP server, and data layer

348 lines (347 loc) • 17.4 kB
// Claude accounts on this computer: one Claude config home per account. // ~/.claude is the "default" account and is launched without CLAUDE_CONFIG_DIR, // so its keychain item and ~/.claude.json stay where Claude Code put them. // Every ~/.claude-<slug> holding a .claude.json is another account. See docs/accounts.md. import { createHash, randomUUID } from "node:crypto"; import { existsSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"; import { mkdir } from "node:fs/promises"; import { spawn } from "node:child_process"; import path from "node:path"; import { dump, load } from "js-yaml"; import { withFileLock } from "../governance/locks.js"; import { claudeConfigDir, homeDir } from "../home-paths.js"; import { bridgeRoot } from "./protocol.js"; import { killProbeGroup, startProbe } from "./probe-processes.js"; import { claudePlan, monthlyAnniversary, subscriptionDate } from "./subscription.js"; export const DEFAULT_ACCOUNT = "default"; const SLUG = /^[a-z0-9][a-z0-9-]{0,31}$/; export function isAccountSlug(value) { return value === DEFAULT_ACCOUNT || SLUG.test(value); } function defaultHome(env) { const configured = Boolean(env.CLAUDE_CONFIG_DIR?.trim()); const dir = claudeConfigDir(env); // Claude keeps .claude.json inside CLAUDE_CONFIG_DIR when set, else beside ~/.claude. return { id: DEFAULT_ACCOUNT, dir, configFile: path.join(configured ? dir : homeDir(env), ".claude.json"), isDefault: true }; } const mtimeOf = (dir) => { try { return statSync(dir).mtimeMs; } catch { return -1; } }; const homesCache = new Map(); /** How long a listing stands even when its folders changed: Claude rewrites each `.claude.json` through * temp files beside it every few seconds, so their mtimes alone would rarely let a listing be reused. */ const HOMES_REUSE_MS = 2_000; /** The longest a listing stands on unchanged mtimes: a home made within one coarse mtime tick of the * last listing would otherwise stay unseen until another folder changed. */ const HOMES_MAX_AGE_MS = 60_000; /** Every Claude home on this computer, default first, then by slug. The Hook asks several times per pane * per overview, so a listing is reused for HOMES_REUSE_MS, and after that while the home folder and * every `.claude-*` folder in it are unchanged, up to HOMES_MAX_AGE_MS. */ export function claudeHomes(env = process.env) { const first = defaultHome(env), home = homeDir(env), key = `${home}\0${first.dir}\0${first.configFile}`; const cached = homesCache.get(key), now = Date.now(); if (cached && (now - cached.at < HOMES_REUSE_MS || (now - cached.at < HOMES_MAX_AGE_MS && mtimeOf(home) === cached.home && cached.candidates.every(candidate => mtimeOf(candidate.dir) === candidate.mtime)))) return [...cached.homes]; const homeMtime = mtimeOf(home); const homes = listClaudeHomes(first, home); homesCache.set(key, { at: now, home: homeMtime, candidates: homes.candidates, homes: homes.homes }); while (homesCache.size > 16) homesCache.delete(homesCache.keys().next().value); return [...homes.homes]; } function listClaudeHomes(first, home) { const homes = [first], candidates = []; let names = []; try { names = readdirSync(home); } catch { return { homes, candidates }; } for (const name of names.sort()) { if (!name.startsWith(".claude-")) continue; candidates.push({ dir: path.join(home, name), mtime: mtimeOf(path.join(home, name)) }); const id = name.slice(".claude-".length); if (!SLUG.test(id) || id === DEFAULT_ACCOUNT) continue; const dir = path.join(home, name); if (dir === homes[0].dir) continue; try { if (!statSync(dir).isDirectory() || !existsSync(path.join(dir, ".claude.json"))) continue; } catch { continue; } homes.push({ id, dir, configFile: path.join(dir, ".claude.json"), isDefault: false }); } return { homes, candidates }; } export function claudeHome(id, env = process.env) { const wanted = id?.trim() || DEFAULT_ACCOUNT; return claudeHomes(env).find(home => home.id === wanted); } /** The home a transcript or other file lives in, by longest matching directory. */ export function claudeHomeOfPath(file, env = process.env) { const resolved = path.resolve(file); return claudeHomes(env) .filter(home => resolved.startsWith(home.dir + path.sep)) .sort((a, b) => b.dir.length - a.dir.length)[0]; } /** Environment a launch into this home needs; empty for the default home. */ export function claudeLaunchEnv(home) { return home.isDefault ? {} : { CLAUDE_CONFIG_DIR: home.dir }; } /** The config home a running Claude process uses, from its CLAUDE_CONFIG_DIR. */ export function claudeHomeOfEnv(value, env = process.env) { if (!value?.trim()) return claudeHome(DEFAULT_ACCOUNT, env); const dir = path.resolve(value.trim()); return claudeHomes(env).find(home => home.dir === dir); } // ── labels (<bridge>/accounts.yaml) ───────────────────────────────────────── export const accountsFile = () => path.join(bridgeRoot(), "accounts.yaml"); /** `accounts.yaml` as an object: empty when there is none (or it is blank), an error when it is there but is * not a mapping, so a write never replaces what it couldn't read. */ export function parseAccountsYaml(text) { if (text === undefined || !text.trim()) return {}; const parsed = load(text); if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return parsed; throw new Error(`${accountsFile()} is not a mapping; fix or remove it first.`); } let accountsWrites = Promise.resolve(); /** * The one way `accounts.yaml` is changed (labels, credits, pools): reads it, applies `change`, and writes it back * atomically. Writes in this process run one at a time, and each holds the file's lock against other processes * (the CLI beside the Hook), so no write drops another's change. A file that can't be read is never replaced. */ export function updateAccountsFile(change) { const run = accountsWrites.then(async () => { await mkdir(bridgeRoot(), { recursive: true, mode: 0o700 }); const file = accountsFile(); withFileLock(file, () => { let text; try { text = readFileSync(file, "utf8"); } catch (error) { if (error.code !== "ENOENT") throw error; } const parsed = parseAccountsYaml(text); change(parsed); const temporary = `${file}.${randomUUID()}.tmp`; try { writeFileSync(temporary, dump(parsed), { mode: 0o600, flag: "wx" }); renameSync(temporary, file); } finally { rmSync(temporary, { force: true }); } }); }); accountsWrites = run.catch(() => undefined); return run; } function readLabels() { try { const parsed = load(readFileSync(accountsFile(), "utf8")); const claude = parsed && typeof parsed === "object" ? parsed.claude : undefined; if (!claude || typeof claude !== "object") return {}; return Object.fromEntries(Object.entries(claude) .filter(([id, label]) => isAccountSlug(id) && typeof label === "string" && label.trim().length > 0 && label.length <= 40) .map(([id, label]) => [id, label.trim()])); } catch { return {}; } } export function accountLabel(id, labels = readLabels()) { if (labels[id]) return labels[id]; if (id === DEFAULT_ACCOUNT) return "Claude"; return id.split("-").filter(Boolean).map(part => part.charAt(0).toUpperCase() + part.slice(1)).join(" "); } export async function setAccountLabel(id, label) { if (!isAccountSlug(id)) throw new Error(`"${id}" is not an account name: use lowercase letters, digits and dashes.`); const clean = label.trim(); if (!clean || clean.length > 40 || /[\u0000-\u001f]/.test(clean)) throw new Error("A label is 1 to 40 printable characters."); await updateAccountsFile(parsed => { const claude = parsed.claude && typeof parsed.claude === "object" ? parsed.claude : {}; parsed.claude = { ...claude, [id]: clean }; }); } const identityCache = new Map(); function oauthIdentity(configFile) { try { const stat = statSync(configFile); if (!stat.isFile() || stat.size > 16_777_216) return {}; const cached = identityCache.get(configFile); if (cached && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) return cached; const config = JSON.parse(readFileSync(configFile, "utf8")); const account = config.oauthAccount && typeof config.oauthAccount === "object" ? config.oauthAccount : {}; const id = (value) => typeof value === "string" && /^[A-Za-z0-9-]{1,64}$/.test(value) ? value : undefined; const email = typeof account.emailAddress === "string" && /^[^\s@]{1,64}@[^\s@]{1,190}$/.test(account.emailAddress) ? account.emailAddress : undefined; const fetched = typeof account.profileFetchedAt === "number" ? subscriptionDate(Math.floor(account.profileFetchedAt / 1000)) : undefined; const value = { mtimeMs: stat.mtimeMs, size: stat.size, uuid: id(account.accountUuid), email, organization: id(account.organizationUuid), plan: claudePlan(account), startedAt: subscriptionDate(account.subscriptionCreatedAt), checkedAt: fetched }; identityCache.set(configFile, value); return value; } catch { return {}; } } /** * Stable across computers for one subscription; home-scoped when unknown. * One login can belong to several organizations (a personal plan and a Team * seat), each its own allowance, so the organization is part of the key. */ export function claudeAccountKey(home) { const { uuid, email, organization } = oauthIdentity(home.configFile); const login = uuid ?? email; if (!login) return `claude:home:${home.id}`; return "claude:" + createHash("sha256").update(organization ? `${login}|${organization}` : login).digest("hex").slice(0, 12); } /** The login's email, so the phone can name a card merged across computers. Usage rows only. */ export function claudeAccountEmail(home) { return oauthIdentity(home.configFile).email; } /** A login is recorded but its profile names no plan Phren knows. */ export function claudePlanUnknown(home) { const identity = oauthIdentity(home.configFile); return Boolean(identity.uuid ?? identity.email) && !identity.plan; } /** * The account home's own subscription, independent of the quota snapshot's * age. `checkedAt` is when Claude Code last fetched the profile, so the * newest profile wins when computers disagree about a plan that changed. */ export function claudeAccountSubscription(home, now = new Date(), fallbackPlan) { const { plan: profilePlan, startedAt, checkedAt } = oauthIdentity(home.configFile); const plan = profilePlan ?? fallbackPlan; if (!plan) return undefined; const renewsAt = startedAt && profilePlan ? monthlyAnniversary(startedAt, now) : undefined; return { plan, ...(startedAt && profilePlan ? { startedAt } : {}), ...(renewsAt ? { renewsAt, renewsEstimated: true } : {}), checkedAt: checkedAt ?? now.toISOString() }; } export function claudeAccountRef(home, labels = readLabels()) { return { id: home.id, label: accountLabel(home.id, labels), key: claudeAccountKey(home) }; } /** * A privacy-preserving fingerprint of a home's login: the signed-in account's stable identity and the * credential file's own metadata, never the main config file's (a trust prompt or project setting * rewrites it without changing the login). A re-login changes it, so cached and persisted answers for * the old login are dropped. Undefined when the config names no identity: the last classification is * then kept rather than discarded. Only the hash is ever stored. */ export function claudeLoginFingerprint(home) { const identity = oauthIdentity(home.configFile); // accountUuid is the login; the organization separates two seats of one login. Email only when no uuid. const stable = identity.uuid ? `${identity.uuid}|${identity.organization ?? ""}` : identity.email; if (!stable) return undefined; let credentials; try { const value = statSync(path.join(home.dir, ".credentials.json")); if (value.isFile()) credentials = { mtimeMs: value.mtimeMs, size: value.size, ino: value.ino }; } catch { /* No credentials file here (macOS often keeps its own in the keychain). */ } return createHash("sha256") .update([stable, credentials?.mtimeMs ?? "", credentials?.size ?? "", credentials?.ino ?? ""].join("|")).digest("hex"); } export const CODEX_ACCOUNT = { id: DEFAULT_ACCOUNT, label: "Codex", key: "codex" }; /** Only for tests. */ /** Drop the cached home listing, so a home made in this process is seen at once. */ export function forgetClaudeHomes() { homesCache.clear(); } export function clearAccountCaches() { identityCache.clear(); authCache.clear(); homesCache.clear(); } const AUTH_CACHE_MS = 5 * 60_000; const AUTH_TIMEOUT_MS = 10_000; const SIGNED_OUT_CACHE_MS = 30_000; const authCache = new Map(); /** Parse `claude auth status --json`. Never keeps anything but the state and plan. */ export function parseAuthStatus(output) { try { const value = JSON.parse(output); if (value.loggedIn !== true) return { signedIn: false, reason: "Not signed in" }; const plan = typeof value.subscriptionType === "string" && /^[a-z0-9_-]{1,32}$/i.test(value.subscriptionType) ? value.subscriptionType : undefined; return { signedIn: true, ...(plan ? { plan } : {}), ...(value.authMethod === "console" ? { console: true } : {}) }; } catch { return { signedIn: false, unknown: true, reason: "Claude did not report its sign-in state" }; } } /** How the sign-in probe starts Claude: an npm install on Windows is `claude.cmd`, which only a shell starts. */ export function claudeAuthSpawn(platform = process.platform) { return { command: "claude", shell: platform === "win32" }; } /** * Stops the sign-in probe and anything it started. On Windows the child is cmd.exe, so * killing it alone leaves the claude started by claude.cmd running: kill the tree with * taskkill. Elsewhere the child is claude itself. */ export function claudeAuthKill(child, platform = process.platform, run = spawn, env = process.env) { const signal = () => { try { child.kill("SIGKILL"); } catch { /* Already gone. */ } }; if (platform !== "win32" || !child.pid) return signal(); const root = env.SystemRoot || env.SYSTEMROOT || env.windir || "C:\\Windows"; try { run(path.win32.join(root, "System32", "taskkill.exe"), ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true }) .on("error", signal); } catch { signal(); } } let probeExit; /** Only for tests: settles when the most recent sign-in probe's child has exited. */ export function claudeAuthProbeExit() { return probeExit; } const runAuthStatus = home => new Promise(resolve => { const { command, shell } = claudeAuthSpawn(); const kill = shell ? claudeAuthKill : killProbeGroup; const child = startProbe(() => spawn(command, ["auth", "status", "--json"], { cwd: homeDir(), stdio: ["ignore", "pipe", "ignore"], shell, detached: !shell, windowsHide: true, env: { ...process.env, ...claudeLaunchEnv(home), NO_COLOR: "1" }, }), kill); let out = "", done = false, exit; probeExit = new Promise(settle => { exit = settle; }); const finish = () => { if (!done) { done = true; clearTimeout(timer); resolve(out); } }; const timer = setTimeout(() => { kill(child); finish(); }, AUTH_TIMEOUT_MS); child.stdout.on("data", (chunk) => { if (out.length < 16_384) out += chunk.toString(); }); child.on("error", () => { exit(); finish(); }); child.on("close", () => { exit(); finish(); }); }); export function claudeAuthStatus(home, run = runAuthStatus, now = Date.now()) { const fingerprint = claudeLoginFingerprint(home); const cached = authCache.get(home.dir); // A re-login changes the fingerprint: an answer cached for the old login must not be reused. if (cached && cached.fingerprint === fingerprint && now - cached.at < (cached.signedIn === false ? SIGNED_OUT_CACHE_MS : AUTH_CACHE_MS)) return cached.value; const entry = { at: now, fingerprint, value: Promise.resolve({ signedIn: false }) }; // A signed-out answer is kept briefly so a fresh /login shows up within half a minute. entry.value = run(home).then(parseAuthStatus, () => ({ signedIn: false, unknown: true, reason: "Claude did not report its sign-in state" })) .then(status => { entry.signedIn = status.unknown ? false : status.signedIn; return status; }); authCache.set(home.dir, entry); return entry.value; }