paseo-room 0.2.0 → 0.4.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.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../package.json","../src/result.ts","../src/credentials.ts","../src/layout.ts","../src/fsops.ts","../src/roles.ts","../src/room.ts","../src/which.ts","../src/auth.ts","../src/room/prompts.ts","../src/room/instructions.ts","../src/agents/mcp.ts","../src/agents/resources.ts","../src/agents/claude.ts","../src/agents/codex.ts","../src/agents/pi.ts","../src/paseo.ts","../src/plugin.ts","../src/commands.ts","../src/wizard.ts","../src/cli.ts","../src/render.ts","../src/index.ts"],"sourcesContent":["{\n \"name\": \"paseo-room\",\n \"version\": \"0.2.0\",\n \"description\": \"One CLI that configures Codex, Claude Code, and Pi role homes in $HOME and registers them with your local Paseo daemon.\",\n \"keywords\": [\n \"paseo\",\n \"codex\",\n \"claude-code\",\n \"pi-coding-agent\",\n \"agent\",\n \"orchestration\",\n \"cli\"\n ],\n \"homepage\": \"https://github.com/cuongntr/paseo-room#readme\",\n \"bugs\": \"https://github.com/cuongntr/paseo-room/issues\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/cuongntr/paseo-room.git\"\n },\n \"license\": \"MIT\",\n \"author\": \"Invoker <cuongnt1987@gmail.com>\",\n \"type\": \"module\",\n \"engines\": {\n \"node\": \">=22\"\n },\n \"bin\": {\n \"paseo-room\": \"dist/index.js\"\n },\n \"files\": [\n \"dist/\"\n ],\n \"scripts\": {\n \"typecheck\": \"tsc --noEmit\",\n \"lint\": \"eslint . --max-warnings 0\",\n \"test\": \"vitest run\",\n \"test:package\": \"vitest run --config vitest.package.config.ts\",\n \"build\": \"tsup && node --input-type=module -e \\\"import { cpSync, rmSync } from 'node:fs'; for (const [source, target] of [['src/room/prompts', 'dist/prompts'], ['src/plugin-assets', 'dist/plugin-assets']]) { rmSync(target, { recursive: true, force: true }); cpSync(source, target, { recursive: true }); }\\\"\",\n \"prepack\": \"npm run build\",\n \"verify\": \"npm run typecheck && npm run lint && npm test && npm run build && npm run test:package\"\n },\n \"dependencies\": {\n \"@clack/prompts\": \"^1.8.0\",\n \"@getpaseo/client\": \"0.8.0-beta.1\",\n \"commander\": \"^14.0.3\",\n \"semver\": \"^7.8.5\",\n \"smol-toml\": \"^1.8.0\",\n \"zod\": \"^4.5.4\"\n },\n \"devDependencies\": {\n \"@eslint/js\": \"^10.0.1\",\n \"@types/node\": \"^22.0.0\",\n \"@types/semver\": \"^7.7.0\",\n \"eslint\": \"^10.10.0\",\n \"tsup\": \"^8.5.1\",\n \"typescript\": \"~5.9.3\",\n \"typescript-eslint\": \"^8.70.0\",\n \"vitest\": \"^4.1.11\"\n }\n}\n","export type Status = 'pass' | 'warn' | 'fail';\nexport interface Check {\n readonly id: string;\n readonly status: Status;\n readonly message: string;\n readonly fix?: string;\n}\nexport interface Operation {\n readonly action: 'create' | 'update' | 'remove' | 'noop';\n readonly kind: 'dir' | 'file' | 'link' | 'provider' | 'profile' | 'plugin';\n readonly target: string;\n}\nexport type Outcome = 'ok' | 'changes-planned' | 'failed';\nexport interface Result {\n readonly command: string;\n readonly outcome: Outcome;\n readonly changed: boolean;\n readonly checks: readonly Check[];\n readonly operations: readonly Operation[];\n}\n\nexport function pass(id: string, message: string): Check {\n return { id, status: 'pass', message };\n}\nexport function warn(id: string, message: string, fix?: string): Check {\n return { id, status: 'warn', message, ...(fix === undefined ? {} : { fix }) };\n}\nexport function fail(id: string, message: string, fix: string): Check {\n return { id, status: 'fail', message, fix };\n}\nexport function failed(command: string, checks: readonly Check[]): Result {\n return { command, outcome: 'failed', changed: false, checks, operations: [] };\n}\nexport function hasFailure(checks: readonly Check[]): boolean {\n return checks.some(check => check.status === 'fail');\n}\nexport function exitCode(result: Result): number {\n return result.outcome === 'failed' || hasFailure(result.checks) ? 1 : 0;\n}\n","import { lstat, readlink } from 'node:fs/promises';\nimport { warn, type Check } from './result.js';\n\nexport type CredentialPathState =\n | { readonly kind: 'missing' }\n | { readonly kind: 'file' }\n | { readonly kind: 'symlink'; readonly target: string }\n | { readonly kind: 'unsafe'; readonly fileType: string };\n\nexport interface CredentialDiagnostic {\n /** Credential paths are diagnostic-only and must never become managed entries. */\n readonly path: string;\n readonly checks: readonly Check[];\n}\n\nfunction fileType(stat: Awaited<ReturnType<typeof lstat>>): string {\n if (stat.isDirectory()) return 'directory';\n if (stat.isSocket()) return 'socket';\n if (stat.isFIFO()) return 'FIFO';\n if (stat.isCharacterDevice()) return 'character device';\n if (stat.isBlockDevice()) return 'block device';\n return 'unsupported file type';\n}\n\n/** Inspect only path metadata. Credential contents and link targets are never followed. */\nexport async function inspectCredentialPath(path: string): Promise<CredentialPathState> {\n let stat;\n try {\n stat = await lstat(path);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { kind: 'missing' };\n return { kind: 'unsafe', fileType: 'uninspectable path' };\n }\n if (stat.isFile()) return { kind: 'file' };\n if (!stat.isSymbolicLink()) return { kind: 'unsafe', fileType: fileType(stat) };\n try {\n return { kind: 'symlink', target: await readlink(path) };\n } catch {\n return { kind: 'unsafe', fileType: 'unreadable symbolic link' };\n }\n}\n\nfunction shellQuote(value: string): string {\n return `'${value.replaceAll(\"'\", `'\"'\"'`)}'`;\n}\n\nexport function roleCommand(\n environment: Readonly<Record<string, string>>,\n executable: string,\n args: readonly string[] = [],\n): string {\n const variables = Object.entries(environment).map(([name, value]) => `${name}=${shellQuote(value)}`);\n return [...variables, ...[executable, ...args].map(shellQuote)].join(' ');\n}\n\nexport interface PreservedCredentialInput {\n readonly id: string;\n readonly agent: string;\n readonly role: string;\n readonly path: string;\n readonly state: Exclude<CredentialPathState, { readonly kind: 'missing' }>;\n readonly login: string;\n readonly status?: string;\n}\n\n/** Produce migration diagnostics for an existing path without claiming authentication. */\nexport function preservedCredentialCheck(input: PreservedCredentialInput): Check {\n const status = input.status ? ` Check status with: ${input.status}.` : '';\n if (input.state.kind === 'file') {\n return warn(`${input.id}.diverged-file-preserve`,\n `${input.agent} ${input.role} auth: configured structurally (diverged-file-preserve); a role-owned credential file exists at ${input.path} and is preserved. Token validity and freshness were not checked.`,\n `If authentication fails, close that role and authenticate it again with: ${input.login}.${status}`);\n }\n if (input.state.kind === 'symlink') {\n return warn(`${input.id}.legacy-shared-risk`,\n `${input.agent} ${input.role} auth: legacy-shared-risk; a credential symlink at ${input.path} -> ${input.state.target} is preserved. Its target was not inspected, followed, or changed.`,\n `Close that role. Remove only the legacy link with: rm -- ${shellQuote(input.path)}. Then create role-owned credentials with: ${input.login}.${status}`);\n }\n return warn(`${input.id}.manual-recovery`,\n `${input.agent} ${input.role} auth: diverged-file-preserve/manual-recovery; ${input.path} is a ${input.state.fileType}, not a credential file. It is preserved without inspection.`,\n `Close that role and inspect the path metadata yourself. Move or remove it manually only when safe, then authenticate with: ${input.login}.${status}`);\n}\n\nexport function presentNames(names: ReadonlySet<string>, supported: readonly string[]): string[] {\n return supported.filter(name => names.has(name));\n}\n\nexport function configuredByNamesCheck(id: string, agent: string, role: string, names: readonly string[]): Check {\n return warn(`${id}.configured-structurally`,\n `${agent} ${role} auth: configured structurally; ${names.join(', ')} ${names.length === 1 ? 'is' : 'are'} present by name. Values, token validity, and freshness were not checked.`);\n}\n\nexport function ambientNamesCheck(id: string, agent: string, role: string, names: readonly string[]): Check {\n return warn(`${id}.ambient-auth-unverifiable`,\n `${agent} ${role} auth: ambient auth unverifiable; ${names.join(', ')} ${names.length === 1 ? 'is' : 'are'} present by name in the setup process. paseo-room does not copy credential values into providers, so availability to the Paseo-launched role, token validity, and freshness were not checked.`);\n}\n","import { homedir } from 'node:os';\nimport { join, resolve, sep } from 'node:path';\nimport { fail, type Check } from './result.js';\nimport type { AgentId, Role } from './roles.js';\n\nexport interface Options {\n readonly roomHome?: string;\n readonly codexHome?: string;\n readonly claudeHome?: string;\n readonly piHome?: string;\n readonly codexBin?: string;\n readonly claudeBin?: string;\n readonly piBin?: string;\n readonly paseoBin?: string;\n}\nexport interface Layout {\n readonly home: string;\n readonly roomHome: string;\n readonly paseoHome: string;\n readonly agentHome: Record<AgentId, string>;\n /** Claude keeps legacy default state beside ~/.claude, but custom config state inside it. */\n readonly claudeState: string;\n readonly bin: Record<AgentId | 'paseo', string>;\n /** The PATH executables are looked up on. Resolved here so nothing reaches for process.env. */\n readonly searchPath: string;\n /** Environment names only, for structural auth diagnostics without retaining values. */\n readonly envNames: ReadonlySet<string>;\n}\n\nfunction pick(...candidates: readonly (string | undefined)[]): string {\n for (const candidate of candidates) if (candidate?.trim()) return candidate.trim();\n throw new Error('Could not determine HOME; pass explicit --room-home and --codex-home/--claude-home paths.');\n}\n\n/** Everything is derived from HOME; flags and environment only override defaults. */\nexport function resolveLayout(options: Options = {}, env: NodeJS.ProcessEnv = process.env): Layout {\n const home = pick(env.HOME, homedir());\n const claudeOverride = options.claudeHome?.trim() || env.CLAUDE_CONFIG_DIR?.trim() || undefined;\n const claudeHome = resolve(pick(claudeOverride, join(home, '.claude')));\n // Relative overrides resolve against the working directory, as a CLI flag should.\n return {\n home,\n roomHome: resolve(pick(options.roomHome, env.PASEO_ROOM_HOME, join(home, '.paseo-room'))),\n paseoHome: resolve(pick(env.PASEO_HOME, join(home, '.paseo'))),\n agentHome: {\n codex: resolve(pick(options.codexHome, env.CODEX_HOME, join(home, '.codex'))),\n claude: claudeHome,\n pi: resolve(pick(options.piHome, env.PI_CODING_AGENT_DIR, join(home, '.pi', 'agent'))),\n },\n claudeState: claudeOverride?.trim() ? join(claudeHome, '.claude.json') : join(home, '.claude.json'),\n bin: {\n codex: pick(options.codexBin, env.CODEX_BIN, 'codex'),\n claude: pick(options.claudeBin, env.CLAUDE_BIN, 'claude'),\n pi: pick(options.piBin, env.PI_BIN, 'pi'),\n paseo: pick(options.paseoBin, env.PASEO_BIN, 'paseo'),\n },\n searchPath: env.PATH ?? '',\n envNames: new Set(Object.keys(env)),\n };\n}\n\n/** True when `path` is the root itself or sits underneath it. */\nexport function contains(root: string, path: string): boolean {\n return path === root || path.startsWith(root.endsWith(sep) ? root : root + sep);\n}\n\n/** The room home must own its directory: no overlap with $HOME or a source agent home. */\nexport function layoutChecks(layout: Layout, agents: readonly AgentId[]): Check[] {\n const checks: Check[] = [];\n if (contains(layout.roomHome, layout.home)) {\n checks.push(fail('room.home', `Refusing to use ${layout.roomHome} as the room home: it contains your home directory.`,\n 'Point --room-home at a dedicated directory, by default ~/.paseo-room.'));\n }\n for (const id of agents) {\n const home = layout.agentHome[id];\n if (contains(layout.roomHome, home) || contains(home, layout.roomHome)) {\n checks.push(fail(`${id}.home`, `The ${id} home ${home} overlaps the room home ${layout.roomHome}.`,\n `Pass --${id}-home pointing at your own ${id} configuration (this happens when setup runs inside a room seat).`));\n }\n }\n return checks;\n}\n\nexport function roleHome(layout: Layout, agent: AgentId, role: Role): string {\n return join(layout.roomHome, 'roles', agent, role);\n}\nexport function sharedRoom(layout: Layout): string {\n return join(layout.roomHome, 'room');\n}\n","import { randomBytes } from 'node:crypto';\nimport { chmod, lstat, mkdir, readdir, readFile, readlink, rename, rm, symlink, unlink, writeFile } from 'node:fs/promises';\nimport type { Stats } from 'node:fs';\nimport { basename, dirname, join } from 'node:path';\nimport type { Operation } from './result.js';\n\n/** A directory the room creates but whose children it does not own. */\nexport interface DirEntry { readonly kind: 'dir'; readonly path: string }\n/** `once` writes the file only when absent: runtime state the agent owns after setup. */\nexport interface FileEntry { readonly kind: 'file'; readonly path: string; readonly content: string; readonly once?: true }\nexport interface LinkEntry { readonly kind: 'link'; readonly path: string; readonly target: string }\n/**\n * A directory whose whole child inventory the room owns: names outside `children`\n * are removed so a generated projection cannot go stale. Ownership is declared here\n * and never inferred from an ordinary `dir`, so it stays limited to generated\n * projections such as Peer `skills` — never role homes or credential-bearing paths.\n */\nexport interface ManagedDirEntry {\n readonly kind: 'managed-dir';\n readonly path: string;\n readonly children: readonly string[];\n /** The single legacy shape this path may be migrated from: a symlink to this target. */\n readonly legacyLink?: string;\n}\nexport type Entry = DirEntry | FileEntry | LinkEntry | ManagedDirEntry;\n\nconst DIR_MODE = 0o700;\nconst FILE_MODE = 0o600;\n\n/**\n * An existing path is not the shape the room manages, so replacing it would destroy\n * something this CLI does not own. Raised before any deletion.\n */\nexport class ManagedPathError extends Error {\n readonly path: string;\n readonly fix: string;\n constructor(path: string, message: string, fix: string) {\n super(message);\n this.name = 'ManagedPathError';\n this.path = path;\n this.fix = fix;\n }\n}\n\nconst MOVE_ASIDE = 'Check that path for role-owned credentials, move it aside manually, then run setup again.';\n\nfunction shape(stat: Stats): string {\n if (stat.isSymbolicLink()) return 'a symbolic link';\n if (stat.isDirectory()) return 'a directory';\n if (stat.isFile()) return 'a regular file';\n return 'a special file';\n}\n\nfunction refuse(path: string, expected: string, stat: Stats): never {\n throw new ManagedPathError(path, `Refusing to replace ${path}: expected ${expected} but found ${shape(stat)}.`, MOVE_ASIDE);\n}\n\nfunction isMissing(error: unknown): boolean {\n return error !== null && typeof error === 'object' && 'code' in error && error.code === 'ENOENT';\n}\n\nasync function lstatOrAbsent(path: string): Promise<Stats | undefined> {\n try { return await lstat(path); } catch (error) {\n if (isMissing(error)) return undefined;\n throw error;\n }\n}\n\n/** Names present under a managed directory that its declaration does not claim. */\nasync function staleChildren(entry: ManagedDirEntry): Promise<string[]> {\n const declared = new Set(entry.children);\n let names: string[];\n try { names = await readdir(entry.path); } catch (error) {\n if (isMissing(error)) return [];\n throw error;\n }\n return names.filter(name => !declared.has(name));\n}\n\nasync function current(entry: Entry): Promise<'absent' | 'same' | 'different'> {\n const stat = await lstatOrAbsent(entry.path);\n if (!stat) return 'absent';\n if (entry.kind === 'dir') return stat.isDirectory() ? 'same' : 'different';\n if (entry.kind === 'managed-dir') {\n if (!stat.isDirectory()) return 'different';\n return (await staleChildren(entry)).length === 0 ? 'same' : 'different';\n }\n if (entry.kind === 'link') {\n if (!stat.isSymbolicLink()) return 'different';\n return await readlink(entry.path) === entry.target ? 'same' : 'different';\n }\n if (!stat.isFile()) return 'different';\n if (entry.once) return 'same';\n return await readFile(entry.path, 'utf8') === entry.content ? 'same' : 'different';\n}\n\n/** Everything lives under the room home, which this CLI owns outright. */\nexport async function planEntries(entries: readonly Entry[]): Promise<Operation[]> {\n const operations: Operation[] = [];\n for (const entry of entries) {\n const state = await current(entry);\n operations.push({\n action: state === 'same' ? 'noop' : state === 'absent' ? 'create' : 'update',\n // A managed directory is still a directory to everything that reports operations.\n kind: entry.kind === 'managed-dir' ? 'dir' : entry.kind,\n target: entry.path,\n });\n }\n return operations;\n}\n\n/** Unique so two runs, or a leftover from a failed one, can never collide. */\nfunction tempSibling(path: string): string {\n return join(dirname(path), `.${basename(path)}.paseo-room-${randomBytes(8).toString('hex')}`);\n}\n\n/** A managed file or link may replace only an absent path or the same shape. */\nasync function assertReplaceable(entry: FileEntry | LinkEntry): Promise<void> {\n const stat = await lstatOrAbsent(entry.path);\n if (!stat) return;\n if (entry.kind === 'link') {\n if (!stat.isSymbolicLink()) refuse(entry.path, 'a symbolic link', stat);\n return;\n }\n if (!stat.isFile()) refuse(entry.path, 'a regular file', stat);\n}\n\n/** Build beside the target and rename, so a reader never sees a half-written path. */\nasync function replaceAtomically(entry: FileEntry | LinkEntry): Promise<void> {\n const temp = tempSibling(entry.path);\n try {\n if (entry.kind === 'link') await symlink(entry.target, temp);\n else {\n await writeFile(temp, entry.content, { mode: FILE_MODE });\n await chmod(temp, FILE_MODE);\n }\n await rename(temp, entry.path);\n } catch (error) {\n await rm(temp, { force: true });\n throw error;\n }\n}\n\nasync function applyDirectory(path: string): Promise<void> {\n const stat = await lstatOrAbsent(path);\n if (stat && !stat.isDirectory()) refuse(path, 'a directory', stat);\n await mkdir(path, { recursive: true, mode: DIR_MODE });\n}\n\n/**\n * Creates the projection, migrating the one declared legacy symlink by unlinking the\n * link alone, and removes only undeclared children that are links or files. An\n * unrecognized shape — including a real child directory — fails instead of being\n * deleted recursively.\n */\nasync function applyManagedDirectory(entry: ManagedDirEntry): Promise<void> {\n const stat = await lstatOrAbsent(entry.path);\n if (stat?.isSymbolicLink() === true) {\n const target = await readlink(entry.path);\n if (entry.legacyLink === undefined || target !== entry.legacyLink) {\n throw new ManagedPathError(entry.path,\n `Refusing to replace ${entry.path}: this room owns that directory, but it is a symbolic link to ${target}.`,\n MOVE_ASIDE);\n }\n // Unlink the alias only; the operator directory it pointed at is never touched.\n await unlink(entry.path);\n await mkdir(entry.path, { recursive: true, mode: DIR_MODE });\n return;\n }\n if (stat && !stat.isDirectory()) refuse(entry.path, 'a directory this room owns', stat);\n await mkdir(entry.path, { recursive: true, mode: DIR_MODE });\n if (!stat) return;\n for (const name of await staleChildren(entry)) {\n const child = join(entry.path, name);\n const childStat = await lstatOrAbsent(child);\n if (!childStat) continue;\n if (!childStat.isFile() && !childStat.isSymbolicLink()) {\n throw new ManagedPathError(child,\n `Refusing to remove ${child}: this room manages ${entry.path} by name, but that stale child is ${shape(childStat)} rather than a generated file or link.`,\n MOVE_ASIDE);\n }\n await rm(child, { force: true });\n }\n}\n\n/** Rewrites only what differs, so a repeat run costs stats rather than writes. */\nexport async function applyEntries(entries: readonly Entry[]): Promise<void> {\n for (const entry of entries) {\n if (await current(entry) === 'same') continue;\n if (entry.kind === 'dir') {\n await applyDirectory(entry.path);\n continue;\n }\n if (entry.kind === 'managed-dir') {\n await applyManagedDirectory(entry);\n continue;\n }\n await mkdir(dirname(entry.path), { recursive: true, mode: DIR_MODE });\n await assertReplaceable(entry);\n await replaceAtomically(entry);\n }\n}\n\nexport async function exists(path: string): Promise<boolean> {\n try { await lstat(path); return true; } catch { return false; }\n}\n\n/** Which of `names` exist under `home`, probed once for all roles that share them. */\nexport async function existingPaths(home: string, names: readonly string[]): Promise<string[]> {\n const paths = names.map(name => join(home, name));\n const present = await Promise.all(paths.map(exists));\n return paths.filter((_, index) => present[index] === true);\n}\n\nexport async function readIfPresent(path: string): Promise<string | undefined> {\n try { return await readFile(path, 'utf8'); } catch { return undefined; }\n}\n","export const ROLES = ['supervisor', 'lead', 'peer'] as const;\nexport type Role = (typeof ROLES)[number];\n\nexport const AGENT_IDS = ['codex', 'claude', 'pi'] as const;\nexport type AgentId = (typeof AGENT_IDS)[number];\n\n/** Supervisor and Lead orchestrate; Peer executes one brief and gets no room tools. */\nexport const ROLE_PASEO_TOOLS: Record<Role, boolean> = { supervisor: true, lead: true, peer: false };\n\n/**\n * Reasoning effort a seat starts at: Supervisor routes, Lead judges, Peer implements.\n * Deliberately short of the top option on either agent — `ultra` and `ultracode`\n * advertise automatic task delegation, which is a second control plane.\n */\nexport const ROLE_THINKING: Record<Role, string> = { supervisor: 'low', lead: 'high', peer: 'high' };\n\n/**\n * The top option on either agent, which Paseo advertises as maximum reasoning with automatic\n * task delegation. Whether it can still delegate once the room has closed the native\n * multi-agent paths is unverified, so selecting one is reported and never rejected.\n */\nexport const DELEGATING_THINKING = ['ultra', 'ultracode'] as const;\n\n/** Paseo profile appearance encodes the room role, independent of agent runtime. */\nexport const ROLE_ICON: Record<Role, string> = { supervisor: 'eye', lead: 'compass', peer: 'code' };\nexport const ROLE_COLOR: Record<Role, string> = { supervisor: 'violet', lead: 'blue', peer: 'emerald' };\n\n/** Paseo shows these to orchestrating agents, so each one says who may open the seat. */\nexport const ROLE_NOTES: Record<Role, string> = {\n supervisor: 'Human-facing routing seat. Opened by Human, never by another agent; cwd, title and provider label do not prove room membership.',\n lead: 'Sole project technical owner. When opening, copy every present profile launch field. Otherwise reuse only with exact current room Lead provider/mode/workspace evidence plus corroborated ownership. Cwd, title and provider label are not membership. Creates Peer seats only.',\n peer: 'One fresh Lead brief. Open by copying every present profile launch field; require exact current room Peer provider/mode/workspace and paseo.parent-agent-id for its Lead. Cwd, title and provider label are not membership; no orchestration.',\n};\n\nexport function providerId(agent: AgentId, role: Role): string {\n return `${agent}-${role}`;\n}\n/** Distinct from the provider id: a host may already have a profile by that name. */\nexport function profileId(agent: AgentId, role: Role): string {\n return `room-${agent}-${role}`;\n}\nexport function providerLabel(agent: AgentId, role: Role): string {\n const title = (value: string): string => value.charAt(0).toUpperCase() + value.slice(1);\n return `${title(agent)} ${title(role)}`;\n}\n","import { join } from 'node:path';\nimport { z } from 'zod';\nimport { readIfPresent } from './fsops.js';\nimport type { Layout } from './layout.js';\nimport { AGENT_IDS, ROLES, type AgentId, type Role } from './roles.js';\n\nexport const MARKER = 'room.json';\n\nconst markerSchema = z.object({\n version: z.string(),\n agents: z.array(z.enum(AGENT_IDS)).min(1),\n roles: z.array(z.enum(ROLES)).min(1),\n /**\n * The rendered contract generation this room was installed from. Optional because a room\n * written before contract provenance existed has no digest, and such a marker must still\n * parse rather than look like a foreign file.\n */\n contract: z.string().min(1).optional(),\n});\nexport type Marker = z.infer<typeof markerSchema>;\n\n/** Deterministic on purpose: re-running setup must not show a phantom change. */\nexport function renderMarker(\n version: string,\n agents: readonly AgentId[],\n roles: readonly Role[],\n contract?: string,\n): string {\n return JSON.stringify({\n version, agents: [...agents], roles: [...roles],\n ...(contract === undefined ? {} : { contract }),\n } satisfies Marker, null, 2) + '\\n';\n}\n\n/** Records what setup created, so verify and remove touch nothing else. */\nexport async function readMarker(layout: Layout): Promise<Marker | undefined> {\n const source = await readIfPresent(join(layout.roomHome, MARKER));\n if (source === undefined) return undefined;\n try { return markerSchema.parse(JSON.parse(source)); } catch { return undefined; }\n}\n","import { execFile } from 'node:child_process';\nimport { access, constants } from 'node:fs/promises';\nimport { delimiter, isAbsolute, join, resolve } from 'node:path';\nimport { promisify } from 'node:util';\n\nconst run = promisify(execFile);\n\n/**\n * Resolve a command to an absolute executable path on `searchPath`.\n *\n * Deliberately not canonicalised. Version managers point a stable name at a\n * versioned file — `~/.local/bin/claude` at `versions/2.1.267`, mise's\n * `node/latest` at `node/24.15.0` — and the resolved target is deleted by the\n * next upgrade. Providers store this path, so following the link would pin every\n * seat to a binary that stops existing.\n */\nexport async function which(command: string, searchPath: string): Promise<string | undefined> {\n const candidates = isAbsolute(command) || command.includes('/')\n ? [resolve(command)]\n : searchPath.split(delimiter).filter(Boolean).map(entry => join(entry, command));\n for (const candidate of candidates) {\n try {\n await access(candidate, constants.X_OK);\n return candidate;\n } catch { /* try the next PATH entry */ }\n }\n return undefined;\n}\n\nexport interface CommandOutput {\n readonly ok: boolean;\n readonly stdout: string;\n}\n/** Bounded, shell-free probe. Failures are reported, never thrown. */\nexport async function probe(executable: string, args: readonly string[], env: NodeJS.ProcessEnv): Promise<CommandOutput> {\n try {\n const { stdout } = await run(executable, [...args], { env, timeout: 20_000, maxBuffer: 16 * 1024 * 1024, encoding: 'utf8' });\n return { ok: true, stdout };\n } catch {\n return { ok: false, stdout: '' };\n }\n}\n","import { spawn } from 'node:child_process';\nimport { constants } from 'node:os';\nimport { join } from 'node:path';\nimport { lstat } from 'node:fs/promises';\nimport { roleCommand } from './credentials.js';\nimport { resolveLayout, roleHome, type Options } from './layout.js';\nimport { MARKER, readMarker } from './room.js';\nimport { AGENT_IDS, ROLES, type AgentId, type Role } from './roles.js';\nimport { which } from './which.js';\n\nexport const AUTHENTICATION_GUIDE = 'AUTHENTICATION.md';\n/** A truthy empty override suppresses Pi's role-home APPEND_SYSTEM.md discovery. */\nexport const PI_AUTH_ARGV = ['--no-extensions', '--no-approve', '--append-system-prompt', ''] as const;\n\n/** A copy-paste-safe Pi login command that cannot inherit the caller repository cwd. */\nexport function piLoginCommand(rolePath: string, binary: string): string {\n const command = roleCommand({ PI_CODING_AGENT_DIR: rolePath }, binary, PI_AUTH_ARGV);\n return `cd ${roleCommand({}, rolePath)} && ${command}`;\n}\n\nexport interface LoginOutput {\n readonly stdout: (text: string) => void;\n readonly stderr: (text: string) => void;\n}\n\nexport interface LoginSpawnOptions {\n readonly env: NodeJS.ProcessEnv;\n readonly cwd?: string;\n readonly shell: false;\n readonly stdio: 'inherit';\n}\n\nexport interface LoginChild {\n once(event: 'error', listener: (error: Error) => void): this;\n once(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;\n}\n\nexport type LoginSpawner = (executable: string, argv: readonly string[], options: LoginSpawnOptions) => LoginChild;\n\nconst spawnLogin: LoginSpawner = (executable, argv, options) => spawn(executable, [...argv], options);\n\nfunction title(value: string): string {\n return value.charAt(0).toUpperCase() + value.slice(1);\n}\n\nfunction loginInvocation(agent: AgentId, rolePath: string, binary: string): {\n readonly env: Readonly<Record<string, string>>;\n readonly argv: readonly string[];\n readonly cwd?: string;\n readonly command: string;\n} {\n if (agent === 'codex') {\n const env = { CODEX_HOME: rolePath };\n const argv = ['login'] as const;\n return { env, argv, command: roleCommand(env, binary, argv) };\n }\n if (agent === 'claude') {\n const env = { CLAUDE_CONFIG_DIR: rolePath, CLAUDE_SECURESTORAGE_CONFIG_DIR: rolePath };\n const argv = ['auth', 'login'] as const;\n return { env, argv, command: roleCommand(env, binary, argv) };\n }\n const env = { PI_CODING_AGENT_DIR: rolePath };\n const argv = PI_AUTH_ARGV;\n return { env, argv, cwd: rolePath, command: piLoginCommand(rolePath, binary) };\n}\n\n/** Deterministic, secret-free instructions using setup's resolved executables. */\nexport function renderAuthenticationGuide(\n roomHome: string,\n binaries: Readonly<Partial<Record<AgentId, string>>>,\n agents: readonly AgentId[],\n roles: readonly Role[],\n): string {\n const lines = [\n '# Role authentication',\n '',\n 'Setup and verify do not validate authentication, inspect credential contents, query keyrings,',\n 'or test token freshness. Run the command for each role you want to authenticate.',\n '',\n ];\n for (const agent of agents) {\n const binary = binaries[agent];\n if (!binary) throw new Error(`Cannot render authentication guidance without the resolved ${agent} executable.`);\n lines.push(`## ${agent === 'claude' ? 'Claude Code' : title(agent)}`, '');\n for (const role of roles) {\n const invocation = loginInvocation(agent, join(roomHome, 'roles', agent, role), binary);\n lines.push(`### ${title(role)}`, '', '```sh', invocation.command, '```', '');\n if (agent === 'pi') {\n lines.push('Run `/login`, then exit Pi when authentication completes. This minimal interactive',\n 'login session starts in the role home, not the caller repository, disables extension discovery and',\n 'approval files, and suppresses role-home APPEND_SYSTEM.md discovery;',\n 'it is not equivalent to launching the room seat through Paseo.', '');\n }\n }\n }\n return `${lines.join('\\n').trimEnd()}\\n`;\n}\n\nasync function realDirectory(path: string): Promise<'directory' | 'missing' | 'unsafe'> {\n try {\n return (await lstat(path)).isDirectory() ? 'directory' : 'unsafe';\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === 'ENOENT' ? 'missing' : 'unsafe';\n }\n}\n\nfunction usageError(output: LoginOutput, detail: string): number {\n output.stderr(`paseo-room auth login: ${detail}\\n`);\n return 2;\n}\n\nexport interface LoginOptions extends Options {\n readonly env?: NodeJS.ProcessEnv;\n readonly isTTY: boolean;\n readonly spawn?: LoginSpawner;\n}\n\n/** Launch one vendor's normal interactive login without touching credential stores itself. */\nexport async function loginRole(\n agentValue: string,\n roleValue: string,\n options: LoginOptions,\n output: LoginOutput,\n): Promise<number> {\n const agent = AGENT_IDS.find(value => value === agentValue);\n if (!agent) return usageError(output, `unknown agent \"${agentValue}\"; expected codex, claude, or pi.`);\n const role = ROLES.find(value => value === roleValue);\n if (!role) return usageError(output, `unknown role \"${roleValue}\"; expected supervisor, lead, or peer.`);\n if (!options.isTTY) {\n output.stderr('paseo-room auth login requires interactive stdin, stdout, and stderr terminals.\\n');\n return 1;\n }\n\n const env = options.env ?? process.env;\n const layout = resolveLayout(options, env);\n if (await realDirectory(layout.roomHome) !== 'directory') {\n output.stderr(`No room found at ${layout.roomHome}. Run: paseo-room setup --apply\\n`);\n return 1;\n }\n try {\n if (!(await lstat(join(layout.roomHome, MARKER))).isFile()) throw new Error('not a regular marker');\n } catch {\n output.stderr(`No valid room marker found at ${join(layout.roomHome, MARKER)}. Run: paseo-room setup --apply\\n`);\n return 1;\n }\n const marker = await readMarker(layout);\n if (!marker) {\n output.stderr(`No valid room marker found at ${join(layout.roomHome, MARKER)}. Run: paseo-room setup --apply\\n`);\n return 1;\n }\n if (!marker.agents.includes(agent)) {\n output.stderr(`${title(agent)} is not selected in this room. Re-run setup with --agent ${agent} --apply.\\n`);\n return 1;\n }\n if (!marker.roles.includes(role)) {\n output.stderr(`${title(role)} is not installed for ${agent} in this room. Re-run setup --apply.\\n`);\n return 1;\n }\n const rolePath = roleHome(layout, agent, role);\n for (const path of [join(layout.roomHome, 'roles'), join(layout.roomHome, 'roles', agent), rolePath]) {\n if (await realDirectory(path) !== 'directory') {\n output.stderr(`The selected ${agent} ${role} role is not safely installed at ${rolePath}. Run: paseo-room setup --apply\\n`);\n return 1;\n }\n }\n\n const binary = await which(layout.bin[agent], layout.searchPath);\n if (!binary) {\n output.stderr(`${title(agent)} executable not found. Install it, or pass --${agent}-bin /path/to/${agent}.\\n`);\n return 1;\n }\n const invocation = loginInvocation(agent, rolePath, binary);\n if (agent === 'pi') {\n output.stdout(`Starting a minimal interactive Pi login session for ${role} in its role home. Run /login, then exit Pi when authentication completes.\\n`);\n output.stdout('Extensions and approval files are disabled, and role APPEND_SYSTEM.md discovery is suppressed.\\n');\n output.stdout('This is not a room-equivalent Paseo launch.\\n');\n } else {\n output.stdout(`Starting ${agent === 'claude' ? 'Claude Code' : 'Codex'} login for ${role}.\\n`);\n }\n\n const childEnv = { ...env, ...invocation.env };\n const launch = options.spawn ?? spawnLogin;\n return new Promise(resolve => {\n let settled = false;\n const finish = (code: number): void => {\n if (settled) return;\n settled = true;\n resolve(code);\n };\n let child: LoginChild;\n try {\n child = launch(binary, invocation.argv, {\n env: childEnv,\n ...(invocation.cwd === undefined ? {} : { cwd: invocation.cwd }),\n shell: false,\n stdio: 'inherit',\n });\n } catch (error) {\n const detail = error instanceof Error ? error.message : 'unknown error';\n output.stderr(`Could not start ${agent} login: ${detail}\\n`);\n finish(1);\n return;\n }\n child.once('error', error => {\n output.stderr(`Could not start ${agent} login: ${error.message}\\n`);\n finish(1);\n });\n child.once('close', (code, signal) => {\n if (code !== null) {\n finish(code);\n return;\n }\n if (signal) {\n const signalNumber = constants.signals[signal];\n const mapped = typeof signalNumber === 'number' ? 128 + signalNumber : 1;\n output.stderr(`${title(agent)} login ended from signal ${signal}; returning ${String(mapped)}.\\n`);\n finish(mapped);\n return;\n }\n output.stderr(`${title(agent)} login ended without an exit code or signal.\\n`);\n finish(1);\n });\n });\n}\n","import { readFileSync } from 'node:fs';\n\nexport const PROMPT_ASSETS = {\n documents: {\n supervisor: { path: 'documents/supervisor.md', kind: 'head' },\n lead: { path: 'documents/lead.md', kind: 'head' },\n peer: { path: 'documents/peer.md', kind: 'head' },\n workspace: { path: 'documents/workspace.md', kind: 'head' },\n },\n contract: {\n humanAuthority: { path: 'contract/shared/human-authority.md', kind: 'section' },\n workspaceProtocolPrecedence: { path: 'contract/shared/workspace-protocol-precedence.md', kind: 'section' },\n evidenceAndEventWaiting: { path: 'contract/shared/evidence-and-event-waiting.md', kind: 'section' },\n scopeAndUnrelatedWork: { path: 'contract/shared/scope-and-unrelated-work.md', kind: 'section' },\n directiveIntegrity: { path: 'contract/supervisor/directive-integrity.md', kind: 'section' },\n technicalNonInterference: { path: 'contract/supervisor/technical-non-interference.md', kind: 'section' },\n leadDiscoveryAndRecovery: { path: 'contract/supervisor/lead-discovery-and-recovery.md', kind: 'section' },\n observationAndAdvice: { path: 'contract/supervisor/observation-and-advice.md', kind: 'section' },\n escalationBoundaries: { path: 'contract/supervisor/escalation-boundaries.md', kind: 'section' },\n projectTechnicalOwnership: { path: 'contract/lead/project-technical-ownership.md', kind: 'section' },\n movingWriteOwnership: { path: 'contract/lead/moving-write-ownership.md', kind: 'section' },\n completePeerBrief: { path: 'contract/lead/complete-peer-brief.md', kind: 'section' },\n challengeSignals: { path: 'contract/shared-lead-peer/challenge-signals.md', kind: 'section' },\n technicalAcceptance: { path: 'contract/lead/technical-acceptance.md', kind: 'section' },\n independentReview: { path: 'contract/lead/independent-review.md', kind: 'section' },\n peerSeatLifecycle: { path: 'contract/lead/peer-seat-lifecycle.md', kind: 'section' },\n boundedOutcome: { path: 'contract/peer/bounded-outcome.md', kind: 'section' },\n independentJudgment: { path: 'contract/peer/independent-judgment.md', kind: 'section' },\n writingAndReviewScope: { path: 'contract/peer/writing-and-review-scope.md', kind: 'section' },\n noOrchestration: { path: 'contract/peer/no-orchestration.md', kind: 'section' },\n reproducibleHandoff: { path: 'contract/peer/reproducible-handoff.md', kind: 'section' },\n noSelfAcceptance: { path: 'contract/peer/no-self-acceptance.md', kind: 'section' },\n },\n workspace: {\n topology: { path: 'workspace/topology.md', kind: 'section' },\n verification: { path: 'workspace/verification.md', kind: 'section' },\n review: { path: 'workspace/review.md', kind: 'section' },\n repositoryConventions: { path: 'workspace/repository-conventions.md', kind: 'section' },\n },\n pi: {\n communicationStyle: { path: 'pi/communication-style.md', kind: 'capsule' },\n runtime: { path: 'pi/runtime.md', kind: 'capsule' },\n },\n} as const;\n\nexport type PromptAssetGroup = keyof typeof PROMPT_ASSETS;\nexport type PromptAssetKey<Group extends PromptAssetGroup> = keyof (typeof PROMPT_ASSETS)[Group];\nexport type ContractKey = PromptAssetKey<'contract'>;\nexport type WorkspaceKey = PromptAssetKey<'workspace'>;\nexport type DocumentKey = PromptAssetKey<'documents'>;\nexport type PiPromptKey = PromptAssetKey<'pi'>;\n\ntype PromptAssetKind = 'head' | 'section' | 'capsule';\ninterface PromptAssetDefinition {\n readonly path: string;\n readonly kind: PromptAssetKind;\n}\n\nexport class PromptAssetError extends Error {\n readonly logicalAsset: string;\n readonly assetUrl: URL;\n\n constructor(logicalAsset: string, assetUrl: URL, detail: string, options?: ErrorOptions) {\n super(`Prompt asset ${logicalAsset} at ${assetUrl.pathname} ${detail} Reinstall paseo-room and try again.`, options);\n this.name = 'PromptAssetError';\n this.logicalAsset = logicalAsset;\n this.assetUrl = assetUrl;\n }\n}\n\nconst cache = new Map<string, string>();\n\nfunction definition<Group extends PromptAssetGroup>(\n group: Group,\n key: PromptAssetKey<Group>,\n): PromptAssetDefinition {\n const assets = PROMPT_ASSETS[group] as Readonly<Record<string, PromptAssetDefinition>>;\n const asset = assets[String(key)];\n if (asset === undefined) throw new Error(`Unknown prompt asset ${group}.${String(key)}.`);\n return asset;\n}\n\nfunction headingCount(source: string, level: 1 | 2): number {\n const prefix = level === 1 ? '# ' : '## ';\n return source.split('\\n').filter(line => line.startsWith(prefix)).length;\n}\n\nfunction validateHeadOrCapsule(source: string, kind: 'head' | 'capsule'): string {\n const trimmed = source.trimEnd();\n if (!trimmed.trim()) throw new Error('is empty.');\n const firstLine = trimmed.split('\\n', 1)[0] ?? '';\n if (!/^# \\S.*$/.test(firstLine) || headingCount(trimmed, 1) !== 1) {\n throw new Error(`${kind === 'head' ? 'document head' : 'Pi capsule'} must begin with exactly one H1 heading.`);\n }\n return trimmed;\n}\n\nfunction validateSection(source: string): string {\n const trimmed = source.trimEnd();\n if (!trimmed.trim()) throw new Error('is empty.');\n const lines = trimmed.split('\\n');\n const heading = lines.shift() ?? '';\n if (!/^## \\S.*$/.test(heading) || headingCount(trimmed, 2) !== 1) {\n throw new Error('section must begin with exactly one H2 heading.');\n }\n if (lines.some(line => /^#{1,6}\\s/.test(line))) {\n throw new Error('section must not contain additional Markdown headings.');\n }\n const body = lines.join('\\n').trim();\n if (!body) throw new Error('section must contain at least one non-empty statement.');\n const statements = body.split(/\\n\\s*\\n/).map(statement =>\n statement.split('\\n').map(line => line.trim()).join(' '),\n );\n if (statements.some(statement => !statement)) {\n throw new Error('section must contain only non-empty statements.');\n }\n return `${heading}\\n${statements.map(statement => `- ${statement}`).join('\\n')}`;\n}\n\nexport function loadPromptAsset<Group extends PromptAssetGroup>(\n group: Group,\n key: PromptAssetKey<Group>,\n): string {\n const logicalAsset = `${group}.${String(key)}`;\n const cached = cache.get(logicalAsset);\n if (cached !== undefined) return cached;\n\n const asset = definition(group, key);\n const assetUrl = new URL(`./prompts/${asset.path}`, import.meta.url);\n try {\n const source = readFileSync(assetUrl, 'utf8');\n if (source.includes('\\uFFFD')) throw new Error('is not valid UTF-8 text.');\n const validated = asset.kind === 'section'\n ? validateSection(source)\n : validateHeadOrCapsule(source, asset.kind);\n cache.set(logicalAsset, validated);\n return validated;\n } catch (error) {\n if (error instanceof PromptAssetError) throw error;\n const detail = error instanceof Error ? error.message : 'could not be read.';\n throw new PromptAssetError(logicalAsset, assetUrl, detail, { cause: error });\n }\n}\n","import { createHash } from 'node:crypto';\nimport { ROLES, type Role } from '../roles.js';\nimport {\n loadPromptAsset,\n type ContractKey,\n type WorkspaceKey,\n} from './prompts.js';\n\nexport type InstructionKind = Role | 'workspace';\n\nconst SHARED_KEYS = [\n 'humanAuthority',\n 'workspaceProtocolPrecedence',\n 'evidenceAndEventWaiting',\n 'scopeAndUnrelatedWork',\n] as const satisfies readonly ContractKey[];\n\nconst ROLE_KEYS = {\n supervisor: [\n 'directiveIntegrity',\n 'technicalNonInterference',\n 'leadDiscoveryAndRecovery',\n 'observationAndAdvice',\n 'escalationBoundaries',\n ],\n lead: [\n 'projectTechnicalOwnership',\n 'movingWriteOwnership',\n 'completePeerBrief',\n 'challengeSignals',\n 'technicalAcceptance',\n 'independentReview',\n 'peerSeatLifecycle',\n ],\n // Peer needs Challenge Signals as well as its own obligations.\n peer: [\n 'challengeSignals',\n 'boundedOutcome',\n 'independentJudgment',\n 'writingAndReviewScope',\n 'noOrchestration',\n 'reproducibleHandoff',\n 'noSelfAcceptance',\n ],\n} as const satisfies Record<Role, readonly ContractKey[]>;\n\nconst ALL_PROTOCOL_KEYS = [\n 'topology',\n 'verification',\n 'review',\n 'repositoryConventions',\n] as const satisfies readonly WorkspaceKey[];\n\n// Topology is Lead's decision and Supervisor's to audit. No Orchestration forbids Peer to\n// infer room topology, so handing Peer the topology rules would contradict its own contract.\nconst PROTOCOL_KEYS = {\n supervisor: ALL_PROTOCOL_KEYS,\n lead: ALL_PROTOCOL_KEYS,\n peer: ['verification', 'review', 'repositoryConventions'],\n} as const satisfies Record<Role, readonly WorkspaceKey[]>;\n\nexport function instructionKeys(role: Role): readonly ContractKey[] {\n // Every role carries the shared authority contract plus its own obligations.\n return [...SHARED_KEYS, ...ROLE_KEYS[role]];\n}\n\nexport function protocolKeys(role: Role): readonly WorkspaceKey[] {\n return PROTOCOL_KEYS[role];\n}\n\nfunction protocol(keys: readonly WorkspaceKey[]): string[] {\n return [\n loadPromptAsset('documents', 'workspace'),\n ...keys.map(key => loadPromptAsset('workspace', key)),\n ];\n}\n\nexport function renderInstructions(kind: InstructionKind): string {\n if (kind === 'workspace') return protocol(ALL_PROTOCOL_KEYS).join('\\n\\n') + '\\n';\n return [\n loadPromptAsset('documents', kind),\n ...instructionKeys(kind).map(key => loadPromptAsset('contract', key)),\n ...protocol(protocolKeys(kind)),\n ].join('\\n\\n') + '\\n';\n}\n\n/** Every document the room composes, in one fixed order, so a digest over them is stable. */\nexport const INSTRUCTION_KINDS = [...ROLES, 'workspace'] as const satisfies readonly InstructionKind[];\n\n/**\n * Identifies the rendered contract generation a room was installed from.\n *\n * Derived from the composed documents rather than the package version: two packages that\n * render identical contracts are the same generation, and editing one prompt asset without a\n * release still changes the digest. Truncated because this is provenance an operator compares\n * by eye, not a security claim.\n */\nexport function contractDigest(): string {\n const hash = createHash('sha256');\n for (const kind of INSTRUCTION_KINDS) hash.update(`${kind}\\u0000${renderInstructions(kind)}\\u0000`);\n return `sha256:${hash.digest('hex').slice(0, 16)}`;\n}\n","import { fail, type Check } from '../result.js';\n\n/**\n * The bounded heuristic: `paseo` as a whole identifier or path token, including a\n * lower-to-upper camel-case boundary. It is not embedded in a larger word, so `paseo`,\n * `paseo-mcp`, `/opt/paseo/bin/serve` and `paseoRoom` match while `grapaseo`,\n * `paseonaut` and `PASEONAUT` do not.\n *\n * This recognizes an obvious configuration collision and says why it matched. It is not a\n * scanner for a hostile or obfuscated endpoint, and matching nothing proves nothing.\n */\nconst PASEO_TOKEN = /(?<![\\p{L}\\p{N}])[Pp][Aa][Ss][Ee][Oo](?=$|[^\\p{L}\\p{N}]|\\p{Lu}\\p{Ll})/u;\n\n/** Declaration fields that name what a server runs or connects to. */\nconst VALUE_FIELDS = ['command', 'url', 'serverUrl', 'httpUrl', 'endpoint'] as const;\n/** Declaration fields that carry a list of such values. */\nconst LIST_FIELDS = ['args'] as const;\n\n/** One recognizable declaration, kept so the diagnostic can state its own evidence. */\nexport interface McpMatch {\n readonly server: string;\n /** `name`, or the declaration field that carried the token. */\n readonly field: 'name' | (typeof VALUE_FIELDS)[number] | (typeof LIST_FIELDS)[number];\n readonly value: string;\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\n/** An MCP declaration map exactly as an already-parsed config carries it. */\nexport function serverTable(value: unknown): Record<string, unknown> {\n return asRecord(value) ?? {};\n}\n\n/** Names one side declares and the other does not, in both directions. */\nexport interface NameDivergence {\n /** Declared for the operator but absent from the compared side. */\n readonly missing: readonly string[];\n /** Declared by the compared side but no longer by the operator. */\n readonly extra: readonly string[];\n}\n\n/**\n * Compare two declaration maps by server name alone. Used for seed-once runtime state the\n * room must not synchronize: a name difference is reportable, and nothing about what those\n * servers run is compared, copied, or written back.\n */\nexport function serverNameDivergence(\n operator: Readonly<Record<string, unknown>>,\n compared: Readonly<Record<string, unknown>>,\n): NameDivergence | undefined {\n const operatorNames = new Set(Object.keys(operator));\n const comparedNames = new Set(Object.keys(compared));\n const missing = [...operatorNames].filter(name => !comparedNames.has(name)).sort();\n const extra = [...comparedNames].filter(name => !operatorNames.has(name)).sort();\n return missing.length === 0 && extra.length === 0 ? undefined : { missing, extra };\n}\n\n/**\n * The declaration maps inside a JSON configuration file, read through the named keys only:\n * nothing else in the document — history, credentials, runtime state — is inspected.\n *\n * Every named key is merged, in the order given, because an agent that accepts more than one\n * key loads all of them: stopping at the first table would let a benign one hide a Paseo\n * declaration under a later key. A name declared twice keeps the earlier key's entry at its\n * own name and the later one under a key-qualified name, so no declaration is lost. Invalid\n * JSON, a non-object root, or a named declaration value that is not an object is rejected:\n * an unparseable source cannot truthfully be reported as inspected and clean.\n */\nexport function jsonServerTable(source: string | undefined, keys: readonly string[]): Record<string, unknown> {\n if (source === undefined) return {};\n const root = asRecord(JSON.parse(source));\n if (!root) throw new TypeError('MCP configuration must be a JSON object.');\n const merged: Record<string, unknown> = {};\n for (const key of keys) {\n const value = root[key];\n if (value === undefined) continue;\n const table = asRecord(value);\n if (!table) throw new TypeError(`${key} must be a JSON object.`);\n for (const [server, declaration] of Object.entries(table)) {\n merged[server in merged ? `${server} (${key})` : server] = declaration;\n }\n }\n return merged;\n}\n\n/** Every recognizably Paseo-related declaration, with the evidence that recognized it. */\nexport function detectPaseoServers(servers: Readonly<Record<string, unknown>>): McpMatch[] {\n const matches: McpMatch[] = [];\n for (const [server, declaration] of Object.entries(servers)) {\n if (PASEO_TOKEN.test(server)) matches.push({ server, field: 'name', value: server });\n const fields = asRecord(declaration);\n if (!fields) continue;\n for (const field of VALUE_FIELDS) {\n const value = fields[field];\n if (typeof value === 'string' && PASEO_TOKEN.test(value)) matches.push({ server, field, value });\n }\n for (const field of LIST_FIELDS) {\n const list = fields[field];\n if (!Array.isArray(list)) continue;\n for (const item of list) {\n if (typeof item === 'string' && PASEO_TOKEN.test(item)) matches.push({ server, field, value: item });\n }\n }\n }\n return matches;\n}\n\nfunction evidence(match: McpMatch): string {\n return match.field === 'name' ? `${match.server} (server name)` : `${match.server} (${match.field}: ${match.value})`;\n}\n\n/**\n * Paseo is the room's only control plane, so a Peer-visible MCP server that looks like a\n * second one fails before anything is applied. The room never edits operator configuration:\n * the fix names the source file and leaves the decision with the operator.\n */\nexport function paseoMcpCheck(id: string, path: string, servers: Readonly<Record<string, unknown>>): Check | undefined {\n const matches = detectPaseoServers(servers);\n if (matches.length === 0) return undefined;\n return fail(id,\n `${path} declares MCP servers that are recognizably Paseo-related: ${matches.map(evidence).join('; ')}.`,\n `Remove or rename those servers in ${path} so no room seat reaches Paseo outside its own seat, then run setup again. paseo-room never edits your MCP configuration, and this name check is a bounded heuristic rather than a sandbox.`);\n}\n","import { readdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { Entry } from '../fsops.js';\nimport type { Role } from '../roles.js';\n\n/** The one operator resource Peer receives as an exact projection rather than an alias. */\nexport const SKILLS = 'skills';\n\n/** A room-owned orchestration skill: advertised to seats that orchestrate, never to Peer. */\nfunction isPaseoSkill(name: string): boolean {\n return name.toLowerCase().startsWith('paseo');\n}\n\n/**\n * Peer has no room tools, so the room also stops loading orchestration surfaces into it.\n * This closes known configuration paths — Peer still has a shell, so it is not containment.\n */\nfunction receivesExecutableResources(role: Role): boolean {\n return role !== 'peer';\n}\n\n/** Names under the operator skills directory; a missing directory is an empty projection. */\nasync function skillNames(path: string): Promise<string[]> {\n try { return (await readdir(path)).filter(name => !isPaseoSkill(name)).sort(); } catch (error) {\n if (error !== null && typeof error === 'object' && 'code' in error && error.code === 'ENOENT') return [];\n throw error;\n }\n}\n\nexport interface RoleResourceInput {\n readonly role: Role;\n /** The role home every generated alias is created inside. */\n readonly target: string;\n /** The operator agent home the shared resources are read from. */\n readonly home: string;\n /** Shared resource basenames in the adapter's declared order, present or not. */\n readonly names: readonly string[];\n /** Absolute operator paths that exist, probed once for every role. */\n readonly shared: readonly string[];\n /** Basenames whose contents can run code, withheld from Peer. */\n readonly executable: readonly string[];\n}\n\n/**\n * Supervisor and Lead keep one alias per shared operator resource that exists, so they never\n * gain a broken link. Peer receives no executable resource, and its `skills` becomes an exact\n * managed directory of links to the non-`paseo*` operator skills, so an inventory change\n * cannot leave it silently stale.\n *\n * Peer's projection is declared even when the operator deleted the whole skills directory:\n * an empty managed directory is what lets a later run remove yesterday's child links, or\n * migrate the legacy whole-directory symlink, instead of leaving them unreconciled.\n */\nexport async function roleResourceEntries(input: RoleResourceInput): Promise<Entry[]> {\n const present = new Set(input.shared);\n const executable = new Set(input.executable);\n const entries: Entry[] = [];\n for (const name of input.names) {\n const path = join(input.home, name);\n const alias = join(input.target, name);\n if (!receivesExecutableResources(input.role)) {\n if (executable.has(name)) continue;\n if (name === SKILLS) {\n const children = present.has(path) ? await skillNames(path) : [];\n entries.push({ kind: 'managed-dir', path: alias, children, legacyLink: path });\n for (const child of children) entries.push({ kind: 'link', path: join(alias, child), target: join(path, child) });\n continue;\n }\n }\n if (!present.has(path)) continue;\n entries.push({ kind: 'link', path: alias, target: path });\n }\n return entries;\n}\n","import { readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport {\n ambientNamesCheck, configuredByNamesCheck, inspectCredentialPath, presentNames, preservedCredentialCheck,\n roleCommand, type CredentialDiagnostic,\n} from '../credentials.js';\nimport type { Layout } from '../layout.js';\nimport { roleHome } from '../layout.js';\nimport type { Entry } from '../fsops.js';\nimport { existingPaths, exists, readIfPresent } from '../fsops.js';\nimport { fail, pass, warn, type Check } from '../result.js';\nimport type { Role } from '../roles.js';\nimport { renderInstructions } from '../room/instructions.js';\nimport { which } from '../which.js';\nimport { jsonServerTable, paseoMcpCheck, serverNameDivergence, type NameDivergence } from './mcp.js';\nimport { roleResourceEntries } from './resources.js';\nimport type { Agent, AgentPlan } from './types.js';\n\n/** Operator-authored resources shared by reference; native agent definitions stay out. */\nconst SHARED = [\n 'skills', 'plugins', 'commands', 'hooks', 'rules',\n 'output-styles', 'keybindings.json', 'themes',\n] as const;\n/** These carry executable prompts, plugin code, and hook programs: never shared with Peer. */\nconst EXECUTABLE = ['plugins', 'commands', 'hooks'] as const;\n/** Claude keeps personal MCP declarations under this one key of its runtime state. */\nconst MCP_KEY = 'mcpServers';\nconst AUTH_ENV = [\n 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_API_KEY', 'CLAUDE_CODE_OAUTH_TOKEN',\n 'CLAUDE_CODE_USE_BEDROCK', 'CLAUDE_CODE_USE_VERTEX', 'CLAUDE_CODE_USE_FOUNDRY',\n] as const;\nconst CONTROL_PLANE_ENV = {\n CLAUDE_CODE_DISABLE_AGENT_VIEW: '1',\n CLAUDE_CODE_DISABLE_WORKFLOWS: '1',\n} as const;\nconst SECURE_STORAGE_ENV = 'CLAUDE_SECURESTORAGE_CONFIG_DIR';\n/** Copied once so a fresh role home does not re-run interactive onboarding. */\nconst SEEDED_KEYS = ['hasCompletedOnboarding', 'theme', 'installMethod', 'userID', MCP_KEY] as const;\n\nfunction asObject(value: unknown): Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value) ? { ...value } : {};\n}\n/** Any unreadable or non-object source is simply an empty starting point. */\nfunction readObject(source: string | undefined): Record<string, unknown> {\n try { return asObject(source === undefined ? {} : JSON.parse(source)); } catch { return {}; }\n}\n\n/** Read optional runtime state, but do not turn an inspection failure into \"no servers\". */\nasync function readStateIfPresent(path: string): Promise<string | undefined> {\n try { return await readFile(path, 'utf8'); } catch (error) {\n if (error !== null && typeof error === 'object' && 'code' in error && error.code === 'ENOENT') return undefined;\n throw error;\n }\n}\n\n/** Keep operator configuration while closing non-Paseo inbound coordination. */\nexport function renderRoleSettings(source: string | undefined, role: Role, secureStorageDir?: string): string {\n const settings = readObject(source);\n // Claude applies settings.env after the launch environment, so repeat these\n // provider pins here after operator values to make them effective.\n settings.env = {\n ...asObject(settings.env),\n ...CONTROL_PLANE_ENV,\n PASEO_ROOM_ROLE: role,\n ...(secureStorageDir === undefined ? {} : { [SECURE_STORAGE_ENV]: secureStorageDir }),\n };\n // These restrictive settings cannot be weakened by another settings scope.\n settings.disableAgentView = true;\n settings.disableWorkflows = true;\n settings.crossSessionInbound = 'refuse';\n return JSON.stringify(settings, null, 2) + '\\n';\n}\n\nexport function renderRoleState(source: string | undefined): string {\n const root = readObject(source);\n const state: Record<string, unknown> = { hasCompletedOnboarding: true };\n for (const key of SEEDED_KEYS) if (key in root) state[key] = root[key];\n return JSON.stringify(state, null, 2) + '\\n';\n}\n\n/** Preserve the operator's global memory, then add the stronger room role contract. */\nexport function renderRoleMemory(source: string | undefined, role: Role): string {\n const operator = source?.trim();\n return operator ? `${operator}\\n\\n${renderInstructions(role)}` : renderInstructions(role);\n}\n\n/** Detect only configuration names; never inspect environment or settings values. */\nexport function claudeAuthMethodNames(settingsSource: string | undefined, envNames: ReadonlySet<string>): string[] {\n const settings = readObject(settingsSource);\n const settingsEnv = asObject(settings.env);\n const names = new Set(presentNames(envNames, AUTH_ENV));\n for (const name of AUTH_ENV) if (Object.hasOwn(settingsEnv, name)) names.add(name);\n if (Object.hasOwn(settings, 'apiKeyHelper')) names.add('apiKeyHelper');\n return [...names];\n}\n\nexport async function claudeCredentialDiagnostic(\n layout: Layout,\n role: Role,\n settingsSource: string | undefined,\n platform: NodeJS.Platform = process.platform,\n binary = 'claude',\n): Promise<CredentialDiagnostic> {\n const home = roleHome(layout, 'claude', role);\n const path = join(home, '.credentials.json');\n const roleEnvironment = { CLAUDE_CONFIG_DIR: home, [SECURE_STORAGE_ENV]: home };\n const login = roleCommand(roleEnvironment, binary, ['auth', 'login']);\n const status = roleCommand(roleEnvironment, binary, ['auth', 'status']);\n const state = await inspectCredentialPath(path);\n const id = `claude.auth.${role}`;\n if (state.kind !== 'missing') {\n return { path, checks: [preservedCredentialCheck({ id, agent: 'Claude', role, path, state, login, status })] };\n }\n const configured = claudeAuthMethodNames(settingsSource, new Set());\n if (configured.length > 0) return { path, checks: [configuredByNamesCheck(id, 'Claude', role, configured)] };\n const ambient = presentNames(layout.envNames, AUTH_ENV);\n if (ambient.length > 0) return { path, checks: [ambientNamesCheck(id, 'Claude', role, ambient)] };\n if (platform === 'darwin') {\n return { path, checks: [{\n id: `${id}.native-keyring-unverifiable`, status: 'warn',\n message: `Claude ${role} auth: native-keyring unverifiable; the current runtime's secure-storage location is pinned to this role home, but no Keychain entry was queried and older runtime behavior was not assumed. Token validity and freshness were not checked.`,\n fix: `Authenticate this role with: ${login}. If that subcommand is unavailable, launch ${roleCommand(roleEnvironment, binary)} and run /login. Check status with: ${status}.`,\n }] };\n }\n return { path, checks: [{\n id: `${id}.login-required`, status: 'warn',\n message: `Claude ${role} auth: login-required; no role-owned .credentials.json or configured environment/static auth method was detected. Authentication was not attempted.`,\n fix: `Authenticate this role with: ${login}. If that subcommand is unavailable, launch ${roleCommand(roleEnvironment, binary)} and run /login. Check status with: ${status}.`,\n }] };\n}\n\n/**\n * `.claude.json` is seeded once and runtime-owned afterwards, so a later change to the\n * operator's own MCP inventory never reaches a role home. That is reported rather than\n * repaired: rewriting the file would discard whatever the runtime has since stored in it.\n * Only declared names are compared — no command, URL, argument, credential or history value\n * is read for this check.\n */\nfunction mcpDriftCheck(role: Role, home: string, path: string, divergence: NameDivergence): Check {\n const parts = [\n ...(divergence.missing.length === 0 ? [] : [`not declared for this role: ${divergence.missing.join(', ')}`]),\n ...(divergence.extra.length === 0 ? [] : [`declared only for this role: ${divergence.extra.join(', ')}`]),\n ];\n return warn(`claude.mcp.drift.${role}`,\n `Claude ${role} MCP server names differ from your own Claude MCP servers (${parts.join('; ')}). ${path} is seeded once and owned by Claude afterwards, so paseo-room did not change it; only server names were compared.`,\n `If this role should have the same servers, add them with: CLAUDE_CONFIG_DIR=${home} claude mcp add ... — or delete ${path} and run setup --apply to reseed it from your current Claude state, which discards that role's other runtime state.`);\n}\n\nexport const claudeAgent: Agent = {\n id: 'claude',\n label: 'Claude Code',\n homeEnv: 'CLAUDE_CONFIG_DIR',\n // Agent View and dynamic workflows have entry points beyond model tool calls.\n providerEnv: CONTROL_PLANE_ENV,\n defaultModeId: 'bypassPermissions',\n // Keep the legacy Task name and block current native orchestration,\n // shared task/cron coordination, and cross-session paths. Paseo alone owns\n // agent lifecycle and coordination.\n pins: {\n disallowedTools: [\n 'Task', 'Agent', 'Workflow', 'ListAgents', 'SendMessage', 'TeamCreate', 'TeamDelete',\n 'TaskCreate', 'TaskGet', 'TaskList', 'TaskUpdate',\n 'CronCreate', 'CronDelete', 'CronList',\n ],\n },\n async build(layout: Layout, roles: readonly Role[]): Promise<AgentPlan> {\n const home = layout.agentHome.claude;\n const binary = await which(layout.bin.claude, layout.searchPath);\n if (!binary) {\n return { entries: [], checks: [fail('claude.bin', 'Claude Code executable not found.', 'Install Claude Code, or pass --claude-bin /path/to/claude.')] };\n }\n if (!(await exists(home))) {\n return { entries: [], checks: [fail('claude.home', `No Claude config directory at ${home}.`, 'Run claude once to initialise it, or pass --claude-home.')] };\n }\n const checks: Check[] = [pass('claude.home', `Claude Code found at ${binary} using ${home}.`)];\n\n const settingsSource = await readIfPresent(join(home, 'settings.json'));\n const memorySource = await readIfPresent(join(home, 'CLAUDE.md'));\n let stateSource: string | undefined;\n let operatorServers: Record<string, unknown>;\n try {\n stateSource = await readStateIfPresent(layout.claudeState);\n // `.claude.json` is runtime-owned after the seed write, so only this one key is interpreted.\n operatorServers = jsonServerTable(stateSource, [MCP_KEY]);\n } catch {\n return { entries: [], checks: [...checks, fail('claude.mcp',\n `Could not read ${layout.claudeState} as a JSON object, so its MCP declarations could not be inspected.`,\n 'Make your Claude state file readable and fix its JSON structure, then run setup again.')] };\n }\n const stateConflict = paseoMcpCheck('claude.mcp', layout.claudeState, operatorServers);\n if (stateConflict) return { entries: [], checks: [...checks, stateConflict] };\n const shared = await existingPaths(home, SHARED);\n const entries: Entry[] = [];\n const credentials: CredentialDiagnostic[] = [];\n const providerEnv: Partial<Record<Role, Readonly<Record<string, string>>>> = {};\n // Held back so a hard conflict found in a later role is never preceded by advice.\n const drift: Check[] = [];\n for (const role of roles) {\n const target = roleHome(layout, 'claude', role);\n const statePath = join(target, '.claude.json');\n // A seeded role home keeps its own copy, so its declarations are checked as well.\n let roleStateSource: string | undefined;\n let roleServers: Record<string, unknown>;\n try {\n roleStateSource = await readStateIfPresent(statePath);\n roleServers = jsonServerTable(roleStateSource, [MCP_KEY]);\n } catch {\n return { entries: [], checks: [...checks, fail(`claude.mcp.${role}`,\n `Could not read ${statePath} as a JSON object, so its MCP declarations could not be inspected.`,\n 'Make that role-owned Claude state file readable and fix its JSON structure, then run setup again.')] };\n }\n const roleConflict = paseoMcpCheck(`claude.mcp.${role}`, statePath, roleServers);\n if (roleConflict) return { entries: [], checks: [...checks, roleConflict] };\n // Only an already-seeded role home can have drifted: an absent one is about to be\n // seeded from the same operator state this run just read.\n if (roleStateSource !== undefined) {\n const divergence = serverNameDivergence(operatorServers, roleServers);\n if (divergence) drift.push(mcpDriftCheck(role, target, statePath, divergence));\n }\n entries.push({ kind: 'dir', path: target });\n entries.push({ kind: 'file', path: join(target, 'CLAUDE.md'), content: renderRoleMemory(memorySource, role) });\n entries.push({ kind: 'file', path: join(target, 'settings.json'), content: renderRoleSettings(settingsSource, role, target) });\n entries.push({ kind: 'file', path: statePath, content: renderRoleState(stateSource), once: true });\n entries.push(...await roleResourceEntries({ role, target, home, names: SHARED, shared, executable: EXECUTABLE }));\n credentials.push(await claudeCredentialDiagnostic(layout, role, settingsSource, process.platform, binary));\n providerEnv[role] = { [SECURE_STORAGE_ENV]: target };\n }\n return { entries, credentials, checks: [...checks, ...drift], binary, providerEnv };\n },\n};\n","import { join } from 'node:path';\nimport { parse, stringify, type TomlTable } from 'smol-toml';\nimport { inspectCredentialPath, preservedCredentialCheck, roleCommand, type CredentialDiagnostic } from '../credentials.js';\nimport type { Layout } from '../layout.js';\nimport { roleHome } from '../layout.js';\nimport type { Entry } from '../fsops.js';\nimport { existingPaths, readIfPresent } from '../fsops.js';\nimport { fail, pass, type Check } from '../result.js';\nimport type { Role } from '../roles.js';\nimport { renderInstructions } from '../room/instructions.js';\nimport { probe, which } from '../which.js';\nimport { paseoMcpCheck, serverTable } from './mcp.js';\nimport { roleResourceEntries } from './resources.js';\nimport type { Agent, AgentPlan } from './types.js';\n\n/** Read-only operator resources every role shares by reference, never by copy. */\nconst SHARED = ['AGENTS.md', 'skills', 'plugins', 'hooks.json'] as const;\n/** Plugins and hooks run operator code, so Peer — which has no room tools — never loads them. */\nconst EXECUTABLE = ['plugins', 'hooks.json'] as const;\nconst CATALOG = 'model-catalog.json';\nexport type CodexCredentialStore = 'file' | 'ephemeral' | 'auto' | 'keyring' | 'unknown';\n\nfunction table(parent: TomlTable, key: string): TomlTable {\n const value = parent[key];\n if (value === undefined || typeof value !== 'object' || Array.isArray(value) || value instanceof Date) {\n return (parent[key] = {});\n }\n return value;\n}\n\n/**\n * Close Codex's native multi-agent features inside one scope: the top-level table, or an\n * active profile, which outranks it.\n */\nfunction pinMultiAgentFeatures(scope: TomlTable): void {\n const features = table(scope, 'features');\n features.multi_agent = false;\n // Newer configs represent v2 as a table; keep that shape rather than writing a\n // boolean at the same key, which would be a TOML conflict.\n if (typeof features.multi_agent_v2 === 'boolean' || features.multi_agent_v2 === undefined) features.multi_agent_v2 = false;\n else table(features, 'multi_agent_v2').enabled = false;\n}\n\nexport interface RoleConfigInput {\n readonly roleDocument: string;\n readonly catalogPath?: string;\n}\n/**\n * Copy the operator's config, then override only the keys the room owns.\n *\n * `model_instructions_file` is deliberately untouched: it *replaces* Codex's base\n * prompt, so writing it would mean vendoring and maintaining a full copy of that\n * prompt. The room contract is additive and belongs in `developer_instructions`.\n */\nexport function renderRoleConfig(source: TomlTable, input: RoleConfigInput): string {\n const config = structuredClone(source);\n config.sandbox_mode = 'danger-full-access';\n config.approval_policy = 'never';\n config.developer_instructions = input.roleDocument;\n if (input.catalogPath) config.model_catalog_json = input.catalogPath;\n // Codex's own multi-agent mode would compete with the room's role contract.\n // `[agents]` stays top-level only: Codex profiles have no such key.\n table(config, 'agents').enabled = false;\n pinMultiAgentFeatures(config);\n // An active profile outranks the top-level keys, so every room-owned key a profile can\n // also carry — sandbox, approval, catalog, features — has to land there too.\n if (typeof config.profile === 'string') {\n const profile = table(table(config, 'profiles'), config.profile);\n profile.sandbox_mode = 'danger-full-access';\n profile.approval_policy = 'never';\n if (input.catalogPath) profile.model_catalog_json = input.catalogPath;\n pinMultiAgentFeatures(profile);\n }\n return stringify(config) + '\\n';\n}\n\nexport function renderCatalog(catalog: unknown): string {\n return JSON.stringify(catalog, (key, value: unknown) => (key === 'multi_agent_version' ? null : value), 2) + '\\n';\n}\n\n/** Facts the captured catalog itself carries. Nothing is inferred beyond them. */\nexport interface CatalogEvidence {\n /** Codex reads the catalog as a JSON object, so any other top-level shape is not one. */\n readonly object: boolean;\n /** How many `multi_agent_version` fields the capture carried, and the copy therefore nulls. */\n readonly markers: number;\n}\n\nexport function catalogEvidence(catalog: unknown): CatalogEvidence {\n let markers = 0;\n const walk = (value: unknown): void => {\n if (Array.isArray(value)) { for (const item of value) walk(item); return; }\n if (value === null || typeof value !== 'object') return;\n for (const [key, nested] of Object.entries(value)) {\n if (key === 'multi_agent_version') markers += 1;\n else walk(nested);\n }\n };\n walk(catalog);\n return { object: catalog !== null && typeof catalog === 'object' && !Array.isArray(catalog), markers };\n}\n\n/** Read only the generated config's non-secret store selector. */\nexport function codexCredentialStore(config: TomlTable): CodexCredentialStore {\n const value = config.cli_auth_credentials_store;\n return value === 'file' || value === 'ephemeral' || value === 'auto' || value === 'keyring'\n ? value\n : 'unknown';\n}\n\nasync function credentialDiagnostic(\n layout: Layout,\n role: Role,\n store: CodexCredentialStore,\n binary: string,\n): Promise<CredentialDiagnostic> {\n const home = roleHome(layout, 'codex', role);\n const path = join(home, 'auth.json');\n const login = roleCommand({ CODEX_HOME: home }, binary, ['login']);\n const status = roleCommand({ CODEX_HOME: home }, binary, ['login', 'status']);\n const state = await inspectCredentialPath(path);\n const id = `codex.auth.${role}`;\n const checks: Check[] = [];\n if (state.kind !== 'missing') {\n checks.push(preservedCredentialCheck({ id, agent: 'Codex', role, path, state, login, status }));\n } else {\n if (store === 'keyring' || store === 'auto') {\n checks.push({\n id: `${id}.native-keyring-unverifiable`, status: 'warn',\n message: `Codex ${role} auth: native-keyring unverifiable; cli_auth_credentials_store is ${store}, and no keyring was queried. Token validity and freshness were not checked.`,\n fix: `Authenticate this role with: ${login}. Check status with: ${status}.`,\n });\n } else {\n const apiKey = layout.envNames.has('OPENAI_API_KEY')\n ? ' OPENAI_API_KEY is present only in the setup process; Codex has not stored it for this role and paseo-room does not copy it into the provider.'\n : '';\n const detail = store === 'ephemeral'\n ? 'cli_auth_credentials_store is ephemeral, so no persistent credential file is expected'\n : `no role-owned auth.json exists${store === 'file' ? ' for the configured file store' : ''}`;\n checks.push({\n id: `${id}.login-required`, status: 'warn',\n message: `Codex ${role} auth: login-required; ${detail}.${apiKey} Authentication was not attempted.`,\n fix: `Authenticate this role with: ${login}. Check status with: ${status}.`,\n });\n }\n }\n if (state.kind !== 'missing' && (store === 'keyring' || store === 'auto')) {\n checks.push({\n id: `${id}.native-keyring-unverifiable`, status: 'warn',\n message: `Codex ${role} auth: native-keyring unverifiable; cli_auth_credentials_store is ${store}, and the preserved auth.json does not prove what the runtime will use. No keyring was queried.`,\n fix: `Check status without exposing credentials: ${status}.`,\n });\n }\n return { path, checks };\n}\n\nexport const codexAgent: Agent = {\n id: 'codex',\n label: 'Codex',\n homeEnv: 'CODEX_HOME',\n defaultModeId: 'full-access',\n // Without these, Paseo's own mode preset (default auto-review) is sent to the\n // app-server and outranks the sandbox/approval keys in the generated config.\n pins: { params: { sandbox_mode: 'danger-full-access', approval_policy: 'never' } },\n async build(layout: Layout, roles: readonly Role[]): Promise<AgentPlan> {\n const checks: Check[] = [];\n const home = layout.agentHome.codex;\n const binary = await which(layout.bin.codex, layout.searchPath);\n if (!binary) {\n return { entries: [], checks: [fail('codex.bin', 'Codex executable not found.', 'Install Codex, or pass --codex-bin /path/to/codex.')] };\n }\n const configPath = join(home, 'config.toml');\n const raw = await readIfPresent(configPath);\n if (raw === undefined) {\n return { entries: [], checks: [fail('codex.home', `No config.toml in ${home}.`, 'Run codex once to initialise it, or pass --codex-home.')] };\n }\n let source: TomlTable;\n try { source = parse(raw); } catch {\n return { entries: [], checks: [fail('codex.config', `Could not read ${configPath} as TOML.`, 'Fix the syntax in your Codex config, then run setup again.')] };\n }\n checks.push(pass('codex.home', `Codex found at ${binary} using ${home}.`));\n // Paseo is the room's only control plane, so a Paseo-looking MCP server fails here,\n // before any managed path is written, rather than being filtered out of the copy.\n const conflict = paseoMcpCheck('codex.mcp', configPath, serverTable(source.mcp_servers));\n if (conflict) return { entries: [], checks: [...checks, conflict] };\n const store = codexCredentialStore(source);\n\n const entries: Entry[] = [];\n const credentials: CredentialDiagnostic[] = [];\n\n // The scrubbed catalog is one of the room's three native multi-agent closures, so a\n // catalog it cannot capture is a build failure, not a silent fall back to the\n // built-in catalog and its collaboration metadata.\n const capture = roleCommand({ CODEX_HOME: home }, binary, ['debug', 'models']);\n const models = await probe(binary, ['debug', 'models'], { HOME: layout.home, CODEX_HOME: home, PATH: layout.searchPath });\n if (!models.ok) {\n return { entries: [], checks: [...checks, fail('codex.catalog',\n 'Codex model catalog unavailable, so native multi-agent metadata cannot be removed.',\n `Run ${capture} to see why it failed, upgrade Codex to a version that prints the JSON catalog, then run setup again.`)] };\n }\n let catalogSource: string;\n let evidence: CatalogEvidence;\n try {\n const parsed: unknown = JSON.parse(models.stdout);\n evidence = catalogEvidence(parsed);\n catalogSource = renderCatalog(parsed);\n } catch {\n return { entries: [], checks: [...checks, fail('codex.catalog',\n 'Codex model catalog was not valid JSON, so native multi-agent metadata cannot be removed.',\n `Check the output of ${capture}, upgrade Codex if it does not print a JSON catalog, then run setup again.`)] };\n }\n // A JSON scalar or array parses but is not a catalog: writing it would point every role\n // at a file Codex cannot load, which is the same closure failure as no catalog at all.\n if (!evidence.object) {\n return { entries: [], checks: [...checks, fail('codex.catalog',\n 'Codex printed valid JSON that is not a model catalog object, so native multi-agent metadata cannot be removed.',\n `Check the output of ${capture}, upgrade Codex to a version that prints the JSON catalog object, then run setup again.`)] };\n }\n checks.push(pass('codex.catalog', evidence.markers === 0\n ? `Codex model catalog captured from ${capture}; it declared no multi_agent_version field, and each role home gets that generated copy instead of Codex's built-in catalog.`\n : `Codex model catalog captured from ${capture}; ${String(evidence.markers)} multi_agent_version field(s) are nulled in the generated copy in each role home.`));\n\n const shared = await existingPaths(home, SHARED);\n for (const role of roles) {\n const target = roleHome(layout, 'codex', role);\n const catalogPath = join(target, CATALOG);\n const roleDocument = renderInstructions(role);\n entries.push({ kind: 'dir', path: target });\n // Codex reads the brief from developer_instructions; this copy is for the operator.\n entries.push({ kind: 'file', path: join(target, 'role-instructions.md'), content: roleDocument });\n entries.push({\n kind: 'file',\n path: join(target, 'config.toml'),\n content: renderRoleConfig(source, { roleDocument, catalogPath }),\n });\n entries.push({ kind: 'file', path: catalogPath, content: catalogSource });\n entries.push(...await roleResourceEntries({ role, target, home, names: SHARED, shared, executable: EXECUTABLE }));\n credentials.push(await credentialDiagnostic(layout, role, store, binary));\n }\n return { entries, credentials, checks, binary };\n },\n};\n","import { spawn } from 'node:child_process';\nimport { mkdtemp, readFile, realpath, rm, stat } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { isAbsolute, join, resolve } from 'node:path';\nimport {\n ambientNamesCheck, inspectCredentialPath, presentNames, preservedCredentialCheck,\n type CredentialDiagnostic,\n} from '../credentials.js';\nimport { piLoginCommand } from '../auth.js';\nimport type { Entry } from '../fsops.js';\nimport { existingPaths } from '../fsops.js';\nimport type { Layout } from '../layout.js';\nimport { contains, roleHome } from '../layout.js';\nimport { fail, pass, type Check } from '../result.js';\nimport type { Role } from '../roles.js';\nimport { renderInstructions } from '../room/instructions.js';\nimport { loadPromptAsset } from '../room/prompts.js';\nimport { which } from '../which.js';\nimport { jsonServerTable, paseoMcpCheck } from './mcp.js';\nimport { roleResourceEntries } from './resources.js';\nimport type { Agent, AgentPlan } from './types.js';\n\nconst PACKAGE_NAME = 'pi-mcp-adapter';\nconst PROBE_ID = 'paseo-room-pi-mcp-probe';\nconst PROBE_TIMEOUT_MS = 10_000;\nconst PROBE_OUTPUT_LIMIT = 1024 * 1024;\nconst SHARED = ['models.json', 'AGENTS.md', 'skills', 'prompts', 'themes', 'keybindings.json', 'mcp.json'] as const;\n/** Pi prompts are its slash commands, so they execute; Peer receives no such resource. */\nconst EXECUTABLE = ['prompts'] as const;\nconst MCP_FILE = 'mcp.json';\n/** Pi accepts either key for its declaration map, so both are read and neither is rewritten. */\nconst MCP_KEYS = ['mcpServers', 'servers'] as const;\n/** Built-in provider key names only; ambient cloud credential files are deliberately not probed. */\nconst AUTH_ENV = [\n 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_OAUTH_TOKEN', 'ANTHROPIC_API_KEY',\n 'OPENAI_API_KEY', 'AZURE_OPENAI_API_KEY', 'GEMINI_API_KEY', 'GOOGLE_CLOUD_API_KEY',\n 'MISTRAL_API_KEY', 'GROQ_API_KEY', 'CEREBRAS_API_KEY', 'XAI_API_KEY',\n 'DEEPSEEK_API_KEY', 'OPENROUTER_API_KEY', 'AI_GATEWAY_API_KEY', 'FIREWORKS_API_KEY',\n 'ZAI_API_KEY', 'MINIMAX_API_KEY', 'OPENCODE_API_KEY', 'KIMI_API_KEY',\n 'COPILOT_GITHUB_TOKEN',\n] as const;\n\nfunction asObject(value: unknown): Record<string, unknown> | undefined {\n return value !== null && typeof value === 'object' && !Array.isArray(value) ? { ...value } : undefined;\n}\n\n/** Copy operator preferences but remove every declaration that can install or load packages. */\nexport function renderPiSettings(source: string | undefined): string {\n const parsed: unknown = source === undefined ? {} : JSON.parse(source);\n const settings = asObject(parsed);\n if (!settings) throw new Error('Pi settings must be a JSON object.');\n delete settings.packages;\n delete settings.extensions;\n return JSON.stringify(settings, null, 2) + '\\n';\n}\n\n/** Preserve the operator append first; room-specific guidance is additive and stronger. */\nexport function renderPiAppend(source: string | undefined, role: Role): string {\n return [\n source?.trim(),\n loadPromptAsset('pi', 'communicationStyle'),\n loadPromptAsset('pi', 'runtime'),\n renderInstructions(role),\n ].filter((part): part is string => Boolean(part)).join('\\n\\n');\n}\n\ninterface ResolvedAdapter {\n readonly entry: string;\n readonly version: string;\n}\n\nfunction adapterFailure(home: string, detail: string): Check {\n return fail('pi.adapter', detail,\n `Install ${PACKAGE_NAME} in ${join(home, 'npm')} with Pi yourself, then run setup again.`);\n}\n\n/** Resolve only Pi's intended global package and its single declared extension entry. */\nexport async function resolvePiAdapter(home: string): Promise<{ readonly adapter?: ResolvedAdapter; readonly check: Check }> {\n const packageRoot = join(home, 'npm', 'node_modules', PACKAGE_NAME);\n const manifestPath = join(packageRoot, 'package.json');\n try {\n const [canonicalRoot, manifestStat, raw] = await Promise.all([\n realpath(packageRoot), stat(manifestPath), readFile(manifestPath, 'utf8'),\n ]);\n if (!manifestStat.isFile()) return { check: adapterFailure(home, `${manifestPath} is not a regular file.`) };\n const manifest = asObject(JSON.parse(raw));\n if (!manifest || manifest.name !== PACKAGE_NAME) {\n return { check: adapterFailure(home, `${manifestPath} does not identify ${PACKAGE_NAME}.`) };\n }\n const pi = asObject(manifest.pi);\n const declared = pi?.extensions;\n if (!Array.isArray(declared) || declared.length !== 1 || typeof declared[0] !== 'string' || !declared[0].trim()) {\n return { check: adapterFailure(home, `${manifestPath} must declare one Pi extension entry.`) };\n }\n const declaration = declared[0];\n if (isAbsolute(declaration)) {\n return { check: adapterFailure(home, `${manifestPath} declares an unsafe absolute extension path.`) };\n }\n const candidate = resolve(packageRoot, declaration);\n const [canonicalEntry, entryStat] = await Promise.all([realpath(candidate), stat(candidate)]);\n if (!contains(canonicalRoot, canonicalEntry) || canonicalEntry === canonicalRoot || !entryStat.isFile()) {\n return { check: adapterFailure(home, `The declared ${PACKAGE_NAME} extension escapes its package or is not a regular file.`) };\n }\n const version = typeof manifest.version === 'string' && manifest.version.trim() ? manifest.version.trim() : 'unknown';\n return {\n adapter: { entry: canonicalEntry, version },\n check: pass('pi.adapter', `${PACKAGE_NAME} ${version} resolved to ${canonicalEntry}.`),\n };\n } catch {\n return { check: adapterFailure(home, `Could not safely resolve ${PACKAGE_NAME} from ${manifestPath}.`) };\n }\n}\n\nexport interface PiProbeOptions {\n readonly timeoutMs?: number;\n readonly outputLimit?: number;\n}\ninterface ProcessResult {\n readonly ok: boolean;\n readonly stdout: string;\n readonly reason?: 'failure' | 'timeout' | 'overflow';\n}\n\nfunction terminateProbe(child: ReturnType<typeof spawn>): void {\n if (child.pid !== undefined) {\n try { process.kill(-child.pid, 'SIGKILL'); } catch { /* the process group may already be gone */ }\n }\n try { child.kill('SIGKILL'); } catch { /* the direct child may already be gone */ }\n child.stdin?.destroy();\n child.stdout?.destroy();\n child.stderr?.destroy();\n}\n\n/** One bounded JSONL request in its own process group and isolated working directory. */\nfunction runProbeProcess(\n executable: string,\n adapterEntry: string,\n env: NodeJS.ProcessEnv,\n options: PiProbeOptions,\n cwd: string,\n): Promise<ProcessResult> {\n const timeoutMs = options.timeoutMs ?? PROBE_TIMEOUT_MS;\n const outputLimit = options.outputLimit ?? PROBE_OUTPUT_LIMIT;\n const args = ['--mode', 'rpc', '--no-session', '--no-extensions', '--extension', adapterEntry, '--no-approve'];\n return new Promise(resolveResult => {\n const child = spawn(executable, args, { cwd, detached: true, env, stdio: ['pipe', 'pipe', 'pipe'] });\n const stdout: Buffer[] = [];\n let bytes = 0;\n let settled = false;\n const finish = (result: ProcessResult): void => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n resolveResult(result);\n };\n const abort = (reason: NonNullable<ProcessResult['reason']>): void => {\n if (settled) return;\n terminateProbe(child);\n finish({ ok: false, stdout: Buffer.concat(stdout).toString('utf8'), reason });\n };\n const capture = (chunk: Buffer, keep: boolean): void => {\n if (settled) return;\n bytes += chunk.length;\n if (bytes > outputLimit) {\n abort('overflow');\n return;\n }\n if (keep) stdout.push(chunk);\n };\n const timer = setTimeout(() => { abort('timeout'); }, timeoutMs);\n child.stdout.on('data', (chunk: Buffer) => { capture(chunk, true); });\n child.stderr.on('data', (chunk: Buffer) => { capture(chunk, false); });\n child.stdout.on('error', () => { abort('failure'); });\n child.stderr.on('error', () => { abort('failure'); });\n child.on('error', () => { abort('failure'); });\n child.on('close', code => {\n const output = Buffer.concat(stdout).toString('utf8');\n finish(code === 0 ? { ok: true, stdout: output } : { ok: false, stdout: output, reason: 'failure' });\n });\n child.stdin.on('error', () => { /* a failed child is reported by close/error */ });\n child.stdin.end(`${JSON.stringify({ id: PROBE_ID, type: 'get_commands' })}\\n`);\n });\n}\n\n/** Pi runs migrations against cwd before RPC, so never probe in the caller's project. */\nasync function runProbe(\n executable: string,\n adapterEntry: string,\n env: NodeJS.ProcessEnv,\n options: PiProbeOptions,\n): Promise<ProcessResult> {\n const createdCwd = await mkdtemp(join(tmpdir(), 'paseo-room-pi-probe-'));\n const cwd = await realpath(createdCwd);\n try {\n return await runProbeProcess(executable, adapterEntry, {\n ...env,\n HOME: cwd,\n PI_CODING_AGENT_DIR: '/dev/null',\n PI_MCP_CONFIG_MODE: 'exclusive',\n PI_OFFLINE: '1',\n }, options, cwd);\n } finally {\n await rm(createdCwd, { force: true, recursive: true });\n }\n}\n\nfunction probeFailure(message: string): Check {\n return fail('pi.capability', message,\n 'Use a Pi and pi-mcp-adapter installation that exposes /mcp through the declared adapter entry.');\n}\n\n/** Authenticate the exact adapter path through Pi's correlated get_commands response. */\nexport async function probePiMcp(\n executable: string,\n adapterEntry: string,\n env: NodeJS.ProcessEnv,\n options: PiProbeOptions = {},\n): Promise<Check> {\n let result: ProcessResult;\n try {\n result = await runProbe(executable, adapterEntry, env, options);\n } catch {\n return probeFailure('Pi capability probe could not create or clean its isolated working directory.');\n }\n if (!result.ok) {\n if (result.reason === 'timeout') return probeFailure('Pi capability probe timed out.');\n if (result.reason === 'overflow') return probeFailure('Pi capability probe exceeded its output limit.');\n return probeFailure('Pi capability probe failed.');\n }\n const correlated: Record<string, unknown>[] = [];\n for (const line of result.stdout.split(/\\r?\\n/).filter(Boolean)) {\n let parsed: unknown;\n try { parsed = JSON.parse(line); } catch { return probeFailure('Pi capability probe returned malformed JSONL.'); }\n const event = asObject(parsed);\n if (!event) return probeFailure('Pi capability probe returned malformed JSONL.');\n if (event.type === 'response' && event.id === PROBE_ID) correlated.push(event);\n }\n if (correlated.length !== 1) return probeFailure('Pi capability probe did not return one correlated get_commands response.');\n const response = correlated[0];\n if (response?.command !== 'get_commands' || response.success !== true) {\n return probeFailure('Pi rejected the get_commands capability probe.');\n }\n const data = asObject(response.data);\n const commands = data?.commands;\n if (!Array.isArray(commands)) return probeFailure('Pi get_commands response was malformed.');\n const matches = commands.map(asObject).filter((command): command is Record<string, unknown> => command?.name === 'mcp');\n if (matches.length !== 1) return probeFailure('Pi did not expose exactly one /mcp command.');\n const command = matches[0];\n if (command?.source !== 'extension') return probeFailure('Pi exposed /mcp from the wrong source.');\n const sourceInfo = asObject(command.sourceInfo);\n if (typeof sourceInfo?.path !== 'string') return probeFailure('Pi did not report the /mcp extension path.');\n try {\n const sourcePath = await realpath(sourceInfo.path);\n if (sourcePath !== adapterEntry) return probeFailure('Pi loaded /mcp from a different extension path.');\n } catch {\n return probeFailure('Pi reported an unresolvable /mcp extension path.');\n }\n return pass('pi.capability', `Pi exposed /mcp from ${adapterEntry}.`);\n}\n\nasync function readPiOptional(path: string): Promise<string | undefined> {\n try {\n return await readFile(path, 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined;\n throw error;\n }\n}\n\nexport async function piCredentialDiagnostic(layout: Layout, role: Role, binary = 'pi'): Promise<CredentialDiagnostic> {\n const home = roleHome(layout, 'pi', role);\n const path = join(home, 'auth.json');\n const launch = piLoginCommand(home, binary);\n const state = await inspectCredentialPath(path);\n const id = `pi.auth.${role}`;\n if (state.kind !== 'missing') {\n return {\n path,\n checks: [preservedCredentialCheck({\n id, agent: 'Pi', role, path, state,\n login: `${launch}; this starts a minimal, non-room-equivalent interactive login session. Run /login, then exit Pi`,\n })],\n };\n }\n const configured = presentNames(layout.envNames, AUTH_ENV);\n if (configured.length > 0) return { path, checks: [ambientNamesCheck(id, 'Pi', role, configured)] };\n return { path, checks: [{\n id: `${id}.login-required`, status: 'warn',\n message: `Pi ${role} auth: login-required; no role-owned auth.json or known provider environment name was detected. Ambient provider auth may exist, but it was not inspected or validated.`,\n fix: `Start a minimal, non-room-equivalent interactive login session with: ${launch}. Run /login, then exit Pi.`,\n }] };\n}\n\nexport const piAgent: Agent = {\n id: 'pi',\n label: 'Pi',\n homeEnv: 'PI_CODING_AGENT_DIR',\n providerEnv: { PI_MCP_CONFIG_MODE: 'exclusive' },\n pins: {},\n async build(layout: Layout, roles: readonly Role[]): Promise<AgentPlan> {\n const home = layout.agentHome.pi;\n const binary = await which(layout.bin.pi, layout.searchPath);\n if (!binary) {\n return { entries: [], checks: [fail('pi.bin', 'Pi executable not found.', 'Install Pi yourself, or pass --pi-bin /path/to/pi.')] };\n }\n try {\n if (!(await stat(home)).isDirectory()) throw new Error('not a directory');\n } catch {\n return { entries: [], checks: [fail('pi.home', `No Pi config directory at ${home}.`, 'Run Pi once to initialise it, or pass --pi-home.')] };\n }\n const resolved = await resolvePiAdapter(home);\n if (!resolved.adapter) return { entries: [], checks: [resolved.check] };\n const capability = await probePiMcp(binary, resolved.adapter.entry, {\n HOME: layout.home,\n PATH: layout.searchPath,\n PI_CODING_AGENT_DIR: '/dev/null',\n PI_OFFLINE: '1',\n });\n if (capability.status === 'fail') return { entries: [], checks: [resolved.check, capability] };\n\n const settingsPath = join(home, 'settings.json');\n let settings: string;\n try { settings = renderPiSettings(await readPiOptional(settingsPath)); } catch {\n return {\n entries: [], checks: [resolved.check, capability,\n fail('pi.settings', `Could not read ${settingsPath} as a JSON object.`,\n 'Make your Pi settings readable and fix any JSON syntax, then run setup again.')],\n };\n }\n const operatorAppendPath = join(home, 'APPEND_SYSTEM.md');\n let operatorAppend: string | undefined;\n try {\n operatorAppend = await readPiOptional(operatorAppendPath);\n } catch {\n return {\n entries: [], checks: [resolved.check, capability,\n fail('pi.append', `Could not read ${operatorAppendPath}.`,\n 'Make your Pi APPEND_SYSTEM.md readable, then run setup again.')],\n };\n }\n const shared = await existingPaths(home, SHARED);\n // The adapter reads this file as its only config source, so a Paseo-looking server here\n // would be a second control plane. Fail before apply; never edit the operator's file.\n const mcpPath = join(home, MCP_FILE);\n let servers: Record<string, unknown>;\n try {\n servers = jsonServerTable(await readPiOptional(mcpPath), MCP_KEYS);\n } catch {\n return {\n entries: [], checks: [resolved.check, capability,\n fail('pi.mcp', `Could not read ${mcpPath} as a JSON object, so its MCP declarations could not be inspected.`,\n 'Make your Pi mcp.json readable and fix its JSON structure, then run setup again.')],\n };\n }\n const conflict = paseoMcpCheck('pi.mcp', mcpPath, servers);\n if (conflict) return { entries: [], checks: [resolved.check, capability, conflict] };\n const entries: Entry[] = [];\n const credentials: CredentialDiagnostic[] = [];\n const argv: Partial<Record<Role, readonly string[]>> = {};\n for (const role of roles) {\n const target = roleHome(layout, 'pi', role);\n const appendPath = join(target, 'APPEND_SYSTEM.md');\n entries.push({ kind: 'dir', path: target });\n entries.push({ kind: 'file', path: join(target, 'settings.json'), content: settings });\n entries.push({ kind: 'file', path: appendPath, content: renderPiAppend(operatorAppend, role) });\n entries.push(...await roleResourceEntries({ role, target, home, names: SHARED, shared, executable: EXECUTABLE }));\n credentials.push(await piCredentialDiagnostic(layout, role, binary));\n argv[role] = ['--no-extensions', '--extension', resolved.adapter.entry, '--no-approve', '--append-system-prompt', appendPath];\n }\n return {\n entries,\n credentials,\n checks: [pass('pi.home', `Pi found at ${binary} using ${home}.`), resolved.check, capability],\n binary,\n argv,\n };\n },\n};\n","import type { PaseoClient, PaseoClientConfig } from '@getpaseo/client';\nimport { gte, valid } from 'semver';\nimport { z } from 'zod';\nimport type { Layout } from './layout.js';\nimport { fail, pass, type Check } from './result.js';\nimport type { Profile, Provider } from './agents/types.js';\nimport type { AgentId } from './roles.js';\nimport { probe, which } from './which.js';\n\nexport const MINIMUM_VERSION = '0.8.0-beta.1';\nexport const PI_MINIMUM_VERSION = '0.8.0';\n\nexport function minimumPaseoVersion(agents: readonly AgentId[]): string {\n return agents.includes('pi') || agents.includes('claude') ? PI_MINIMUM_VERSION : MINIMUM_VERSION;\n}\n\nconst statusSchema = z.object({\n listen: z.string().min(1),\n localDaemon: z.enum(['running', 'stopped', 'stale_pid', 'unresponsive']),\n cliVersion: z.string(),\n daemonVersion: z.string().nullable(),\n});\n\nexport interface Daemon {\n readonly url: string;\n readonly version: string;\n}\nexport interface DaemonResult {\n readonly checks: readonly Check[];\n readonly daemon?: Daemon;\n}\n\nexport function normalizeUrl(listen: string): string | undefined {\n const match = /^(?:ws:\\/\\/)?([^:/]+|\\[[^\\]]+\\]):(\\d+)$/.exec(listen.trim());\n if (!match) return undefined;\n const [, host = '', port = ''] = match;\n const local = ['localhost', '127.0.0.1', '0.0.0.0', '[::1]', '[::]'].includes(host) ? '127.0.0.1' : host;\n return `ws://${local}:${port}`;\n}\n\n/** The whole compatibility story: is Paseo running, and is it new enough? */\nexport function assessStatus(raw: unknown, minimumVersion = MINIMUM_VERSION): DaemonResult {\n const parsed = statusSchema.safeParse(raw);\n if (!parsed.success) {\n return { checks: [fail('paseo.status', 'Paseo status output was not understood.', 'Upgrade Paseo, then run: paseo daemon status --json')] };\n }\n const status = parsed.data;\n if (status.localDaemon !== 'running') {\n return { checks: [fail('paseo.daemon', `Paseo daemon is ${status.localDaemon}.`, 'Start it with: paseo daemon start')] };\n }\n const cli = valid(status.cliVersion);\n const daemon = status.daemonVersion === null ? null : valid(status.daemonVersion);\n if (!cli || !daemon) {\n return { checks: [fail('paseo.version', 'Paseo did not report a usable version.', 'Upgrade Paseo to a release that reports semver versions.')] };\n }\n if (cli !== daemon) {\n return { checks: [fail('paseo.version', `Paseo CLI is ${cli} but the running daemon is ${daemon}.`, 'Restart the daemon with: paseo daemon restart')] };\n }\n if (!gte(daemon, minimumVersion)) {\n return { checks: [fail('paseo.version', `Paseo ${daemon} is older than the required ${minimumVersion}.`, 'Upgrade Paseo, then run setup again.')] };\n }\n const url = normalizeUrl(status.listen);\n if (!url) {\n return { checks: [fail('paseo.listen', `Paseo listen address ${status.listen} was not understood.`, 'Use a host:port listen address in the Paseo config.')] };\n }\n return { checks: [pass('paseo.version', `Paseo ${daemon} is running on ${url} (compatible, needs >= ${minimumVersion}).`)], daemon: { url, version: daemon } };\n}\n\nexport async function checkDaemon(layout: Layout, env: NodeJS.ProcessEnv = process.env, minimumVersion = MINIMUM_VERSION): Promise<DaemonResult> {\n const binary = await which(layout.bin.paseo, layout.searchPath);\n if (!binary) {\n return { checks: [fail('paseo.bin', 'Paseo executable not found.', 'Install Paseo, or pass --paseo-bin /path/to/paseo.')] };\n }\n const output = await probe(binary, ['daemon', 'status', '--json'], {\n HOME: layout.home, PASEO_HOME: layout.paseoHome, PATH: layout.searchPath,\n ...(env.PASEO_PASSWORD === undefined ? {} : { PASEO_PASSWORD: env.PASEO_PASSWORD }),\n });\n if (!output.ok) {\n return { checks: [fail('paseo.status', 'Could not read Paseo daemon status.', 'Run: paseo daemon status --json')] };\n }\n try { return assessStatus(JSON.parse(output.stdout), minimumVersion); }\n catch { return assessStatus(undefined, minimumVersion); }\n}\n\nconst configSchema = z.object({\n config: z.object({\n providers: z.record(z.string(), z.unknown()).optional(),\n // Read loosely: entries carry operator fields the room neither knows nor touches.\n agentProfiles: z.array(z.record(z.string(), z.unknown())).optional(),\n pluginsEnabled: z.boolean().optional(),\n }),\n});\nexport type LiveProfile = Record<string, unknown>;\nexport interface LivePlugin {\n readonly id: string;\n readonly path: string;\n readonly enabled: boolean;\n readonly status: string;\n readonly error?: string | undefined;\n}\n\nexport interface Session {\n readProviders(): Promise<Record<string, unknown>>;\n writeProviders(providers: Readonly<Record<string, Provider>>): Promise<void>;\n removeProviders(ids: readonly string[]): Promise<void>;\n readProfiles(): Promise<readonly LiveProfile[]>;\n /** Paseo has no remove-one call for profiles, so this replaces the whole array. */\n writeProfiles(profiles: readonly LiveProfile[]): Promise<void>;\n pluginsEnabled(): Promise<boolean>;\n listPlugins(): Promise<readonly LivePlugin[]>;\n installPlugin(path: string, id: string): Promise<LivePlugin>;\n reloadPlugin(id: string): Promise<LivePlugin>;\n enablePlugin(id: string): Promise<LivePlugin>;\n removePlugin(id: string): Promise<void>;\n refresh(ids: readonly string[]): Promise<void>;\n}\nexport interface RoomClient extends PaseoClient {\n listPlugins(): Promise<LivePlugin[]>;\n installDirectoryPlugin(path: string, id?: string): Promise<LivePlugin>;\n reloadPlugin(id: string): Promise<LivePlugin>;\n enablePlugin(id: string): Promise<LivePlugin>;\n removePlugin(id: string): Promise<void>;\n}\nexport type ClientFactory = (config: PaseoClientConfig) => RoomClient;\n\n/** One connection per command. No retries, no reconnects, no background state. */\nexport async function withSession<T>(\n daemon: Daemon,\n run: (session: Session) => Promise<T>,\n options: { readonly password?: string; readonly factory?: ClientFactory } = {},\n): Promise<T> {\n const quiet = { debug() { /* silent */ }, info() { /* silent */ }, warn() { /* silent */ }, error() { /* silent */ } };\n // Loaded here so the \"Paseo is not running\" path never pays for the SDK.\n const clientConfig: PaseoClientConfig = {\n url: `${daemon.url}/ws`,\n ...(options.password === undefined ? {} : { password: options.password }),\n appVersion: MINIMUM_VERSION,\n connectTimeoutMs: 10_000,\n reconnect: { enabled: false },\n logger: quiet,\n };\n let client: RoomClient;\n if (options.factory !== undefined) {\n client = options.factory(clientConfig);\n } else {\n const [{ createPaseoApi }, { DaemonClient }] = await Promise.all([\n import('@getpaseo/client'), import('@getpaseo/client/internal/daemon-client'),\n ]);\n const raw = new DaemonClient({ ...clientConfig, clientId: `paseo-room-${String(process.pid)}`, clientType: 'cli' });\n client = {\n ...createPaseoApi(raw),\n connect: () => raw.connect(), close: () => raw.close(),\n ensureConnected: () => { raw.ensureConnected(); }, getConnectionState: () => raw.getConnectionState(),\n listPlugins: () => raw.listPlugins(),\n installDirectoryPlugin: (path, id) => raw.installDirectoryPlugin(path, id),\n reloadPlugin: id => raw.reloadPlugin(id), enablePlugin: id => raw.enablePlugin(id),\n removePlugin: id => raw.removePlugin(id),\n };\n }\n try {\n await client.connect();\n return await run({\n async readProviders() {\n const response = configSchema.parse(await client.config.get());\n return response.config.providers ?? {};\n },\n async writeProviders(providers) {\n await client.config.patch({ providers } as unknown as Parameters<PaseoClient['config']['patch']>[0]);\n },\n async removeProviders(ids) {\n await client.config.patch({ removeProviders: [...ids] });\n },\n async readProfiles() {\n const response = configSchema.parse(await client.config.get());\n return response.config.agentProfiles ?? [];\n },\n async writeProfiles(profiles) {\n await client.config.patch({ agentProfiles: [...profiles] } as unknown as Parameters<PaseoClient['config']['patch']>[0]);\n },\n async pluginsEnabled() {\n const response = configSchema.parse(await client.config.get());\n return response.config.pluginsEnabled === true;\n },\n async listPlugins() {\n return await client.listPlugins();\n },\n async installPlugin(path, id) {\n return await client.installDirectoryPlugin(path, id);\n },\n async reloadPlugin(id) {\n return await client.reloadPlugin(id);\n },\n async enablePlugin(id) {\n return await client.enablePlugin(id);\n },\n async removePlugin(id) {\n await client.removePlugin(id);\n },\n async refresh(ids) {\n await client.providers.refresh({ providers: [...ids] });\n },\n });\n } finally {\n await client.close();\n }\n}\n\n/**\n * The provider environment is written whole by the room, so it is compared whole: an\n * added key can enable exactly what the pins close, and a subset test would call that a\n * match. Unrelated *top-level* provider fields remain the operator's.\n */\nfunction envMatches(live: unknown, desired: Readonly<Record<string, string>>): boolean {\n if (live === null || typeof live !== 'object' || Array.isArray(live)) return false;\n const entries = Object.entries(live as Record<string, unknown>);\n return entries.length === Object.keys(desired).length &&\n entries.every(([key, value]) => Object.hasOwn(desired, key) && value === desired[key]);\n}\n\n/** Compare only the keys the room owns; unrelated fields stay the operator's. */\nexport function providerMatches(desired: Provider, live: unknown): boolean {\n if (live === null || typeof live !== 'object') return false;\n const entry = live as Record<string, unknown>;\n const tools = entry.paseoTools;\n const same = (left: unknown, right: unknown): boolean => JSON.stringify(left ?? null) === JSON.stringify(right ?? null);\n return entry.extends === desired.extends &&\n same(entry.command, desired.command) &&\n envMatches(entry.env, desired.env) &&\n tools !== null && typeof tools === 'object' &&\n (tools as { enabled?: unknown }).enabled === desired.paseoTools.enabled &&\n // Pins are the room's guarantee: drifting them silently re-enables what they block.\n same(entry.params, desired.params) &&\n same(entry.disallowedTools, desired.disallowedTools);\n}\n\n/** Compare only the fields the room writes on an update; the rest are the operator's. */\nexport function profileMatches(desired: Profile, live: unknown): boolean {\n if (live === null || typeof live !== 'object') return false;\n const entry = live as Record<string, unknown>;\n return entry.name === desired.name && entry.icon === desired.icon && entry.color === desired.color &&\n entry.provider === desired.provider && entry.modeId === desired.modeId && entry.notes === desired.notes;\n}\n\n/**\n * Paseo stores every profile in one host-wide array, so the room rewrites that array\n * rather than patching an entry. Operator profiles pass through untouched, and so does\n * every field of a room profile that the room does not own.\n */\nexport function mergeProfiles(\n live: readonly LiveProfile[],\n desired: readonly Profile[],\n drop: readonly string[],\n): LiveProfile[] {\n const dropped = new Set(drop);\n const wanted = new Map(desired.map(profile => [profile.id, profile]));\n const seen = new Set<string>();\n const kept = live\n .filter(entry => !dropped.has(String(entry.id)))\n .map(entry => {\n const profile = wanted.get(String(entry.id));\n if (!profile) return entry;\n seen.add(profile.id);\n // Model and thinkingOptionId remain operator choices; the room owns the\n // role's visual identity and its no-prompt launch mode.\n const updated: LiveProfile = {\n ...entry, name: profile.name, icon: profile.icon, color: profile.color,\n provider: profile.provider, notes: profile.notes,\n };\n if (profile.modeId === undefined) delete updated.modeId;\n else updated.modeId = profile.modeId;\n return updated;\n });\n return [...kept, ...desired.filter(profile => !seen.has(profile.id)).map(profile => ({ ...profile }))];\n}\n","import { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { Entry } from './fsops.js';\nimport type { Layout } from './layout.js';\nimport { providerId, type Role } from './roles.js';\nimport { contractDigest, renderInstructions } from './room/instructions.js';\n\nexport const CLAUDE_CARRIER_PLUGIN_ID = 'paseo-room-claude-carrier';\nexport const CLAUDE_CARRIER_PASEO_RANGE = '>=0.8.0 <0.9.0';\n\nconst STATIC_ASSETS = [\n 'paseo-plugin.json',\n 'package.json',\n 'tsconfig.json',\n 'index.server.ts',\n 'server/carrier.ts',\n] as const;\n\nfunction loadAsset(path: string): string {\n return readFileSync(new URL(`./plugin-assets/${path}`, import.meta.url), 'utf8');\n}\n\nexport function claudeCarrierPluginDir(layout: Layout): string {\n return join(layout.roomHome, 'plugin');\n}\n\nexport function renderClaudeCarrierContract(roles: readonly Role[]): string {\n const contracts = Object.fromEntries(roles.map(role => [providerId('claude', role), renderInstructions(role)]));\n return [\n '/** Generated by paseo-room. The Markdown prompt assets remain authoritative. */',\n `export const GENERATION = ${JSON.stringify(contractDigest())};`,\n `export const CONTRACT: Readonly<Record<string, string>> = ${JSON.stringify(contracts, null, 2)};`,\n '',\n ].join('\\n');\n}\n\nexport function claudeCarrierEntries(layout: Layout, roles: readonly Role[]): Entry[] {\n const root = claudeCarrierPluginDir(layout);\n return [\n { kind: 'dir', path: root },\n { kind: 'dir', path: join(root, 'server') },\n ...STATIC_ASSETS.map(path => ({ kind: 'file' as const, path: join(root, path), content: loadAsset(path) })),\n { kind: 'file', path: join(root, 'server', 'contract.ts'), content: renderClaudeCarrierContract(roles) },\n ];\n}\n","import { join, sep } from 'node:path';\nimport { lstat, rm } from 'node:fs/promises';\nimport metadata from '../package.json' with { type: 'json' };\nimport { claudeAgent } from './agents/claude.js';\nimport { codexAgent } from './agents/codex.js';\nimport { piAgent } from './agents/pi.js';\nimport type { Agent, AgentPlan, Profile, Provider } from './agents/types.js';\nimport { AUTHENTICATION_GUIDE, renderAuthenticationGuide } from './auth.js';\nimport { applyEntries, exists, planEntries, type Entry } from './fsops.js';\nimport { layoutChecks, resolveLayout, roleHome, sharedRoom, type Layout, type Options } from './layout.js';\nimport { checkDaemon, mergeProfiles, minimumPaseoVersion, profileMatches, providerMatches, withSession, type ClientFactory, type LivePlugin, type LiveProfile, type Session } from './paseo.js';\nimport { CLAUDE_CARRIER_PLUGIN_ID, claudeCarrierEntries, claudeCarrierPluginDir } from './plugin.js';\nimport { fail, failed, hasFailure, pass, warn, type Check, type Operation, type Result } from './result.js';\nimport { contractDigest, renderInstructions } from './room/instructions.js';\nimport { MARKER, readMarker, renderMarker, type Marker } from './room.js';\nimport { DELEGATING_THINKING, profileId, providerId, providerLabel, ROLES, ROLE_COLOR, ROLE_ICON, ROLE_NOTES, ROLE_PASEO_TOOLS, ROLE_THINKING, type AgentId, type Role } from './roles.js';\n\nexport const AGENTS: Record<AgentId, Agent> = { codex: codexAgent, claude: claudeAgent, pi: piAgent };\n\nexport interface RunOptions extends Options {\n readonly agents?: readonly AgentId[];\n readonly apply?: boolean;\n readonly env?: NodeJS.ProcessEnv;\n readonly factory?: ClientFactory;\n}\n\nfunction sessionOptions(options: RunOptions): { password?: string; factory?: ClientFactory } {\n const password = (options.env ?? process.env).PASEO_PASSWORD;\n return { ...(password === undefined ? {} : { password }), ...(options.factory ? { factory: options.factory } : {}) };\n}\n\n/** The only per-agent differences are the home variable and the provider pins. */\nfunction roleProviders(\n layout: Layout,\n agent: Agent,\n plan: { readonly binary: string; readonly argv?: AgentPlan['argv']; readonly providerEnv?: AgentPlan['providerEnv'] },\n roles: readonly Role[],\n): Record<string, Provider> {\n return Object.fromEntries(roles.map(role => [providerId(agent.id, role), {\n extends: agent.id,\n label: providerLabel(agent.id, role),\n command: [plan.binary, ...(plan.argv?.[role] ?? [])],\n env: { ...agent.providerEnv, ...plan.providerEnv?.[role], [agent.homeEnv]: roleHome(layout, agent.id, role) },\n paseoTools: { enabled: ROLE_PASEO_TOOLS[role] },\n ...agent.pins,\n }]));\n}\n\n/** The picker preset that points at a provider, so a seat is one click rather than four. */\nfunction roleProfiles(agent: Agent, roles: readonly Role[]): Profile[] {\n return roles.map(role => ({\n id: profileId(agent.id, role),\n name: providerLabel(agent.id, role),\n icon: ROLE_ICON[role],\n color: ROLE_COLOR[role],\n provider: providerId(agent.id, role),\n ...(agent.defaultModeId === undefined ? {} : { modeId: agent.defaultModeId }),\n thinkingOptionId: ROLE_THINKING[role],\n notes: ROLE_NOTES[role],\n }));\n}\n\ninterface Desired {\n readonly entries: readonly Entry[];\n readonly providers: Readonly<Record<string, Provider>>;\n readonly profiles: readonly Profile[];\n readonly checks: readonly Check[];\n readonly pluginPath?: string;\n}\nasync function buildDesired(layout: Layout, agents: readonly AgentId[], roles: readonly Role[]): Promise<Desired> {\n // Template, not linked into any seat: each repo owns its own docs/WORKSPACE_PROTOCOL.md.\n // Named exactly as Workspace Protocol Precedence names it, so a copy needs no rename.\n const entries: Entry[] = [\n { kind: 'dir', path: layout.roomHome },\n { kind: 'dir', path: sharedRoom(layout) },\n { kind: 'file', path: join(sharedRoom(layout), 'WORKSPACE_PROTOCOL.md'), content: renderInstructions('workspace') },\n ];\n const providers: Record<string, Provider> = {};\n const profiles: Profile[] = [];\n const checks: Check[] = [];\n const binaries: Partial<Record<AgentId, string>> = {};\n for (const id of agents) {\n const agent = AGENTS[id];\n const plan = await agent.build(layout, roles);\n entries.push(...plan.entries);\n checks.push(...plan.checks);\n const credentials = plan.credentials ?? [];\n checks.push(...credentials.flatMap(credential => credential.checks));\n const credentialPaths = new Set(credentials.map(credential => credential.path));\n const collisions = plan.entries.filter(entry => credentialPaths.has(entry.path));\n if (collisions.length > 0) {\n checks.push(fail(`${id}.credentials`,\n `${agent.label} produced managed entries for preserve-only credential paths: ${collisions.map(entry => entry.path).join(', ')}.`,\n 'This is an adapter defect; do not apply the plan.'));\n }\n if (plan.binary === undefined) continue;\n binaries[id] = plan.binary;\n Object.assign(providers, roleProviders(layout, agent, {\n binary: plan.binary,\n ...(plan.argv ? { argv: plan.argv } : {}),\n ...(plan.providerEnv ? { providerEnv: plan.providerEnv } : {}),\n }, roles));\n profiles.push(...roleProfiles(agent, roles));\n }\n if (agents.every(id => binaries[id] !== undefined)) {\n entries.push({\n kind: 'file',\n path: join(layout.roomHome, AUTHENTICATION_GUIDE),\n content: renderAuthenticationGuide(layout.roomHome, binaries, agents, roles),\n });\n checks.push(warn('room.authentication-not-validated',\n `Role authentication was not validated. Login instructions are managed at ${join(layout.roomHome, AUTHENTICATION_GUIDE)}.`,\n 'After setup --apply, follow that guide or run: paseo-room auth login <agent> <role>'));\n }\n const pluginPath = agents.includes('claude') ? claudeCarrierPluginDir(layout) : undefined;\n if (pluginPath !== undefined) entries.push(...claudeCarrierEntries(layout, roles));\n entries.push({ kind: 'file', path: join(layout.roomHome, MARKER), content: renderMarker(metadata.version, agents, roles, contractDigest()) });\n return { entries, providers, profiles, checks, ...(pluginPath === undefined ? {} : { pluginPath }) };\n}\n\n/**\n * The marker records which rendered contract generation installed this room, so an operator\n * who upgrades the package can see that the seats now hold older text. A room installed\n * before provenance existed has no digest, which is reported the same way rather than\n * treated as a broken marker.\n */\nfunction contractProvenance(previous: Marker | undefined): Check[] {\n const digest = contractDigest();\n if (!previous) return [];\n if (previous.contract === digest) {\n return [pass('room.contract', `Role contract generation ${digest} matches this package.`)];\n }\n const held = previous.contract === undefined\n ? `was installed before the room recorded its contract generation (package ${previous.version})`\n : `holds contract generation ${previous.contract}`;\n return [warn('room.contract',\n `This room ${held}; this package renders ${digest}. Managed role documents are rewritten by setup, and a running seat keeps the text it started with.`,\n 'Run: paseo-room setup --apply, then restart the affected seats.')];\n}\n\n/**\n * `thinkingOptionId` is seeded once and the operator's afterwards, so a risky selection is\n * reported rather than corrected. Nothing here changes provider selection, profile writes, or\n * exit status.\n */\nfunction thinkingDiagnostics(live: readonly LiveProfile[], desired: readonly Profile[]): Check[] {\n const owned = new Set(desired.map(profile => profile.id));\n const selected = live\n .filter(entry => owned.has(String(entry.id)))\n .filter(entry => DELEGATING_THINKING.some(option => option === entry.thinkingOptionId))\n .map(entry => `${String(entry.id)} (${String(entry.thinkingOptionId)})`)\n .sort();\n if (selected.length === 0) return [];\n return [warn('room.thinking',\n `${String(selected.length)} room seats are set to a top reasoning option that Paseo describes as including automatic task delegation: ${selected.join(', ')}. Whether that option can actually delegate once the room has closed the native multi-agent paths is unverified: paseo-room has not verified whether those closures prevent that option from delegating, and left your selection in place.`,\n `Choose a lower reasoning option for those seats in Paseo if you want the room's own defaults (${ROLE_THINKING.supervisor} for Supervisor, ${ROLE_THINKING.lead} for Lead and Peer).`)];\n}\n\n/** Catalog copies are one of the room's three native multi-agent closures, so their drift is named. */\nfunction fileDriftDetail(targets: readonly string[]): string {\n const catalogs = targets.filter(target => target.endsWith(`${sep}model-catalog.json`));\n if (catalogs.length === 0) return '';\n const count = catalogs.length === 1 ? 'One of them is a generated Codex model catalog' : `${String(catalogs.length)} of them are generated Codex model catalogs`;\n return ` ${count}, so those seats currently lack the scrubbed catalog closure rather than only older contract text.`;\n}\n\ninterface Stale {\n readonly providerIds: readonly string[];\n readonly profileIds: readonly string[];\n readonly removePlugin: boolean;\n /** Role homes are retained during setup because runtime-owned credentials may be inside. */\n readonly retainedDirectories: readonly string[];\n}\nconst NOTHING_STALE: Stale = { providerIds: [], profileIds: [], removePlugin: false, retainedDirectories: [] };\n\nasync function safeDirectory(path: string, checks: Check[]): Promise<boolean> {\n try {\n const stat = await lstat(path);\n if (stat.isDirectory()) return true;\n checks.push(fail('room.path-safety',\n `Refusing to traverse ${path}: every existing room directory ancestor must be a real directory, not a symbolic link or another file type.`,\n 'Move the path aside manually after checking it for role-owned credentials, then run the command again.'));\n return false;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;\n checks.push(fail('room.path-safety', `Could not inspect room directory ${path} without following links.`,\n 'Fix its parent permissions or move the path manually, then run the command again.'));\n return false;\n }\n}\n\n/** Refuse managed writes through any existing room-relative directory alias. */\nasync function roomPathSafety(layout: Layout, agents: readonly AgentId[], roles: readonly Role[]): Promise<Check[]> {\n const checks: Check[] = [];\n if (!await safeDirectory(layout.roomHome, checks)) return checks;\n await safeDirectory(sharedRoom(layout), checks);\n const rolesHome = join(layout.roomHome, 'roles');\n if (!await safeDirectory(rolesHome, checks)) return checks;\n for (const agent of agents) {\n const agentHome = join(rolesHome, agent);\n if (!await safeDirectory(agentHome, checks)) continue;\n for (const role of roles) await safeDirectory(roleHome(layout, agent, role), checks);\n }\n return checks;\n}\n\n/** A previous setup may have seated agents or roles this one does not: drop those. */\nasync function staleFrom(layout: Layout, previous: Marker | undefined, agents: readonly AgentId[], roles: readonly Role[]): Promise<Stale> {\n if (!previous) return NOTHING_STALE;\n const kept = new Set(agents.flatMap(agent => roles.map(role => providerId(agent, role))));\n const providerIds: string[] = [];\n const profileIds: string[] = [];\n const retainedDirectories: string[] = [];\n for (const agent of previous.agents) {\n for (const role of previous.roles) {\n if (kept.has(providerId(agent, role))) continue;\n providerIds.push(providerId(agent, role));\n profileIds.push(profileId(agent, role));\n const path = roleHome(layout, agent, role);\n if (await exists(path)) retainedDirectories.push(path);\n }\n }\n return {\n providerIds,\n profileIds,\n removePlugin: previous.agents.includes('claude') && !agents.includes('claude'),\n retainedDirectories,\n };\n}\n\ninterface Plan {\n readonly operations: readonly Operation[];\n /** Carried out of the plan so apply rewrites the array it actually compared against. */\n readonly liveProfiles: readonly LiveProfile[];\n readonly livePlugin?: LivePlugin;\n readonly pluginChecks: readonly Check[];\n}\n\nfunction pluginPlan(desired: Desired, stale: Stale, plugins: readonly LivePlugin[], expectedPath: string): {\n operation?: Operation; livePlugin?: LivePlugin; checks: Check[];\n} {\n const livePlugin = plugins.find(plugin => plugin.id === CLAUDE_CARRIER_PLUGIN_ID);\n const shouldManage = desired.pluginPath !== undefined || stale.removePlugin;\n if (!shouldManage) return { checks: [] };\n if (livePlugin !== undefined && livePlugin.path !== expectedPath) {\n return {\n livePlugin,\n checks: [fail('claude.plugin.path',\n `Plugin ${CLAUDE_CARRIER_PLUGIN_ID} is registered from ${livePlugin.path}, not the room-owned path ${expectedPath}.`,\n 'Move or remove that conflicting plugin registration manually, then run setup again.')],\n };\n }\n if (desired.pluginPath !== undefined) {\n const healthy = livePlugin?.enabled === true && livePlugin.status === 'running' && livePlugin.error === undefined;\n return {\n ...(livePlugin === undefined ? {} : { livePlugin }),\n operation: { action: livePlugin === undefined ? 'create' : healthy ? 'noop' : 'update', kind: 'plugin', target: CLAUDE_CARRIER_PLUGIN_ID },\n checks: [],\n };\n }\n return {\n ...(livePlugin === undefined ? {} : { livePlugin }),\n operation: { action: livePlugin === undefined ? 'noop' : 'remove', kind: 'plugin', target: CLAUDE_CARRIER_PLUGIN_ID },\n checks: [],\n };\n}\n\n/** One definition of drift, shared by the command that fixes it and the one that reports it. */\nasync function planRoom(session: Session, desired: Desired, stale: Stale, expectedPluginPath: string): Promise<Plan> {\n const inspectPlugins = desired.pluginPath !== undefined || stale.removePlugin;\n const [live, liveProfiles, plugins] = await Promise.all([\n session.readProviders(), session.readProfiles(), inspectPlugins ? session.listPlugins() : Promise.resolve([]),\n ]);\n const byId = new Map(liveProfiles.map(entry => [String(entry.id), entry]));\n const plugin = pluginPlan(desired, stale, plugins, expectedPluginPath);\n return {\n liveProfiles,\n ...(plugin.livePlugin === undefined ? {} : { livePlugin: plugin.livePlugin }),\n pluginChecks: plugin.checks,\n operations: [\n ...await planEntries(desired.entries),\n ...Object.entries(desired.providers).map(([id, provider]) => ({\n action: !(id in live) ? 'create' : providerMatches(provider, live[id]) ? 'noop' : 'update',\n kind: 'provider',\n target: id,\n }) satisfies Operation),\n ...desired.profiles.map(profile => ({\n action: !byId.has(profile.id) ? 'create' : profileMatches(profile, byId.get(profile.id)) ? 'noop' : 'update',\n kind: 'profile',\n target: profile.id,\n }) satisfies Operation),\n ...stale.providerIds.filter(id => id in live).map(id => ({ action: 'remove', kind: 'provider', target: id }) satisfies Operation),\n ...stale.profileIds.filter(id => byId.has(id)).map(id => ({ action: 'remove', kind: 'profile', target: id }) satisfies Operation),\n ...(plugin.operation === undefined ? [] : [plugin.operation]),\n ],\n };\n}\n\nfunction pluginsEnabledCheck(enabled: boolean): Check {\n return enabled\n ? pass('claude.plugin.enabled', 'Paseo plugins are enabled for the required Claude contract carrier.')\n : fail('claude.plugin.enabled',\n 'Claude rooms require the paseo-room trusted server plugin, but Paseo plugins are disabled. Plugins are trusted, unsandboxed code with access to the daemon machine.',\n 'Review that trust boundary, enable plugins in Paseo Settings, reload Paseo, then run setup again.');\n}\n\nfunction pluginRuntimeCheck(plugin: LivePlugin | undefined, expectedPath: string): Check {\n if (plugin === undefined) {\n return fail('claude.plugin.runtime', `Plugin ${CLAUDE_CARRIER_PLUGIN_ID} is not registered.`, 'Run: paseo-room setup --apply');\n }\n if (plugin.path !== expectedPath) {\n return fail('claude.plugin.runtime', `Plugin ${CLAUDE_CARRIER_PLUGIN_ID} is registered from ${plugin.path}, not ${expectedPath}.`,\n 'Move or remove that conflicting plugin registration manually, then run setup again.');\n }\n if (!plugin.enabled || plugin.status !== 'running' || plugin.error !== undefined) {\n const detail = plugin.error === undefined ? `status ${plugin.status}` : `${plugin.status}: ${plugin.error}`;\n return fail('claude.plugin.runtime', `Plugin ${CLAUDE_CARRIER_PLUGIN_ID} is not running (${detail}).`, 'Run: paseo-room setup --apply');\n }\n return pass('claude.plugin.runtime', `Claude contract carrier plugin is running from ${expectedPath}.`);\n}\n\nasync function reconcilePlugin(\n session: Session, desired: Desired, plan: Plan, pending: readonly Operation[], expectedPath: string,\n): Promise<Check[]> {\n if (desired.pluginPath === undefined) {\n if (plan.livePlugin !== undefined) await session.removePlugin(CLAUDE_CARRIER_PLUGIN_ID);\n return [];\n }\n let plugin = plan.livePlugin;\n if (plugin === undefined) {\n plugin = await session.installPlugin(expectedPath, CLAUDE_CARRIER_PLUGIN_ID);\n } else {\n if (!plugin.enabled) plugin = await session.enablePlugin(CLAUDE_CARRIER_PLUGIN_ID);\n const filesChanged = pending.some(operation =>\n (operation.kind === 'file' || operation.kind === 'dir') && operation.target.startsWith(`${expectedPath}${sep}`),\n );\n const needsReload = filesChanged || plugin.status !== 'running' || plugin.error !== undefined;\n if (needsReload) plugin = await session.reloadPlugin(CLAUDE_CARRIER_PLUGIN_ID);\n }\n return [pluginRuntimeCheck(plugin, expectedPath)];\n}\n\n/** The whole product: write the role homes, then register them with Paseo. */\nexport async function setup(options: RunOptions = {}): Promise<Result> {\n const layout = resolveLayout(options, options.env);\n const agents = options.agents ?? ['codex'];\n const invalid = layoutChecks(layout, agents);\n if (invalid.length > 0) return failed('setup', invalid);\n const rootSafety = await roomPathSafety(layout, [], []);\n if (hasFailure(rootSafety)) return failed('setup', rootSafety);\n const previous = await readMarker(layout);\n const safetyAgents = [...new Set([...agents, ...(previous?.agents ?? [])])];\n const pathSafety = await roomPathSafety(layout, safetyAgents, ROLES);\n if (hasFailure(pathSafety)) return failed('setup', pathSafety);\n // Cleanup uses the APIs required by the old selection too (notably Claude's plugin API).\n const compatibilityAgents = [...new Set([...agents, ...(previous?.agents ?? [])])];\n const daemon = await checkDaemon(layout, options.env, minimumPaseoVersion(compatibilityAgents));\n if (!daemon.daemon) return failed('setup', daemon.checks);\n const desired = await buildDesired(layout, agents, ROLES);\n const stale = await staleFrom(layout, previous, agents, ROLES);\n const retained = stale.retainedDirectories.length === 0 ? [] : [warn(\n 'room.stale-role-homes-preserved',\n `Preserved ${String(stale.retainedDirectories.length)} deselected role homes because they may contain role-owned credentials or runtime state.`,\n `Use paseo-room remove --apply to delete the entire room after reviewing its credential warning, or remove deselected homes manually: ${stale.retainedDirectories.join(', ')}`,\n )];\n const checks = [...daemon.checks, ...desired.checks, ...retained];\n if (hasFailure(checks)) return failed('setup', checks);\n\n return withSession(daemon.daemon, async session => {\n const expectedPluginPath = claudeCarrierPluginDir(layout);\n const plan = await planRoom(session, desired, stale, expectedPluginPath);\n const { operations, liveProfiles } = plan;\n const pending = operations.filter(operation => operation.action !== 'noop');\n const pluginPreconditions = desired.pluginPath === undefined\n ? plan.pluginChecks\n : [pluginsEnabledCheck(await session.pluginsEnabled()), ...plan.pluginChecks];\n // Diagnostics last: nothing above may be reached only through a warning.\n const preApplyDiagnostics = [...checks, ...pluginPreconditions, ...contractProvenance(previous), ...thinkingDiagnostics(liveProfiles, desired.profiles)];\n if (hasFailure(preApplyDiagnostics) || !options.apply) {\n return {\n command: 'setup',\n outcome: hasFailure(preApplyDiagnostics) ? 'failed' : pending.length > 0 ? 'changes-planned' : 'ok',\n changed: false, checks: preApplyDiagnostics, operations,\n } satisfies Result;\n }\n // Keep the old marker until daemon reconciliation succeeds. If a remote write fails,\n // rerunning setup can still discover every stale provider/profile/plugin it must remove.\n const markerPath = join(layout.roomHome, MARKER);\n const markerEntries = desired.entries.filter(entry => entry.path === markerPath);\n await applyEntries(desired.entries.filter(entry => entry.path !== markerPath));\n const ids = Object.keys(desired.providers);\n await session.writeProviders(desired.providers);\n if (stale.providerIds.length > 0) await session.removeProviders(stale.providerIds);\n // Profiles point at providers, so they are written once the providers exist — and\n // only when something changed, since one write replaces the host's whole array.\n let appliedProfiles = liveProfiles;\n if (pending.some(operation => operation.kind === 'profile')) {\n appliedProfiles = mergeProfiles(liveProfiles, desired.profiles, stale.profileIds);\n await session.writeProfiles(appliedProfiles);\n }\n await session.refresh(ids);\n const pluginChecks = await reconcilePlugin(session, desired, plan, pending, expectedPluginPath);\n await applyEntries(markerEntries);\n const appliedMarker: Marker = {\n version: metadata.version, agents: [...agents], roles: [...ROLES], contract: contractDigest(),\n };\n const appliedChecks = [...checks, ...pluginPreconditions, ...pluginChecks,\n pass('room.applied', `Room ready at ${layout.roomHome} with ${String(ids.length)} Paseo providers.`),\n ...contractProvenance(appliedMarker), ...thinkingDiagnostics(appliedProfiles, desired.profiles)];\n return {\n command: 'setup', outcome: hasFailure(appliedChecks) ? 'failed' : 'ok', changed: pending.length > 0,\n checks: appliedChecks, operations,\n } satisfies Result;\n }, sessionOptions(options));\n}\n\nexport async function verify(options: RunOptions = {}): Promise<Result> {\n const layout = resolveLayout(options, options.env);\n const rootSafety = await roomPathSafety(layout, [], []);\n if (hasFailure(rootSafety)) return failed('verify', rootSafety);\n const marker = await readMarker(layout);\n if (!marker) {\n return failed('verify', [fail('room.marker', `No room found at ${layout.roomHome}.`, 'Run: paseo-room setup --apply')]);\n }\n const invalid = layoutChecks(layout, marker.agents);\n if (invalid.length > 0) return failed('verify', invalid);\n const pathSafety = await roomPathSafety(layout, marker.agents, marker.roles);\n if (hasFailure(pathSafety)) return failed('verify', pathSafety);\n const daemon = await checkDaemon(layout, options.env, minimumPaseoVersion(marker.agents));\n if (!daemon.daemon) return failed('verify', daemon.checks);\n const desired = await buildDesired(layout, marker.agents, marker.roles);\n const checks = [...daemon.checks, ...desired.checks];\n if (hasFailure(checks)) return failed('verify', checks);\n\n return withSession(daemon.daemon, async session => {\n const expectedPluginPath = claudeCarrierPluginDir(layout);\n const plan = await planRoom(session, desired, NOTHING_STALE, expectedPluginPath);\n const { operations, liveProfiles } = plan;\n const drifted = operations.filter(operation => operation.action !== 'noop');\n const count = (kind: Operation['kind']): number => drifted.filter(operation => operation.kind === kind).length;\n const providers = count('provider');\n const profiles = count('profile');\n const driftedFiles = drifted.filter(operation => !['provider', 'profile', 'plugin'].includes(operation.kind));\n const files = driftedFiles.length;\n const pluginChecks = desired.pluginPath === undefined ? [] : [\n pluginsEnabledCheck(await session.pluginsEnabled()),\n ...plan.pluginChecks,\n pluginRuntimeCheck(plan.livePlugin, expectedPluginPath),\n ];\n const all: Check[] = [...checks,\n files === 0\n ? pass('room.files', 'Every managed role file matches the current definition.')\n : fail('room.files', `${String(files)} managed role files are missing or outdated.${fileDriftDetail(driftedFiles.map(operation => operation.target))}`, 'Run: paseo-room setup --apply'),\n providers === 0\n ? pass('room.providers', `All ${String(Object.keys(desired.providers).length)} Paseo providers are registered as expected.`)\n : fail('room.providers', `${String(providers)} Paseo providers are missing or differ.`, 'Run: paseo-room setup --apply'),\n profiles === 0\n ? pass('room.profiles', `All ${String(desired.profiles.length)} Paseo agent profiles are registered as expected.`)\n : fail('room.profiles', `${String(profiles)} Paseo agent profiles are missing or differ.`, 'Run: paseo-room setup --apply'),\n ...pluginChecks,\n // Diagnostics last: a warning never precedes the failure it might be mistaken for.\n ...contractProvenance(marker),\n ...thinkingDiagnostics(liveProfiles, desired.profiles),\n ];\n return {\n command: 'verify', outcome: hasFailure(all) ? 'failed' : 'ok', changed: false, checks: all, operations,\n } satisfies Result;\n }, sessionOptions(options));\n}\n\nexport async function remove(options: RunOptions = {}): Promise<Result> {\n const layout = resolveLayout(options, options.env);\n const rootSafety = await roomPathSafety(layout, [], []);\n if (hasFailure(rootSafety)) return failed('remove', rootSafety);\n const marker = await readMarker(layout);\n if (!marker) {\n return failed('remove', [fail('room.marker', `No room found at ${layout.roomHome}.`, 'Nothing to remove; the room home was never created here.')]);\n }\n // A recursive delete needs a floor, so the layout rules gate this command too.\n const invalid = layoutChecks(layout, marker.agents);\n if (invalid.length > 0) return failed('remove', invalid);\n const ids = marker.agents.flatMap(agent => marker.roles.map(role => providerId(agent, role)));\n const profiles = new Set(marker.agents.flatMap(agent => marker.roles.map(role => profileId(agent, role))));\n const hasClaude = marker.agents.includes('claude');\n const operations: Operation[] = [\n ...ids.map(id => ({ action: 'remove', kind: 'provider', target: id }) satisfies Operation),\n ...[...profiles].map(id => ({ action: 'remove', kind: 'profile', target: id }) satisfies Operation),\n ...(hasClaude ? [{ action: 'remove', kind: 'plugin', target: CLAUDE_CARRIER_PLUGIN_ID } satisfies Operation] : []),\n { action: 'remove', kind: 'dir', target: layout.roomHome },\n ];\n const credentialWarning = warn('room.remove.credentials',\n `Deleting ${layout.roomHome} will delete role-owned credential files stored inside it. Native OS keyring entries are not inspected or deleted and may remain. Operator agent-home credentials are untouched.`);\n if (!options.apply) {\n return { command: 'remove', outcome: 'changes-planned', changed: false, checks: [credentialWarning], operations };\n }\n const daemon = await checkDaemon(layout, options.env);\n const checks: Check[] = [credentialWarning];\n if (!daemon.daemon) {\n return failed('remove', [\n credentialWarning,\n ...daemon.checks,\n fail(\n 'room.files',\n `Preserved ${layout.roomHome}, including its room marker, because Paseo cleanup could not start.`,\n 'Start Paseo, then run: paseo-room remove --apply',\n ),\n ]);\n }\n try {\n await withSession(daemon.daemon, async session => {\n if (hasClaude) {\n const plugin = (await session.listPlugins()).find(entry => entry.id === CLAUDE_CARRIER_PLUGIN_ID);\n const expectedPath = claudeCarrierPluginDir(layout);\n if (plugin !== undefined && plugin.path !== expectedPath) {\n throw new Error(`refusing to remove foreign plugin path ${plugin.path}`);\n }\n if (plugin !== undefined) await session.removePlugin(CLAUDE_CARRIER_PLUGIN_ID);\n }\n await session.removeProviders(ids);\n const live = await session.readProfiles();\n const kept = live.filter(entry => !profiles.has(String(entry.id)));\n if (kept.length !== live.length) await session.writeProfiles(kept);\n }, sessionOptions(options));\n checks.push(pass('room.providers', `Removed ${String(ids.length)} Paseo providers and their agent profiles.`));\n } catch {\n return failed('remove', [\n credentialWarning,\n fail(\n 'room.providers',\n `Paseo provider/profile cleanup did not complete; ${layout.roomHome} and its room marker were preserved.`,\n 'Restore Paseo connectivity, then run: paseo-room remove --apply',\n ),\n ]);\n }\n // Explicit remove owns the whole room home, including runtime-owned role credentials.\n try {\n await rm(layout.roomHome, { recursive: true, force: true });\n } catch (error) {\n const detail = error instanceof Error ? error.message : 'unknown filesystem error';\n checks.push(fail(\n 'room.files',\n `Removed the Paseo providers and profiles, but could not fully delete ${layout.roomHome}: ${detail}`,\n 'Delete that directory manually after reviewing it for role-owned credentials; the Paseo side is already clean.',\n ));\n const completedOperations = operations.filter(operation => operation.kind !== 'dir');\n return { command: 'remove', outcome: 'failed', changed: true, checks, operations: completedOperations };\n }\n checks.push(pass('room.files', `Deleted ${layout.roomHome}.`));\n return { command: 'remove', outcome: 'ok', changed: true, checks, operations };\n}\n","import * as clack from '@clack/prompts';\nimport { AGENTS, remove, setup, verify, type RunOptions } from './commands.js';\nimport type { Result } from './result.js';\nimport { AGENT_IDS, type AgentId } from './roles.js';\n\nexport interface Prompts {\n select(options: { readonly message: string; readonly options: readonly { readonly value: string; readonly label: string }[] }): Promise<string | symbol>;\n multiselect(options: { readonly message: string; readonly options: readonly { readonly value: AgentId; readonly label: string }[] }): Promise<AgentId[] | symbol>;\n confirm(options: { readonly message: string }): Promise<boolean | symbol>;\n}\nexport const terminalPrompts: Prompts = {\n select: options => clack.select({ message: options.message, options: [...options.options] }),\n multiselect: options => clack.multiselect({ message: options.message, options: [...options.options], required: true }),\n confirm: options => clack.confirm({ message: options.message, initialValue: false }),\n};\n\n/** Guided path over the same commands the flags use; nothing extra happens here. */\nexport async function runWizard(\n prompts: Prompts,\n emit: (result: Result) => number,\n write: (text: string) => void,\n options: RunOptions = {},\n onAction?: (action: string) => void,\n): Promise<number> {\n const cancelled = (): number => { write('Cancelled; nothing was changed.\\n'); return 0; };\n const action = await prompts.select({\n message: 'What do you want to do?',\n options: [\n { value: 'setup', label: 'Set up / update the room (login stays separate)' },\n { value: 'verify', label: 'Verify the current room' },\n { value: 'remove', label: 'Remove the room' },\n ],\n });\n if (typeof action === 'symbol') return cancelled();\n onAction?.(action);\n if (action === 'verify') return emit(await verify(options));\n if (action === 'remove') {\n const preview = await remove(options);\n const status = emit(preview);\n if (preview.outcome !== 'changes-planned') return status;\n const approved = await prompts.confirm({ message: 'Delete the room home, including role credentials, and its Paseo providers?' });\n return approved === true ? emit(await remove({ ...options, apply: true })) : cancelled();\n }\n const agents = await prompts.multiselect({\n message: 'Which coding agents should the room use?',\n options: AGENT_IDS.map(value => ({ value, label: AGENTS[value].label })),\n });\n if (typeof agents === 'symbol' || agents.length === 0) return cancelled();\n const preview = await setup({ ...options, agents });\n const status = emit(preview);\n if (preview.outcome !== 'changes-planned') return status;\n const approved = await prompts.confirm({ message: 'Apply these changes? Authentication will not be validated or started.' });\n if (approved !== true) return cancelled();\n return emit(await setup({ ...options, agents, apply: true }));\n}\n","import { Command, CommanderError, InvalidArgumentError } from 'commander';\nimport metadata from '../package.json' with { type: 'json' };\nimport { loginRole, type LoginSpawner } from './auth.js';\nimport { remove, setup, verify, type RunOptions } from './commands.js';\nimport { renderHuman, renderJson } from './render.js';\nimport { exitCode, fail, failed, type Result } from './result.js';\nimport { AGENT_IDS, type AgentId } from './roles.js';\nimport { PromptAssetError } from './room/prompts.js';\nimport type { Prompts } from './wizard.js';\n\nexport interface Output {\n readonly stdout: (text: string) => void;\n readonly stderr: (text: string) => void;\n}\nexport interface CliContext {\n readonly isTTY?: boolean;\n readonly prompts?: Prompts;\n readonly options?: RunOptions;\n readonly loginSpawn?: LoginSpawner;\n}\n\n/** Commander passes no initial value, so the first call starts the list. */\nfunction collectAgent(value: string, previous: AgentId[] | undefined): AgentId[] {\n const agent = AGENT_IDS.find(id => id === value);\n if (!agent) throw new InvalidArgumentError(`Unknown agent: ${value}`);\n const seated = previous ?? [];\n return seated.includes(agent) ? seated : [...seated, agent];\n}\n\nconst PATH_FLAGS = ['roomHome', 'codexHome', 'claudeHome', 'piHome', 'codexBin', 'claudeBin', 'piBin', 'paseoBin'] as const;\n\nfunction optionsFrom(raw: Record<string, unknown>, base: RunOptions): RunOptions {\n const paths: Record<string, string> = {};\n for (const flag of PATH_FLAGS) {\n const value = raw[flag];\n if (typeof value === 'string' && value.trim()) paths[flag] = value.trim();\n }\n const agents = Array.isArray(raw.agent) && raw.agent.length > 0 ? (raw.agent as AgentId[]) : undefined;\n return { ...base, ...paths, ...(agents ? { agents } : {}), ...(raw.apply === true ? { apply: true } : {}) };\n}\n\nfunction failedFromThrown(command: string, error: unknown): Result {\n if (error instanceof PromptAssetError) {\n return failed(command, [fail(\n `${command}.prompt-asset`,\n error.message,\n 'Reinstall paseo-room, then try again.',\n )]);\n }\n const detail = error instanceof Error ? error.message : 'unknown error';\n return failed(command, [fail(\n `${command}.error`,\n detail,\n 'Check that Paseo is running and reachable, then try again.',\n )]);\n}\n\nexport async function runCli(argv: readonly string[], output: Output, context: CliContext = {}): Promise<number> {\n const password = (context.options?.env ?? process.env).PASEO_PASSWORD;\n const redact = (text: string): string => (password ? text.split(password).join('[redacted]') : text);\n // Set once the flags are parsed; the wizard path never sees flags, so text output is right there.\n let json = false;\n const emit = (result: Result): number => {\n output.stdout(redact(json ? renderJson(result) : renderHuman(result)));\n return exitCode(result);\n };\n const isTTY = context.isTTY ?? (process.stdin.isTTY && process.stdout.isTTY && process.stderr.isTTY);\n const base = context.options ?? {};\n\n if (argv.length === 0) {\n if (!isTTY) {\n output.stderr('paseo-room: no command given. Try: paseo-room setup, verify, remove, auth login, or --help.\\n');\n return 2;\n }\n let wizardCommand = 'wizard';\n try {\n // @clack/prompts is only reachable here, so keep it off the scripted path.\n const { runWizard, terminalPrompts } = await import('./wizard.js');\n return await runWizard(\n context.prompts ?? terminalPrompts,\n emit,\n text => { output.stdout(text); },\n base,\n action => { wizardCommand = action; },\n );\n } catch (error) {\n return emit(failedFromThrown(wizardCommand, error));\n }\n }\n const program = new Command()\n .name('paseo-room')\n .description('Configure Codex/Claude/Pi role homes in $HOME and register them with your local Paseo daemon.')\n .version(metadata.version)\n .usage('<setup|verify|remove> [options]\\n auth login <codex|claude|pi> <supervisor|lead|peer> [options]')\n .argument('<command>', 'setup | verify | remove | auth')\n .argument('[command-arguments...]', 'auth login <agent> <role>')\n .option('--agent <agent>', 'codex, claude, or pi; repeat to combine (default: codex)', collectAgent)\n .option('--apply', 'actually make the changes (default: dry run)')\n .option('--json', 'machine-readable output')\n .option('--room-home <path>', 'where role homes are written (default: ~/.paseo-room)')\n .option('--codex-home <path>', 'source Codex config (default: ~/.codex)')\n .option('--claude-home <path>', 'source Claude Code config (default: ~/.claude)')\n .option('--pi-home <path>', 'source Pi config (default: ~/.pi/agent)')\n .option('--codex-bin <path>', 'Codex executable (default: found on PATH)')\n .option('--claude-bin <path>', 'Claude Code executable (default: found on PATH)')\n .option('--pi-bin <path>', 'Pi executable (default: found on PATH)')\n .option('--paseo-bin <path>', 'Paseo executable (default: found on PATH)')\n .configureOutput({ writeOut: text => { output.stdout(text); }, writeErr: text => { output.stderr(text); } })\n .exitOverride();\n\n let command: string;\n let commandArguments: string[];\n let options: RunOptions;\n let raw: Record<string, unknown>;\n try {\n program.parse([...argv], { from: 'user' });\n raw = program.opts<Record<string, unknown>>();\n json = raw.json === true;\n command = program.args[0] ?? '';\n commandArguments = program.args.slice(1);\n options = optionsFrom(raw, base);\n } catch (error) {\n if (error instanceof CommanderError && error.exitCode === 0) return 0;\n return 2;\n }\n\n try {\n if (command === 'auth') {\n if (raw.apply === true) {\n output.stderr('paseo-room auth login is already explicit and does not use --apply.\\n');\n return 2;\n }\n if (raw.json === true) {\n output.stderr('paseo-room auth login is interactive and does not support --json.\\n');\n return 2;\n }\n if (raw.agent !== undefined) {\n output.stderr('paseo-room auth login takes exactly one positional agent and does not use --agent.\\n');\n return 2;\n }\n if (commandArguments.length !== 3 || commandArguments[0] !== 'login') {\n output.stderr('Usage: paseo-room auth login <codex|claude|pi> <supervisor|lead|peer>\\n');\n return 2;\n }\n return await loginRole(commandArguments[1] ?? '', commandArguments[2] ?? '', {\n ...options,\n isTTY,\n ...(context.loginSpawn ? { spawn: context.loginSpawn } : {}),\n }, output);\n }\n if (commandArguments.length > 0) {\n output.stderr(`paseo-room ${command}: unexpected arguments: ${commandArguments.join(' ')}\\n`);\n return 2;\n }\n if (command === 'setup') return emit(await setup(options));\n if (command === 'verify') return emit(await verify(options));\n if (command === 'remove') return emit(await remove(options));\n } catch (error) {\n return emit(failedFromThrown(command, error));\n }\n output.stderr(`paseo-room: unknown command \"${command}\". Try: setup, verify, remove, or auth login.\\n`);\n return 2;\n}\n","import type { Result } from './result.js';\n\nexport function renderJson(result: Result): string {\n return `${JSON.stringify({ schemaVersion: 2, ...result }, null, 2)}\\n`;\n}\n\nconst ICONS = { pass: '✓', warn: '!', fail: '✗' } as const;\n\nexport function renderHuman(result: Result): string {\n const lines: string[] = [];\n for (const check of result.checks) {\n lines.push(`${ICONS[check.status]} ${check.message}`);\n if (check.fix) lines.push(` → ${check.fix}`);\n }\n const changes = result.operations.filter(operation => operation.action !== 'noop');\n if (changes.length > 0) {\n lines.push('', result.changed ? 'Applied:' : 'Planned changes:');\n for (const operation of changes) lines.push(` ${operation.action} ${operation.kind} ${operation.target}`);\n const unchanged = result.operations.length - changes.length;\n if (unchanged > 0) lines.push(` (${String(unchanged)} already up to date)`);\n } else if (result.operations.length > 0) {\n lines.push('', 'Everything is already up to date.');\n }\n lines.push('', `${result.command}: ${result.outcome}`);\n return `${lines.join('\\n')}\\n`;\n}\n","#!/usr/bin/env node\nimport { runCli } from './cli.js';\n\nprocess.exitCode = await runCli(process.argv.slice(2), {\n stdout: text => { process.stdout.write(text); },\n stderr: text => { process.stderr.write(text); },\n});\n"],"mappings":";;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA,MACE,MAAQ;AAAA,MACR,SAAW;AAAA,MACX,aAAe;AAAA,MACf,UAAY;AAAA,QACV;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MACA,UAAY;AAAA,MACZ,MAAQ;AAAA,MACR,YAAc;AAAA,Q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AK,MAAM,MAAM,OAAO,CAAC;AACzD,QAAI,YAAY,SAAU,QAAO,KAAK,MAAM,OAAO,OAAO,CAAC;AAC3D,QAAI,YAAY,SAAU,QAAO,KAAK,MAAM,OAAO,OAAO,CAAC;AAAA,EAC7D,SAAS,OAAO;AACd,WAAO,KAAK,iBAAiB,SAAS,KAAK,CAAC;AAAA,EAC9C;AACA,SAAO,OAAO,gCAAgC,OAAO;AAAA,CAAiD;AACtG,SAAO;AACT;;;AE/JA,QAAQ,WAAW,MAAM,OAAO,QAAQ,KAAK,MAAM,CAAC,GAAG;AAAA,EACrD,QAAQ,UAAQ;AAAE,YAAQ,OAAO,MAAM,IAAI;AAAA,EAAG;AAAA,EAC9C,QAAQ,UAAQ;AAAE,YAAQ,OAAO,MAAM,IAAI;AAAA,EAAG;AAChD,CAAC;","names":["stat","lstat","readlink","join","stat","title","join","join","resolve","constants","join","lstat","env","argv","resolve","table","readdir","join","readFile","join","join","SHARED","EXECUTABLE","evidence","spawn","readFile","rm","isAbsolute","join","resolve","asObject","command","AUTH_ENV","SHARED","EXECUTABLE","z","run","readFileSync","join","join","sep","lstat","rm","stat","preview","status","approved","runWizard","terminalPrompts"]}
1
+ {"version":3,"sources":["../package.json","../src/result.ts","../src/credentials.ts","../src/layout.ts","../src/fsops.ts","../src/roles.ts","../src/room.ts","../src/which.ts","../src/auth.ts","../src/room/prompts.ts","../src/room/instructions.ts","../src/agents/mcp.ts","../src/agents/resources.ts","../src/agents/claude.ts","../src/agents/codex.ts","../src/agents/pi.ts","../src/paseo.ts","../src/plugin.ts","../src/commands.ts","../src/wizard.ts","../src/cli.ts","../src/render.ts","../src/index.ts"],"sourcesContent":["{\n \"name\": \"paseo-room\",\n \"version\": \"0.4.0\",\n \"description\": \"One CLI that configures Codex, Claude Code, and Pi role homes in $HOME and registers them with your local Paseo daemon.\",\n \"keywords\": [\n \"paseo\",\n \"codex\",\n \"claude-code\",\n \"pi-coding-agent\",\n \"agent\",\n \"orchestration\",\n \"cli\"\n ],\n \"homepage\": \"https://github.com/cuongntr/paseo-room#readme\",\n \"bugs\": \"https://github.com/cuongntr/paseo-room/issues\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/cuongntr/paseo-room.git\"\n },\n \"license\": \"MIT\",\n \"author\": \"Invoker <cuongnt1987@gmail.com>\",\n \"type\": \"module\",\n \"engines\": {\n \"node\": \">=22\"\n },\n \"bin\": {\n \"paseo-room\": \"dist/index.js\"\n },\n \"files\": [\n \"dist/\"\n ],\n \"scripts\": {\n \"typecheck\": \"tsc --noEmit\",\n \"lint\": \"eslint . --max-warnings 0\",\n \"test\": \"vitest run\",\n \"test:package\": \"vitest run --config vitest.package.config.ts\",\n \"build\": \"tsup && node --input-type=module -e \\\"import { cpSync, rmSync } from 'node:fs'; for (const [source, target] of [['src/room/prompts', 'dist/prompts'], ['src/plugin-assets', 'dist/plugin-assets']]) { rmSync(target, { recursive: true, force: true }); cpSync(source, target, { recursive: true }); }\\\"\",\n \"prepack\": \"npm run build\",\n \"verify\": \"npm run typecheck && npm run lint && npm test && npm run build && npm run test:package\"\n },\n \"dependencies\": {\n \"@clack/prompts\": \"^1.8.0\",\n \"@getpaseo/client\": \"0.8.0-beta.1\",\n \"commander\": \"^14.0.3\",\n \"semver\": \"^7.8.5\",\n \"smol-toml\": \"^1.8.0\",\n \"zod\": \"^4.5.4\"\n },\n \"devDependencies\": {\n \"@eslint/js\": \"^10.0.1\",\n \"@types/node\": \"^22.0.0\",\n \"@types/semver\": \"^7.7.0\",\n \"eslint\": \"^10.10.0\",\n \"tsup\": \"^8.5.1\",\n \"typescript\": \"~5.9.3\",\n \"typescript-eslint\": \"^8.70.0\",\n \"vitest\": \"^4.1.11\"\n }\n}\n","export type Status = 'pass' | 'warn' | 'fail';\nexport interface Check {\n readonly id: string;\n readonly status: Status;\n readonly message: string;\n readonly fix?: string;\n}\nexport interface Operation {\n readonly action: 'create' | 'update' | 'remove' | 'noop';\n readonly kind: 'dir' | 'file' | 'link' | 'provider' | 'profile' | 'plugin';\n readonly target: string;\n}\nexport type Outcome = 'ok' | 'changes-planned' | 'failed';\nexport interface Result {\n readonly command: string;\n readonly outcome: Outcome;\n readonly changed: boolean;\n readonly checks: readonly Check[];\n readonly operations: readonly Operation[];\n}\n\nexport function pass(id: string, message: string): Check {\n return { id, status: 'pass', message };\n}\nexport function warn(id: string, message: string, fix?: string): Check {\n return { id, status: 'warn', message, ...(fix === undefined ? {} : { fix }) };\n}\nexport function fail(id: string, message: string, fix: string): Check {\n return { id, status: 'fail', message, fix };\n}\nexport function failed(command: string, checks: readonly Check[]): Result {\n return { command, outcome: 'failed', changed: false, checks, operations: [] };\n}\nexport function hasFailure(checks: readonly Check[]): boolean {\n return checks.some(check => check.status === 'fail');\n}\nexport function exitCode(result: Result): number {\n return result.outcome === 'failed' || hasFailure(result.checks) ? 1 : 0;\n}\n","import { lstat, readlink } from 'node:fs/promises';\nimport { warn, type Check } from './result.js';\n\nexport type CredentialPathState =\n | { readonly kind: 'missing' }\n | { readonly kind: 'file' }\n | { readonly kind: 'symlink'; readonly target: string }\n | { readonly kind: 'unsafe'; readonly fileType: string };\n\nexport interface CredentialDiagnostic {\n /** Credential paths are diagnostic-only and must never become managed entries. */\n readonly path: string;\n readonly checks: readonly Check[];\n}\n\nfunction fileType(stat: Awaited<ReturnType<typeof lstat>>): string {\n if (stat.isDirectory()) return 'directory';\n if (stat.isSocket()) return 'socket';\n if (stat.isFIFO()) return 'FIFO';\n if (stat.isCharacterDevice()) return 'character device';\n if (stat.isBlockDevice()) return 'block device';\n return 'unsupported file type';\n}\n\n/** Inspect only path metadata. Credential contents and link targets are never followed. */\nexport async function inspectCredentialPath(path: string): Promise<CredentialPathState> {\n let stat;\n try {\n stat = await lstat(path);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { kind: 'missing' };\n return { kind: 'unsafe', fileType: 'uninspectable path' };\n }\n if (stat.isFile()) return { kind: 'file' };\n if (!stat.isSymbolicLink()) return { kind: 'unsafe', fileType: fileType(stat) };\n try {\n return { kind: 'symlink', target: await readlink(path) };\n } catch {\n return { kind: 'unsafe', fileType: 'unreadable symbolic link' };\n }\n}\n\nfunction shellQuote(value: string): string {\n return `'${value.replaceAll(\"'\", `'\"'\"'`)}'`;\n}\n\nexport function roleCommand(\n environment: Readonly<Record<string, string>>,\n executable: string,\n args: readonly string[] = [],\n): string {\n const variables = Object.entries(environment).map(([name, value]) => `${name}=${shellQuote(value)}`);\n return [...variables, ...[executable, ...args].map(shellQuote)].join(' ');\n}\n\nexport interface PreservedCredentialInput {\n readonly id: string;\n readonly agent: string;\n readonly role: string;\n readonly path: string;\n readonly state: Exclude<CredentialPathState, { readonly kind: 'missing' }>;\n readonly login: string;\n readonly status?: string;\n}\n\n/** Produce migration diagnostics for an existing path without claiming authentication. */\nexport function preservedCredentialCheck(input: PreservedCredentialInput): Check {\n const status = input.status ? ` Check status with: ${input.status}.` : '';\n if (input.state.kind === 'file') {\n return warn(`${input.id}.diverged-file-preserve`,\n `${input.agent} ${input.role} auth: configured structurally (diverged-file-preserve); a role-owned credential file exists at ${input.path} and is preserved. Token validity and freshness were not checked.`,\n `If authentication fails, close that role and authenticate it again with: ${input.login}.${status}`);\n }\n if (input.state.kind === 'symlink') {\n return warn(`${input.id}.legacy-shared-risk`,\n `${input.agent} ${input.role} auth: legacy-shared-risk; a credential symlink at ${input.path} -> ${input.state.target} is preserved. Its target was not inspected, followed, or changed.`,\n `Close that role. Remove only the legacy link with: rm -- ${shellQuote(input.path)}. Then create role-owned credentials with: ${input.login}.${status}`);\n }\n return warn(`${input.id}.manual-recovery`,\n `${input.agent} ${input.role} auth: diverged-file-preserve/manual-recovery; ${input.path} is a ${input.state.fileType}, not a credential file. It is preserved without inspection.`,\n `Close that role and inspect the path metadata yourself. Move or remove it manually only when safe, then authenticate with: ${input.login}.${status}`);\n}\n\nexport function presentNames(names: ReadonlySet<string>, supported: readonly string[]): string[] {\n return supported.filter(name => names.has(name));\n}\n\nexport function configuredByNamesCheck(id: string, agent: string, role: string, names: readonly string[]): Check {\n return warn(`${id}.configured-structurally`,\n `${agent} ${role} auth: configured structurally; ${names.join(', ')} ${names.length === 1 ? 'is' : 'are'} present by name. Values, token validity, and freshness were not checked.`);\n}\n\nexport function ambientNamesCheck(id: string, agent: string, role: string, names: readonly string[]): Check {\n return warn(`${id}.ambient-auth-unverifiable`,\n `${agent} ${role} auth: ambient auth unverifiable; ${names.join(', ')} ${names.length === 1 ? 'is' : 'are'} present by name in the setup process. paseo-room does not copy credential values into providers, so availability to the Paseo-launched role, token validity, and freshness were not checked.`);\n}\n","import { homedir } from 'node:os';\nimport { join, resolve, sep } from 'node:path';\nimport { fail, type Check } from './result.js';\nimport type { AgentId, Role } from './roles.js';\n\nexport interface Options {\n readonly roomHome?: string;\n readonly codexHome?: string;\n readonly claudeHome?: string;\n readonly piHome?: string;\n readonly codexBin?: string;\n readonly claudeBin?: string;\n readonly piBin?: string;\n readonly paseoBin?: string;\n}\nexport interface Layout {\n readonly home: string;\n readonly roomHome: string;\n readonly paseoHome: string;\n readonly agentHome: Record<AgentId, string>;\n /** Claude keeps legacy default state beside ~/.claude, but custom config state inside it. */\n readonly claudeState: string;\n readonly bin: Record<AgentId | 'paseo', string>;\n /** The PATH executables are looked up on. Resolved here so nothing reaches for process.env. */\n readonly searchPath: string;\n /** Environment names only, for structural auth diagnostics without retaining values. */\n readonly envNames: ReadonlySet<string>;\n}\n\nfunction pick(...candidates: readonly (string | undefined)[]): string {\n for (const candidate of candidates) if (candidate?.trim()) return candidate.trim();\n throw new Error('Could not determine HOME; pass explicit --room-home and --codex-home/--claude-home paths.');\n}\n\n/** Everything is derived from HOME; flags and environment only override defaults. */\nexport function resolveLayout(options: Options = {}, env: NodeJS.ProcessEnv = process.env): Layout {\n const home = pick(env.HOME, homedir());\n const claudeOverride = options.claudeHome?.trim() || env.CLAUDE_CONFIG_DIR?.trim() || undefined;\n const claudeHome = resolve(pick(claudeOverride, join(home, '.claude')));\n // Relative overrides resolve against the working directory, as a CLI flag should.\n return {\n home,\n roomHome: resolve(pick(options.roomHome, env.PASEO_ROOM_HOME, join(home, '.paseo-room'))),\n paseoHome: resolve(pick(env.PASEO_HOME, join(home, '.paseo'))),\n agentHome: {\n codex: resolve(pick(options.codexHome, env.CODEX_HOME, join(home, '.codex'))),\n claude: claudeHome,\n pi: resolve(pick(options.piHome, env.PI_CODING_AGENT_DIR, join(home, '.pi', 'agent'))),\n },\n claudeState: claudeOverride?.trim() ? join(claudeHome, '.claude.json') : join(home, '.claude.json'),\n bin: {\n codex: pick(options.codexBin, env.CODEX_BIN, 'codex'),\n claude: pick(options.claudeBin, env.CLAUDE_BIN, 'claude'),\n pi: pick(options.piBin, env.PI_BIN, 'pi'),\n paseo: pick(options.paseoBin, env.PASEO_BIN, 'paseo'),\n },\n searchPath: env.PATH ?? '',\n envNames: new Set(Object.keys(env)),\n };\n}\n\n/** True when `path` is the root itself or sits underneath it. */\nexport function contains(root: string, path: string): boolean {\n return path === root || path.startsWith(root.endsWith(sep) ? root : root + sep);\n}\n\n/** The room home must own its directory: no overlap with $HOME or a source agent home. */\nexport function layoutChecks(layout: Layout, agents: readonly AgentId[]): Check[] {\n const checks: Check[] = [];\n if (contains(layout.roomHome, layout.home)) {\n checks.push(fail('room.home', `Refusing to use ${layout.roomHome} as the room home: it contains your home directory.`,\n 'Point --room-home at a dedicated directory, by default ~/.paseo-room.'));\n }\n for (const id of agents) {\n const home = layout.agentHome[id];\n if (contains(layout.roomHome, home) || contains(home, layout.roomHome)) {\n checks.push(fail(`${id}.home`, `The ${id} home ${home} overlaps the room home ${layout.roomHome}.`,\n `Pass --${id}-home pointing at your own ${id} configuration (this happens when setup runs inside a room seat).`));\n }\n }\n return checks;\n}\n\nexport function roleHome(layout: Layout, agent: AgentId, role: Role): string {\n return join(layout.roomHome, 'roles', agent, role);\n}\nexport function sharedRoom(layout: Layout): string {\n return join(layout.roomHome, 'room');\n}\n","import { randomBytes } from 'node:crypto';\nimport { chmod, lstat, mkdir, readdir, readFile, readlink, rename, rm, symlink, unlink, writeFile } from 'node:fs/promises';\nimport type { Stats } from 'node:fs';\nimport { basename, dirname, join } from 'node:path';\nimport type { Operation } from './result.js';\n\n/** A directory the room creates but whose children it does not own. */\nexport interface DirEntry { readonly kind: 'dir'; readonly path: string }\n/** `once` writes the file only when absent: runtime state the agent owns after setup. */\nexport interface FileEntry { readonly kind: 'file'; readonly path: string; readonly content: string; readonly once?: true }\nexport interface LinkEntry { readonly kind: 'link'; readonly path: string; readonly target: string }\n/**\n * A managed path this room declares must not exist, so suppressing generated content\n * removes the stale file instead of leaving an older generation behind. Like every other\n * managed entry it only ever replaces the shape it writes: a regular file. Anything else\n * is refused rather than deleted.\n */\nexport interface AbsentEntry { readonly kind: 'absent'; readonly path: string }\n/**\n * A directory whose whole child inventory the room owns: names outside `children`\n * are removed so a generated projection cannot go stale. Ownership is declared here\n * and never inferred from an ordinary `dir`, so it stays limited to generated\n * projections such as Peer `skills` — never role homes or credential-bearing paths.\n */\nexport interface ManagedDirEntry {\n readonly kind: 'managed-dir';\n readonly path: string;\n readonly children: readonly string[];\n /** The single legacy shape this path may be migrated from: a symlink to this target. */\n readonly legacyLink?: string;\n}\nexport type Entry = DirEntry | FileEntry | LinkEntry | ManagedDirEntry | AbsentEntry;\n\nconst DIR_MODE = 0o700;\nconst FILE_MODE = 0o600;\n\n/**\n * An existing path is not the shape the room manages, so replacing it would destroy\n * something this CLI does not own. Raised before any deletion.\n */\nexport class ManagedPathError extends Error {\n readonly path: string;\n readonly fix: string;\n constructor(path: string, message: string, fix: string) {\n super(message);\n this.name = 'ManagedPathError';\n this.path = path;\n this.fix = fix;\n }\n}\n\nconst MOVE_ASIDE = 'Check that path for role-owned credentials, move it aside manually, then run setup again.';\n\nfunction shape(stat: Stats): string {\n if (stat.isSymbolicLink()) return 'a symbolic link';\n if (stat.isDirectory()) return 'a directory';\n if (stat.isFile()) return 'a regular file';\n return 'a special file';\n}\n\nfunction refuse(path: string, expected: string, stat: Stats): never {\n throw new ManagedPathError(path, `Refusing to replace ${path}: expected ${expected} but found ${shape(stat)}.`, MOVE_ASIDE);\n}\n\nfunction isMissing(error: unknown): boolean {\n return error !== null && typeof error === 'object' && 'code' in error && error.code === 'ENOENT';\n}\n\nasync function lstatOrAbsent(path: string): Promise<Stats | undefined> {\n try { return await lstat(path); } catch (error) {\n if (isMissing(error)) return undefined;\n throw error;\n }\n}\n\n/** Names present under a managed directory that its declaration does not claim. */\nasync function staleChildren(entry: ManagedDirEntry): Promise<string[]> {\n const declared = new Set(entry.children);\n let names: string[];\n try { names = await readdir(entry.path); } catch (error) {\n if (isMissing(error)) return [];\n throw error;\n }\n return names.filter(name => !declared.has(name));\n}\n\nasync function current(entry: Entry): Promise<'absent' | 'same' | 'different'> {\n const stat = await lstatOrAbsent(entry.path);\n // A declared-absent path is already correct when nothing is there.\n if (entry.kind === 'absent') return stat ? 'different' : 'same';\n if (!stat) return 'absent';\n if (entry.kind === 'dir') return stat.isDirectory() ? 'same' : 'different';\n if (entry.kind === 'managed-dir') {\n if (!stat.isDirectory()) return 'different';\n return (await staleChildren(entry)).length === 0 ? 'same' : 'different';\n }\n if (entry.kind === 'link') {\n if (!stat.isSymbolicLink()) return 'different';\n return await readlink(entry.path) === entry.target ? 'same' : 'different';\n }\n if (!stat.isFile()) return 'different';\n if (entry.once) return 'same';\n return await readFile(entry.path, 'utf8') === entry.content ? 'same' : 'different';\n}\n\n/** Everything lives under the room home, which this CLI owns outright. */\nexport async function planEntries(entries: readonly Entry[]): Promise<Operation[]> {\n const operations: Operation[] = [];\n for (const entry of entries) {\n const state = await current(entry);\n operations.push({\n action: state === 'same' ? 'noop' : entry.kind === 'absent' ? 'remove' : state === 'absent' ? 'create' : 'update',\n // A managed directory is still a directory to everything that reports operations.\n kind: entry.kind === 'managed-dir' ? 'dir' : entry.kind === 'absent' ? 'file' : entry.kind,\n target: entry.path,\n });\n }\n return operations;\n}\n\n/** Unique so two runs, or a leftover from a failed one, can never collide. */\nfunction tempSibling(path: string): string {\n return join(dirname(path), `.${basename(path)}.paseo-room-${randomBytes(8).toString('hex')}`);\n}\n\n/** A managed file or link may replace only an absent path or the same shape. */\nasync function assertReplaceable(entry: FileEntry | LinkEntry): Promise<void> {\n const stat = await lstatOrAbsent(entry.path);\n if (!stat) return;\n if (entry.kind === 'link') {\n if (!stat.isSymbolicLink()) refuse(entry.path, 'a symbolic link', stat);\n return;\n }\n if (!stat.isFile()) refuse(entry.path, 'a regular file', stat);\n}\n\n/** Build beside the target and rename, so a reader never sees a half-written path. */\nasync function replaceAtomically(entry: FileEntry | LinkEntry): Promise<void> {\n const temp = tempSibling(entry.path);\n try {\n if (entry.kind === 'link') await symlink(entry.target, temp);\n else {\n await writeFile(temp, entry.content, { mode: FILE_MODE });\n await chmod(temp, FILE_MODE);\n }\n await rename(temp, entry.path);\n } catch (error) {\n await rm(temp, { force: true });\n throw error;\n }\n}\n\nasync function applyDirectory(path: string): Promise<void> {\n const stat = await lstatOrAbsent(path);\n if (stat && !stat.isDirectory()) refuse(path, 'a directory', stat);\n await mkdir(path, { recursive: true, mode: DIR_MODE });\n}\n\n/**\n * Creates the projection, migrating the one declared legacy symlink by unlinking the\n * link alone, and removes only undeclared children that are links or files. An\n * unrecognized shape — including a real child directory — fails instead of being\n * deleted recursively.\n */\nasync function applyManagedDirectory(entry: ManagedDirEntry): Promise<void> {\n const stat = await lstatOrAbsent(entry.path);\n if (stat?.isSymbolicLink() === true) {\n const target = await readlink(entry.path);\n if (entry.legacyLink === undefined || target !== entry.legacyLink) {\n throw new ManagedPathError(entry.path,\n `Refusing to replace ${entry.path}: this room owns that directory, but it is a symbolic link to ${target}.`,\n MOVE_ASIDE);\n }\n // Unlink the alias only; the operator directory it pointed at is never touched.\n await unlink(entry.path);\n await mkdir(entry.path, { recursive: true, mode: DIR_MODE });\n return;\n }\n if (stat && !stat.isDirectory()) refuse(entry.path, 'a directory this room owns', stat);\n await mkdir(entry.path, { recursive: true, mode: DIR_MODE });\n if (!stat) return;\n for (const name of await staleChildren(entry)) {\n const child = join(entry.path, name);\n const childStat = await lstatOrAbsent(child);\n if (!childStat) continue;\n if (!childStat.isFile() && !childStat.isSymbolicLink()) {\n throw new ManagedPathError(child,\n `Refusing to remove ${child}: this room manages ${entry.path} by name, but that stale child is ${shape(childStat)} rather than a generated file or link.`,\n MOVE_ASIDE);\n }\n await rm(child, { force: true });\n }\n}\n\n/**\n * Removes a suppressed managed file. Only a regular file is ever deleted: a directory,\n * link or special file at that path belongs to something this room does not own.\n */\nasync function removeManagedFile(path: string): Promise<void> {\n const stat = await lstatOrAbsent(path);\n if (!stat) return;\n if (!stat.isFile()) refuse(path, 'a regular file this room generated', stat);\n await rm(path, { force: true });\n}\n\n/** Rewrites only what differs, so a repeat run costs stats rather than writes. */\nexport async function applyEntries(entries: readonly Entry[]): Promise<void> {\n for (const entry of entries) {\n if (await current(entry) === 'same') continue;\n if (entry.kind === 'dir') {\n await applyDirectory(entry.path);\n continue;\n }\n if (entry.kind === 'managed-dir') {\n await applyManagedDirectory(entry);\n continue;\n }\n if (entry.kind === 'absent') {\n await removeManagedFile(entry.path);\n continue;\n }\n await mkdir(dirname(entry.path), { recursive: true, mode: DIR_MODE });\n await assertReplaceable(entry);\n await replaceAtomically(entry);\n }\n}\n\nexport async function exists(path: string): Promise<boolean> {\n try { await lstat(path); return true; } catch { return false; }\n}\n\n/** Which of `names` exist under `home`, probed once for all roles that share them. */\nexport async function existingPaths(home: string, names: readonly string[]): Promise<string[]> {\n const paths = names.map(name => join(home, name));\n const present = await Promise.all(paths.map(exists));\n return paths.filter((_, index) => present[index] === true);\n}\n\nexport async function readIfPresent(path: string): Promise<string | undefined> {\n try { return await readFile(path, 'utf8'); } catch { return undefined; }\n}\n","export const ROLES = ['supervisor', 'lead', 'peer'] as const;\nexport type Role = (typeof ROLES)[number];\n\nexport const AGENT_IDS = ['codex', 'claude', 'pi'] as const;\nexport type AgentId = (typeof AGENT_IDS)[number];\n\n/** Supervisor and Lead orchestrate; Peer executes one brief and gets no room tools. */\nexport const ROLE_PASEO_TOOLS: Record<Role, boolean> = { supervisor: true, lead: true, peer: false };\n\n/**\n * Reasoning effort a seat starts at: Supervisor routes, Lead judges, Peer implements.\n * Deliberately short of the top option on either agent — `ultra` and `ultracode`\n * advertise automatic task delegation, which is a second control plane.\n */\nexport const ROLE_THINKING: Record<Role, string> = { supervisor: 'low', lead: 'high', peer: 'high' };\n\n/**\n * The top option on either agent, which Paseo advertises as maximum reasoning with automatic\n * task delegation. Whether it can still delegate once the room has closed the native\n * multi-agent paths is unverified, so selecting one is reported and never rejected.\n */\nexport const DELEGATING_THINKING = ['ultra', 'ultracode'] as const;\n\n/** Paseo profile appearance encodes the room role, independent of agent runtime. */\nexport const ROLE_ICON: Record<Role, string> = { supervisor: 'eye', lead: 'compass', peer: 'code' };\nexport const ROLE_COLOR: Record<Role, string> = { supervisor: 'violet', lead: 'blue', peer: 'emerald' };\n\n/** Paseo shows these to orchestrating agents, so each one says who may open the seat. */\nexport const ROLE_NOTES: Record<Role, string> = {\n supervisor: 'Human-facing routing seat. Opened by Human, never by another agent; cwd, title and provider label do not prove room membership.',\n lead: 'Sole project technical owner. When opening, copy every present profile launch field. Otherwise reuse only with exact current room Lead provider/mode/workspace evidence plus corroborated ownership. Cwd, title and provider label are not membership. Creates Peer seats only.',\n peer: 'One fresh Lead brief. Open by copying every present profile launch field; require exact current room Peer provider/mode/workspace and paseo.parent-agent-id for its Lead. Cwd, title and provider label are not membership; no orchestration.',\n};\n\nexport function providerId(agent: AgentId, role: Role): string {\n return `${agent}-${role}`;\n}\n/** Distinct from the provider id: a host may already have a profile by that name. */\nexport function profileId(agent: AgentId, role: Role): string {\n return `room-${agent}-${role}`;\n}\nexport function providerLabel(agent: AgentId, role: Role): string {\n const title = (value: string): string => value.charAt(0).toUpperCase() + value.slice(1);\n return `${title(agent)} ${title(role)}`;\n}\n","import { join } from 'node:path';\nimport { z } from 'zod';\nimport { readIfPresent } from './fsops.js';\nimport type { Layout } from './layout.js';\nimport { AGENT_IDS, ROLES, type AgentId, type Role } from './roles.js';\n\nexport const MARKER = 'room.json';\n\nconst markerSchema = z.object({\n version: z.string(),\n agents: z.array(z.enum(AGENT_IDS)).min(1),\n roles: z.array(z.enum(ROLES)).min(1),\n /**\n * The rendered contract generation this room was installed from. Optional because a room\n * written before contract provenance existed has no digest, and such a marker must still\n * parse rather than look like a foreign file.\n */\n contract: z.string().min(1).optional(),\n /**\n * False when this room deliberately suppressed the role contract in Claude's `CLAUDE.md`,\n * leaving the plugin as its only Claude carrier. Optional and defaulted to true so a room\n * written before the option existed keeps parsing and keeps its current behaviour.\n */\n claudeMemoryContract: z.boolean().optional(),\n});\nexport type Marker = z.infer<typeof markerSchema>;\n\n/** Deterministic on purpose: re-running setup must not show a phantom change. */\nexport function renderMarker(\n version: string,\n agents: readonly AgentId[],\n roles: readonly Role[],\n contract?: string,\n claudeMemoryContract?: boolean,\n): string {\n return JSON.stringify({\n version, agents: [...agents], roles: [...roles],\n ...(contract === undefined ? {} : { contract }),\n // Written only when it differs from the default, so an unchanged room's marker is unchanged.\n ...(claudeMemoryContract === false ? { claudeMemoryContract: false } : {}),\n } satisfies Marker, null, 2) + '\\n';\n}\n\n/** Records what setup created, so verify and remove touch nothing else. */\nexport async function readMarker(layout: Layout): Promise<Marker | undefined> {\n const source = await readIfPresent(join(layout.roomHome, MARKER));\n if (source === undefined) return undefined;\n try { return markerSchema.parse(JSON.parse(source)); } catch { return undefined; }\n}\n","import { execFile } from 'node:child_process';\nimport { access, constants } from 'node:fs/promises';\nimport { delimiter, isAbsolute, join, resolve } from 'node:path';\nimport { promisify } from 'node:util';\n\nconst run = promisify(execFile);\n\n/**\n * Resolve a command to an absolute executable path on `searchPath`.\n *\n * Deliberately not canonicalised. Version managers point a stable name at a\n * versioned file — `~/.local/bin/claude` at `versions/2.1.267`, mise's\n * `node/latest` at `node/24.15.0` — and the resolved target is deleted by the\n * next upgrade. Providers store this path, so following the link would pin every\n * seat to a binary that stops existing.\n */\nexport async function which(command: string, searchPath: string): Promise<string | undefined> {\n const candidates = isAbsolute(command) || command.includes('/')\n ? [resolve(command)]\n : searchPath.split(delimiter).filter(Boolean).map(entry => join(entry, command));\n for (const candidate of candidates) {\n try {\n await access(candidate, constants.X_OK);\n return candidate;\n } catch { /* try the next PATH entry */ }\n }\n return undefined;\n}\n\nexport interface CommandOutput {\n readonly ok: boolean;\n readonly stdout: string;\n}\n/** Bounded, shell-free probe. Failures are reported, never thrown. */\nexport async function probe(executable: string, args: readonly string[], env: NodeJS.ProcessEnv): Promise<CommandOutput> {\n try {\n const { stdout } = await run(executable, [...args], { env, timeout: 20_000, maxBuffer: 16 * 1024 * 1024, encoding: 'utf8' });\n return { ok: true, stdout };\n } catch {\n return { ok: false, stdout: '' };\n }\n}\n","import { spawn } from 'node:child_process';\nimport { constants } from 'node:os';\nimport { join } from 'node:path';\nimport { lstat } from 'node:fs/promises';\nimport { roleCommand } from './credentials.js';\nimport { resolveLayout, roleHome, type Options } from './layout.js';\nimport { MARKER, readMarker } from './room.js';\nimport { AGENT_IDS, ROLES, type AgentId, type Role } from './roles.js';\nimport { which } from './which.js';\n\nexport const AUTHENTICATION_GUIDE = 'AUTHENTICATION.md';\n/** A truthy empty override suppresses Pi's role-home APPEND_SYSTEM.md discovery. */\nexport const PI_AUTH_ARGV = ['--no-extensions', '--no-approve', '--append-system-prompt', ''] as const;\n\n/** A copy-paste-safe Pi login command that cannot inherit the caller repository cwd. */\nexport function piLoginCommand(rolePath: string, binary: string): string {\n const command = roleCommand({ PI_CODING_AGENT_DIR: rolePath }, binary, PI_AUTH_ARGV);\n return `cd ${roleCommand({}, rolePath)} && ${command}`;\n}\n\nexport interface LoginOutput {\n readonly stdout: (text: string) => void;\n readonly stderr: (text: string) => void;\n}\n\nexport interface LoginSpawnOptions {\n readonly env: NodeJS.ProcessEnv;\n readonly cwd?: string;\n readonly shell: false;\n readonly stdio: 'inherit';\n}\n\nexport interface LoginChild {\n once(event: 'error', listener: (error: Error) => void): this;\n once(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;\n}\n\nexport type LoginSpawner = (executable: string, argv: readonly string[], options: LoginSpawnOptions) => LoginChild;\n\nconst spawnLogin: LoginSpawner = (executable, argv, options) => spawn(executable, [...argv], options);\n\nfunction title(value: string): string {\n return value.charAt(0).toUpperCase() + value.slice(1);\n}\n\nfunction loginInvocation(agent: AgentId, rolePath: string, binary: string): {\n readonly env: Readonly<Record<string, string>>;\n readonly argv: readonly string[];\n readonly cwd?: string;\n readonly command: string;\n} {\n if (agent === 'codex') {\n const env = { CODEX_HOME: rolePath };\n const argv = ['login'] as const;\n return { env, argv, command: roleCommand(env, binary, argv) };\n }\n if (agent === 'claude') {\n const env = { CLAUDE_CONFIG_DIR: rolePath, CLAUDE_SECURESTORAGE_CONFIG_DIR: rolePath };\n const argv = ['auth', 'login'] as const;\n return { env, argv, command: roleCommand(env, binary, argv) };\n }\n const env = { PI_CODING_AGENT_DIR: rolePath };\n const argv = PI_AUTH_ARGV;\n return { env, argv, cwd: rolePath, command: piLoginCommand(rolePath, binary) };\n}\n\n/** Deterministic, secret-free instructions using setup's resolved executables. */\nexport function renderAuthenticationGuide(\n roomHome: string,\n binaries: Readonly<Partial<Record<AgentId, string>>>,\n agents: readonly AgentId[],\n roles: readonly Role[],\n): string {\n const lines = [\n '# Role authentication',\n '',\n 'Setup and verify do not validate authentication, inspect credential contents, query keyrings,',\n 'or test token freshness. Run the command for each role you want to authenticate.',\n '',\n ];\n for (const agent of agents) {\n const binary = binaries[agent];\n if (!binary) throw new Error(`Cannot render authentication guidance without the resolved ${agent} executable.`);\n lines.push(`## ${agent === 'claude' ? 'Claude Code' : title(agent)}`, '');\n for (const role of roles) {\n const invocation = loginInvocation(agent, join(roomHome, 'roles', agent, role), binary);\n lines.push(`### ${title(role)}`, '', '```sh', invocation.command, '```', '');\n if (agent === 'pi') {\n lines.push('Run `/login`, then exit Pi when authentication completes. This minimal interactive',\n 'login session starts in the role home, not the caller repository, disables extension discovery and',\n 'approval files, and suppresses role-home APPEND_SYSTEM.md discovery;',\n 'it is not equivalent to launching the room seat through Paseo.', '');\n }\n }\n }\n return `${lines.join('\\n').trimEnd()}\\n`;\n}\n\nasync function realDirectory(path: string): Promise<'directory' | 'missing' | 'unsafe'> {\n try {\n return (await lstat(path)).isDirectory() ? 'directory' : 'unsafe';\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === 'ENOENT' ? 'missing' : 'unsafe';\n }\n}\n\nfunction usageError(output: LoginOutput, detail: string): number {\n output.stderr(`paseo-room auth login: ${detail}\\n`);\n return 2;\n}\n\nexport interface LoginOptions extends Options {\n readonly env?: NodeJS.ProcessEnv;\n readonly isTTY: boolean;\n readonly spawn?: LoginSpawner;\n}\n\n/** Launch one vendor's normal interactive login without touching credential stores itself. */\nexport async function loginRole(\n agentValue: string,\n roleValue: string,\n options: LoginOptions,\n output: LoginOutput,\n): Promise<number> {\n const agent = AGENT_IDS.find(value => value === agentValue);\n if (!agent) return usageError(output, `unknown agent \"${agentValue}\"; expected codex, claude, or pi.`);\n const role = ROLES.find(value => value === roleValue);\n if (!role) return usageError(output, `unknown role \"${roleValue}\"; expected supervisor, lead, or peer.`);\n if (!options.isTTY) {\n output.stderr('paseo-room auth login requires interactive stdin, stdout, and stderr terminals.\\n');\n return 1;\n }\n\n const env = options.env ?? process.env;\n const layout = resolveLayout(options, env);\n if (await realDirectory(layout.roomHome) !== 'directory') {\n output.stderr(`No room found at ${layout.roomHome}. Run: paseo-room setup --apply\\n`);\n return 1;\n }\n try {\n if (!(await lstat(join(layout.roomHome, MARKER))).isFile()) throw new Error('not a regular marker');\n } catch {\n output.stderr(`No valid room marker found at ${join(layout.roomHome, MARKER)}. Run: paseo-room setup --apply\\n`);\n return 1;\n }\n const marker = await readMarker(layout);\n if (!marker) {\n output.stderr(`No valid room marker found at ${join(layout.roomHome, MARKER)}. Run: paseo-room setup --apply\\n`);\n return 1;\n }\n if (!marker.agents.includes(agent)) {\n output.stderr(`${title(agent)} is not selected in this room. Re-run setup with --agent ${agent} --apply.\\n`);\n return 1;\n }\n if (!marker.roles.includes(role)) {\n output.stderr(`${title(role)} is not installed for ${agent} in this room. Re-run setup --apply.\\n`);\n return 1;\n }\n const rolePath = roleHome(layout, agent, role);\n for (const path of [join(layout.roomHome, 'roles'), join(layout.roomHome, 'roles', agent), rolePath]) {\n if (await realDirectory(path) !== 'directory') {\n output.stderr(`The selected ${agent} ${role} role is not safely installed at ${rolePath}. Run: paseo-room setup --apply\\n`);\n return 1;\n }\n }\n\n const binary = await which(layout.bin[agent], layout.searchPath);\n if (!binary) {\n output.stderr(`${title(agent)} executable not found. Install it, or pass --${agent}-bin /path/to/${agent}.\\n`);\n return 1;\n }\n const invocation = loginInvocation(agent, rolePath, binary);\n if (agent === 'pi') {\n output.stdout(`Starting a minimal interactive Pi login session for ${role} in its role home. Run /login, then exit Pi when authentication completes.\\n`);\n output.stdout('Extensions and approval files are disabled, and role APPEND_SYSTEM.md discovery is suppressed.\\n');\n output.stdout('This is not a room-equivalent Paseo launch.\\n');\n } else {\n output.stdout(`Starting ${agent === 'claude' ? 'Claude Code' : 'Codex'} login for ${role}.\\n`);\n }\n\n const childEnv = { ...env, ...invocation.env };\n const launch = options.spawn ?? spawnLogin;\n return new Promise(resolve => {\n let settled = false;\n const finish = (code: number): void => {\n if (settled) return;\n settled = true;\n resolve(code);\n };\n let child: LoginChild;\n try {\n child = launch(binary, invocation.argv, {\n env: childEnv,\n ...(invocation.cwd === undefined ? {} : { cwd: invocation.cwd }),\n shell: false,\n stdio: 'inherit',\n });\n } catch (error) {\n const detail = error instanceof Error ? error.message : 'unknown error';\n output.stderr(`Could not start ${agent} login: ${detail}\\n`);\n finish(1);\n return;\n }\n child.once('error', error => {\n output.stderr(`Could not start ${agent} login: ${error.message}\\n`);\n finish(1);\n });\n child.once('close', (code, signal) => {\n if (code !== null) {\n finish(code);\n return;\n }\n if (signal) {\n const signalNumber = constants.signals[signal];\n const mapped = typeof signalNumber === 'number' ? 128 + signalNumber : 1;\n output.stderr(`${title(agent)} login ended from signal ${signal}; returning ${String(mapped)}.\\n`);\n finish(mapped);\n return;\n }\n output.stderr(`${title(agent)} login ended without an exit code or signal.\\n`);\n finish(1);\n });\n });\n}\n","import { readFileSync } from 'node:fs';\n\nexport const PROMPT_ASSETS = {\n documents: {\n supervisor: { path: 'documents/supervisor.md', kind: 'head' },\n lead: { path: 'documents/lead.md', kind: 'head' },\n peer: { path: 'documents/peer.md', kind: 'head' },\n workspace: { path: 'documents/workspace.md', kind: 'head' },\n },\n contract: {\n humanAuthority: { path: 'contract/shared/human-authority.md', kind: 'section' },\n workspaceProtocolPrecedence: { path: 'contract/shared-supervisor-lead/workspace-protocol-precedence.md', kind: 'section' },\n evidenceAndEventWaiting: { path: 'contract/shared/evidence-and-event-waiting.md', kind: 'section' },\n scopeAndUnrelatedWork: { path: 'contract/shared/scope-and-unrelated-work.md', kind: 'section' },\n directiveIntegrity: { path: 'contract/supervisor/directive-integrity.md', kind: 'section' },\n technicalNonInterference: { path: 'contract/supervisor/technical-non-interference.md', kind: 'section' },\n leadDiscoveryAndRecovery: { path: 'contract/supervisor/lead-discovery-and-recovery.md', kind: 'section' },\n observationAndAdvice: { path: 'contract/supervisor/observation-and-advice.md', kind: 'section' },\n escalationBoundaries: { path: 'contract/supervisor/escalation-boundaries.md', kind: 'section' },\n projectTechnicalOwnership: { path: 'contract/lead/project-technical-ownership.md', kind: 'section' },\n movingWriteOwnership: { path: 'contract/lead/moving-write-ownership.md', kind: 'section' },\n completePeerBrief: { path: 'contract/lead/complete-peer-brief.md', kind: 'section' },\n challengeSignals: { path: 'contract/shared-lead-peer/challenge-signals.md', kind: 'section' },\n technicalAcceptance: { path: 'contract/lead/technical-acceptance.md', kind: 'section' },\n independentReview: { path: 'contract/lead/independent-review.md', kind: 'section' },\n peerSeatLifecycle: { path: 'contract/lead/peer-seat-lifecycle.md', kind: 'section' },\n boundedOutcome: { path: 'contract/peer/bounded-outcome.md', kind: 'section' },\n independentJudgment: { path: 'contract/peer/independent-judgment.md', kind: 'section' },\n assignmentScope: { path: 'contract/peer/assignment-scope.md', kind: 'section' },\n noOrchestration: { path: 'contract/peer/no-orchestration.md', kind: 'section' },\n reproducibleHandoff: { path: 'contract/peer/reproducible-handoff.md', kind: 'section' },\n noSelfAcceptance: { path: 'contract/peer/no-self-acceptance.md', kind: 'section' },\n },\n workspace: {\n topology: { path: 'workspace/topology.md', kind: 'section' },\n verification: { path: 'workspace/verification.md', kind: 'section' },\n review: { path: 'workspace/review.md', kind: 'section' },\n repositoryConventions: { path: 'workspace/repository-conventions.md', kind: 'section' },\n },\n pi: {\n communicationStyle: { path: 'pi/communication-style.md', kind: 'capsule' },\n runtime: { path: 'pi/runtime.md', kind: 'capsule' },\n },\n} as const;\n\nexport type PromptAssetGroup = keyof typeof PROMPT_ASSETS;\nexport type PromptAssetKey<Group extends PromptAssetGroup> = keyof (typeof PROMPT_ASSETS)[Group];\nexport type ContractKey = PromptAssetKey<'contract'>;\nexport type WorkspaceKey = PromptAssetKey<'workspace'>;\nexport type DocumentKey = PromptAssetKey<'documents'>;\nexport type PiPromptKey = PromptAssetKey<'pi'>;\n\ntype PromptAssetKind = 'head' | 'section' | 'capsule';\ninterface PromptAssetDefinition {\n readonly path: string;\n readonly kind: PromptAssetKind;\n}\n\nexport class PromptAssetError extends Error {\n readonly logicalAsset: string;\n readonly assetUrl: URL;\n\n constructor(logicalAsset: string, assetUrl: URL, detail: string, options?: ErrorOptions) {\n super(`Prompt asset ${logicalAsset} at ${assetUrl.pathname} ${detail} Reinstall paseo-room and try again.`, options);\n this.name = 'PromptAssetError';\n this.logicalAsset = logicalAsset;\n this.assetUrl = assetUrl;\n }\n}\n\nconst cache = new Map<string, string>();\n\nfunction definition<Group extends PromptAssetGroup>(\n group: Group,\n key: PromptAssetKey<Group>,\n): PromptAssetDefinition {\n const assets = PROMPT_ASSETS[group] as Readonly<Record<string, PromptAssetDefinition>>;\n const asset = assets[String(key)];\n if (asset === undefined) throw new Error(`Unknown prompt asset ${group}.${String(key)}.`);\n return asset;\n}\n\nfunction headingCount(source: string, level: 1 | 2): number {\n const prefix = level === 1 ? '# ' : '## ';\n return source.split('\\n').filter(line => line.startsWith(prefix)).length;\n}\n\nfunction validateHeadOrCapsule(source: string, kind: 'head' | 'capsule'): string {\n const trimmed = source.trimEnd();\n if (!trimmed.trim()) throw new Error('is empty.');\n const firstLine = trimmed.split('\\n', 1)[0] ?? '';\n if (!/^# \\S.*$/.test(firstLine) || headingCount(trimmed, 1) !== 1) {\n throw new Error(`${kind === 'head' ? 'document head' : 'Pi capsule'} must begin with exactly one H1 heading.`);\n }\n return trimmed;\n}\n\nfunction validateSection(source: string): string {\n const trimmed = source.trimEnd();\n if (!trimmed.trim()) throw new Error('is empty.');\n const lines = trimmed.split('\\n');\n const heading = lines.shift() ?? '';\n if (!/^## \\S.*$/.test(heading) || headingCount(trimmed, 2) !== 1) {\n throw new Error('section must begin with exactly one H2 heading.');\n }\n if (lines.some(line => /^#{1,6}\\s/.test(line))) {\n throw new Error('section must not contain additional Markdown headings.');\n }\n const body = lines.join('\\n').trim();\n if (!body) throw new Error('section must contain at least one non-empty statement.');\n const statements = body.split(/\\n\\s*\\n/).map(statement =>\n statement.split('\\n').map(line => line.trim()).join(' '),\n );\n if (statements.some(statement => !statement)) {\n throw new Error('section must contain only non-empty statements.');\n }\n return `${heading}\\n${statements.map(statement => `- ${statement}`).join('\\n')}`;\n}\n\nexport function loadPromptAsset<Group extends PromptAssetGroup>(\n group: Group,\n key: PromptAssetKey<Group>,\n): string {\n const logicalAsset = `${group}.${String(key)}`;\n const cached = cache.get(logicalAsset);\n if (cached !== undefined) return cached;\n\n const asset = definition(group, key);\n const assetUrl = new URL(`./prompts/${asset.path}`, import.meta.url);\n try {\n const source = readFileSync(assetUrl, 'utf8');\n if (source.includes('\\uFFFD')) throw new Error('is not valid UTF-8 text.');\n const validated = asset.kind === 'section'\n ? validateSection(source)\n : validateHeadOrCapsule(source, asset.kind);\n cache.set(logicalAsset, validated);\n return validated;\n } catch (error) {\n if (error instanceof PromptAssetError) throw error;\n const detail = error instanceof Error ? error.message : 'could not be read.';\n throw new PromptAssetError(logicalAsset, assetUrl, detail, { cause: error });\n }\n}\n","import { createHash } from 'node:crypto';\nimport { ROLES, type Role } from '../roles.js';\nimport {\n loadPromptAsset,\n type ContractKey,\n type WorkspaceKey,\n} from './prompts.js';\n\nexport type InstructionKind = Role | 'workspace';\n\n// Every role carries the same authority contract; Workspace Protocol Precedence is not part\n// of it. That layer reaches only the seats that read a repository's protocol: the model gives\n// it to Lead, and to Supervisor when auditing, while Peer receives the constraints that bear\n// on its brief quoted into the brief. Telling Peer about the file is the broadcast the model\n// exists to avoid.\nconst AUTHORITY_KEYS = [\n 'humanAuthority',\n 'evidenceAndEventWaiting',\n 'scopeAndUnrelatedWork',\n] as const satisfies readonly ContractKey[];\n\nconst PROTOCOL_READER_KEYS = [\n 'humanAuthority',\n 'workspaceProtocolPrecedence',\n 'evidenceAndEventWaiting',\n 'scopeAndUnrelatedWork',\n] as const satisfies readonly ContractKey[];\n\nconst SHARED_KEYS = {\n supervisor: PROTOCOL_READER_KEYS,\n lead: PROTOCOL_READER_KEYS,\n peer: AUTHORITY_KEYS,\n} as const satisfies Record<Role, readonly ContractKey[]>;\n\nconst ROLE_KEYS = {\n supervisor: [\n 'directiveIntegrity',\n 'technicalNonInterference',\n 'leadDiscoveryAndRecovery',\n 'observationAndAdvice',\n 'escalationBoundaries',\n ],\n lead: [\n 'projectTechnicalOwnership',\n 'movingWriteOwnership',\n 'completePeerBrief',\n 'challengeSignals',\n 'technicalAcceptance',\n 'independentReview',\n 'peerSeatLifecycle',\n ],\n // Peer needs Challenge Signals as well as its own obligations.\n peer: [\n 'challengeSignals',\n 'boundedOutcome',\n 'independentJudgment',\n 'assignmentScope',\n 'noOrchestration',\n 'reproducibleHandoff',\n 'noSelfAcceptance',\n ],\n} as const satisfies Record<Role, readonly ContractKey[]>;\n\nconst ALL_PROTOCOL_KEYS = [\n 'topology',\n 'verification',\n 'review',\n 'repositoryConventions',\n] as const satisfies readonly WorkspaceKey[];\n\n// The workspace layer belongs to the seats that own workflow: Lead decides it and\n// Supervisor audits it. Peer receives none of it, so its attention stays on one brief and\n// the brief remains the only channel for repository-local constraints.\nconst PROTOCOL_KEYS = {\n supervisor: ALL_PROTOCOL_KEYS,\n lead: ALL_PROTOCOL_KEYS,\n peer: [],\n} as const satisfies Record<Role, readonly WorkspaceKey[]>;\n\nexport function instructionKeys(role: Role): readonly ContractKey[] {\n // Every role carries the shared authority contract plus its own obligations.\n return [...SHARED_KEYS[role], ...ROLE_KEYS[role]];\n}\n\nexport function protocolKeys(role: Role): readonly WorkspaceKey[] {\n return PROTOCOL_KEYS[role];\n}\n\nfunction protocol(keys: readonly WorkspaceKey[]): string[] {\n // A preface introducing sections that follow is noise when none of them do.\n if (keys.length === 0) return [];\n return [\n loadPromptAsset('documents', 'workspace'),\n ...keys.map(key => loadPromptAsset('workspace', key)),\n ];\n}\n\nexport function renderInstructions(kind: InstructionKind): string {\n if (kind === 'workspace') return protocol(ALL_PROTOCOL_KEYS).join('\\n\\n') + '\\n';\n return [\n loadPromptAsset('documents', kind),\n ...instructionKeys(kind).map(key => loadPromptAsset('contract', key)),\n ...protocol(protocolKeys(kind)),\n ].join('\\n\\n') + '\\n';\n}\n\n/** Every document the room composes, in one fixed order, so a digest over them is stable. */\nexport const INSTRUCTION_KINDS = [...ROLES, 'workspace'] as const satisfies readonly InstructionKind[];\n\n/**\n * Identifies the rendered contract generation a room was installed from.\n *\n * Derived from the composed documents rather than the package version: two packages that\n * render identical contracts are the same generation, and editing one prompt asset without a\n * release still changes the digest. Truncated because this is provenance an operator compares\n * by eye, not a security claim.\n */\nexport function contractDigest(): string {\n const hash = createHash('sha256');\n for (const kind of INSTRUCTION_KINDS) hash.update(`${kind}\\u0000${renderInstructions(kind)}\\u0000`);\n return `sha256:${hash.digest('hex').slice(0, 16)}`;\n}\n","import { fail, type Check } from '../result.js';\n\n/**\n * The bounded heuristic: `paseo` as a whole identifier or path token, including a\n * lower-to-upper camel-case boundary. It is not embedded in a larger word, so `paseo`,\n * `paseo-mcp`, `/opt/paseo/bin/serve` and `paseoRoom` match while `grapaseo`,\n * `paseonaut` and `PASEONAUT` do not.\n *\n * This recognizes an obvious configuration collision and says why it matched. It is not a\n * scanner for a hostile or obfuscated endpoint, and matching nothing proves nothing.\n */\nconst PASEO_TOKEN = /(?<![\\p{L}\\p{N}])[Pp][Aa][Ss][Ee][Oo](?=$|[^\\p{L}\\p{N}]|\\p{Lu}\\p{Ll})/u;\n\n/** Declaration fields that name what a server runs or connects to. */\nconst VALUE_FIELDS = ['command', 'url', 'serverUrl', 'httpUrl', 'endpoint'] as const;\n/** Declaration fields that carry a list of such values. */\nconst LIST_FIELDS = ['args'] as const;\n\n/** One recognizable declaration, kept so the diagnostic can state its own evidence. */\nexport interface McpMatch {\n readonly server: string;\n /** `name`, or the declaration field that carried the token. */\n readonly field: 'name' | (typeof VALUE_FIELDS)[number] | (typeof LIST_FIELDS)[number];\n readonly value: string;\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\n/** An MCP declaration map exactly as an already-parsed config carries it. */\nexport function serverTable(value: unknown): Record<string, unknown> {\n return asRecord(value) ?? {};\n}\n\n/** Names one side declares and the other does not, in both directions. */\nexport interface NameDivergence {\n /** Declared for the operator but absent from the compared side. */\n readonly missing: readonly string[];\n /** Declared by the compared side but no longer by the operator. */\n readonly extra: readonly string[];\n}\n\n/**\n * Compare two declaration maps by server name alone. Used for seed-once runtime state the\n * room must not synchronize: a name difference is reportable, and nothing about what those\n * servers run is compared, copied, or written back.\n */\nexport function serverNameDivergence(\n operator: Readonly<Record<string, unknown>>,\n compared: Readonly<Record<string, unknown>>,\n): NameDivergence | undefined {\n const operatorNames = new Set(Object.keys(operator));\n const comparedNames = new Set(Object.keys(compared));\n const missing = [...operatorNames].filter(name => !comparedNames.has(name)).sort();\n const extra = [...comparedNames].filter(name => !operatorNames.has(name)).sort();\n return missing.length === 0 && extra.length === 0 ? undefined : { missing, extra };\n}\n\n/**\n * The declaration maps inside a JSON configuration file, read through the named keys only:\n * nothing else in the document — history, credentials, runtime state — is inspected.\n *\n * Every named key is merged, in the order given, because an agent that accepts more than one\n * key loads all of them: stopping at the first table would let a benign one hide a Paseo\n * declaration under a later key. A name declared twice keeps the earlier key's entry at its\n * own name and the later one under a key-qualified name, so no declaration is lost. Invalid\n * JSON, a non-object root, or a named declaration value that is not an object is rejected:\n * an unparseable source cannot truthfully be reported as inspected and clean.\n */\nexport function jsonServerTable(source: string | undefined, keys: readonly string[]): Record<string, unknown> {\n if (source === undefined) return {};\n const root = asRecord(JSON.parse(source));\n if (!root) throw new TypeError('MCP configuration must be a JSON object.');\n const merged: Record<string, unknown> = {};\n for (const key of keys) {\n const value = root[key];\n if (value === undefined) continue;\n const table = asRecord(value);\n if (!table) throw new TypeError(`${key} must be a JSON object.`);\n for (const [server, declaration] of Object.entries(table)) {\n merged[server in merged ? `${server} (${key})` : server] = declaration;\n }\n }\n return merged;\n}\n\n/** Every recognizably Paseo-related declaration, with the evidence that recognized it. */\nexport function detectPaseoServers(servers: Readonly<Record<string, unknown>>): McpMatch[] {\n const matches: McpMatch[] = [];\n for (const [server, declaration] of Object.entries(servers)) {\n if (PASEO_TOKEN.test(server)) matches.push({ server, field: 'name', value: server });\n const fields = asRecord(declaration);\n if (!fields) continue;\n for (const field of VALUE_FIELDS) {\n const value = fields[field];\n if (typeof value === 'string' && PASEO_TOKEN.test(value)) matches.push({ server, field, value });\n }\n for (const field of LIST_FIELDS) {\n const list = fields[field];\n if (!Array.isArray(list)) continue;\n for (const item of list) {\n if (typeof item === 'string' && PASEO_TOKEN.test(item)) matches.push({ server, field, value: item });\n }\n }\n }\n return matches;\n}\n\nfunction evidence(match: McpMatch): string {\n return match.field === 'name' ? `${match.server} (server name)` : `${match.server} (${match.field}: ${match.value})`;\n}\n\n/**\n * Paseo is the room's only control plane, so a Peer-visible MCP server that looks like a\n * second one fails before anything is applied. The room never edits operator configuration:\n * the fix names the source file and leaves the decision with the operator.\n */\nexport function paseoMcpCheck(id: string, path: string, servers: Readonly<Record<string, unknown>>): Check | undefined {\n const matches = detectPaseoServers(servers);\n if (matches.length === 0) return undefined;\n return fail(id,\n `${path} declares MCP servers that are recognizably Paseo-related: ${matches.map(evidence).join('; ')}.`,\n `Remove or rename those servers in ${path} so no room seat reaches Paseo outside its own seat, then run setup again. paseo-room never edits your MCP configuration, and this name check is a bounded heuristic rather than a sandbox.`);\n}\n","import { readdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { Entry } from '../fsops.js';\nimport type { Role } from '../roles.js';\n\n/** The one operator resource Peer receives as an exact projection rather than an alias. */\nexport const SKILLS = 'skills';\n\n/** A room-owned orchestration skill: advertised to seats that orchestrate, never to Peer. */\nfunction isPaseoSkill(name: string): boolean {\n return name.toLowerCase().startsWith('paseo');\n}\n\n/**\n * Peer has no room tools, so the room also stops loading orchestration surfaces into it.\n * This closes known configuration paths — Peer still has a shell, so it is not containment.\n */\nfunction receivesExecutableResources(role: Role): boolean {\n return role !== 'peer';\n}\n\n/** Names under the operator skills directory; a missing directory is an empty projection. */\nasync function skillNames(path: string): Promise<string[]> {\n try { return (await readdir(path)).filter(name => !isPaseoSkill(name)).sort(); } catch (error) {\n if (error !== null && typeof error === 'object' && 'code' in error && error.code === 'ENOENT') return [];\n throw error;\n }\n}\n\nexport interface RoleResourceInput {\n readonly role: Role;\n /** The role home every generated alias is created inside. */\n readonly target: string;\n /** The operator agent home the shared resources are read from. */\n readonly home: string;\n /** Shared resource basenames in the adapter's declared order, present or not. */\n readonly names: readonly string[];\n /** Absolute operator paths that exist, probed once for every role. */\n readonly shared: readonly string[];\n /** Basenames whose contents can run code, withheld from Peer. */\n readonly executable: readonly string[];\n}\n\n/**\n * Supervisor and Lead keep one alias per shared operator resource that exists, so they never\n * gain a broken link. Peer receives no executable resource, and its `skills` becomes an exact\n * managed directory of links to the non-`paseo*` operator skills, so an inventory change\n * cannot leave it silently stale.\n *\n * Peer's projection is declared even when the operator deleted the whole skills directory:\n * an empty managed directory is what lets a later run remove yesterday's child links, or\n * migrate the legacy whole-directory symlink, instead of leaving them unreconciled.\n */\nexport async function roleResourceEntries(input: RoleResourceInput): Promise<Entry[]> {\n const present = new Set(input.shared);\n const executable = new Set(input.executable);\n const entries: Entry[] = [];\n for (const name of input.names) {\n const path = join(input.home, name);\n const alias = join(input.target, name);\n if (!receivesExecutableResources(input.role)) {\n if (executable.has(name)) continue;\n if (name === SKILLS) {\n const children = present.has(path) ? await skillNames(path) : [];\n entries.push({ kind: 'managed-dir', path: alias, children, legacyLink: path });\n for (const child of children) entries.push({ kind: 'link', path: join(alias, child), target: join(path, child) });\n continue;\n }\n }\n if (!present.has(path)) continue;\n entries.push({ kind: 'link', path: alias, target: path });\n }\n return entries;\n}\n","import { readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport {\n ambientNamesCheck, configuredByNamesCheck, inspectCredentialPath, presentNames, preservedCredentialCheck,\n roleCommand, type CredentialDiagnostic,\n} from '../credentials.js';\nimport type { Layout } from '../layout.js';\nimport { roleHome } from '../layout.js';\nimport type { Entry } from '../fsops.js';\nimport { existingPaths, exists, readIfPresent } from '../fsops.js';\nimport { fail, pass, warn, type Check } from '../result.js';\nimport type { Role } from '../roles.js';\nimport { renderInstructions } from '../room/instructions.js';\nimport { which } from '../which.js';\nimport { jsonServerTable, paseoMcpCheck, serverNameDivergence, type NameDivergence } from './mcp.js';\nimport { roleResourceEntries } from './resources.js';\nimport type { Agent, AgentPlan, BuildOptions } from './types.js';\n\n/** Operator-authored resources shared by reference; native agent definitions stay out. */\nconst SHARED = [\n 'skills', 'plugins', 'commands', 'hooks', 'rules',\n 'output-styles', 'keybindings.json', 'themes',\n] as const;\n/** These carry executable prompts, plugin code, and hook programs: never shared with Peer. */\nconst EXECUTABLE = ['plugins', 'commands', 'hooks'] as const;\n/** Claude keeps personal MCP declarations under this one key of its runtime state. */\nconst MCP_KEY = 'mcpServers';\nconst AUTH_ENV = [\n 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_API_KEY', 'CLAUDE_CODE_OAUTH_TOKEN',\n 'CLAUDE_CODE_USE_BEDROCK', 'CLAUDE_CODE_USE_VERTEX', 'CLAUDE_CODE_USE_FOUNDRY',\n] as const;\nconst CONTROL_PLANE_ENV = {\n CLAUDE_CODE_DISABLE_AGENT_VIEW: '1',\n CLAUDE_CODE_DISABLE_WORKFLOWS: '1',\n} as const;\nconst SECURE_STORAGE_ENV = 'CLAUDE_SECURESTORAGE_CONFIG_DIR';\n/** Copied once so a fresh role home does not re-run interactive onboarding. */\nconst SEEDED_KEYS = ['hasCompletedOnboarding', 'theme', 'installMethod', 'userID', MCP_KEY] as const;\n\nfunction asObject(value: unknown): Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value) ? { ...value } : {};\n}\n/** Any unreadable or non-object source is simply an empty starting point. */\nfunction readObject(source: string | undefined): Record<string, unknown> {\n try { return asObject(source === undefined ? {} : JSON.parse(source)); } catch { return {}; }\n}\n\n/** Read optional runtime state, but do not turn an inspection failure into \"no servers\". */\nasync function readStateIfPresent(path: string): Promise<string | undefined> {\n try { return await readFile(path, 'utf8'); } catch (error) {\n if (error !== null && typeof error === 'object' && 'code' in error && error.code === 'ENOENT') return undefined;\n throw error;\n }\n}\n\n/** Keep operator configuration while closing non-Paseo inbound coordination. */\nexport function renderRoleSettings(source: string | undefined, role: Role, secureStorageDir?: string): string {\n const settings = readObject(source);\n // Claude applies settings.env after the launch environment, so repeat these\n // provider pins here after operator values to make them effective.\n settings.env = {\n ...asObject(settings.env),\n ...CONTROL_PLANE_ENV,\n PASEO_ROOM_ROLE: role,\n ...(secureStorageDir === undefined ? {} : { [SECURE_STORAGE_ENV]: secureStorageDir }),\n };\n // These restrictive settings cannot be weakened by another settings scope.\n settings.disableAgentView = true;\n settings.disableWorkflows = true;\n settings.crossSessionInbound = 'refuse';\n return JSON.stringify(settings, null, 2) + '\\n';\n}\n\nexport function renderRoleState(source: string | undefined): string {\n const root = readObject(source);\n const state: Record<string, unknown> = { hasCompletedOnboarding: true };\n for (const key of SEEDED_KEYS) if (key in root) state[key] = root[key];\n return JSON.stringify(state, null, 2) + '\\n';\n}\n\n/**\n * Preserve the operator's global memory, then add the stronger room role contract.\n *\n * With the contract suppressed, the file carries the operator's memory alone: the plugin is\n * then the room's only Claude contract carrier. Returning `undefined` for an operator with no\n * global memory keeps the room from writing a file whose whole content it just removed.\n */\nexport function renderRoleMemory(source: string | undefined, role: Role, contract = true): string | undefined {\n const operator = source?.trim();\n if (!contract) return operator ? `${operator}\\n` : undefined;\n return operator ? `${operator}\\n\\n${renderInstructions(role)}` : renderInstructions(role);\n}\n\n/** Detect only configuration names; never inspect environment or settings values. */\nexport function claudeAuthMethodNames(settingsSource: string | undefined, envNames: ReadonlySet<string>): string[] {\n const settings = readObject(settingsSource);\n const settingsEnv = asObject(settings.env);\n const names = new Set(presentNames(envNames, AUTH_ENV));\n for (const name of AUTH_ENV) if (Object.hasOwn(settingsEnv, name)) names.add(name);\n if (Object.hasOwn(settings, 'apiKeyHelper')) names.add('apiKeyHelper');\n return [...names];\n}\n\nexport async function claudeCredentialDiagnostic(\n layout: Layout,\n role: Role,\n settingsSource: string | undefined,\n platform: NodeJS.Platform = process.platform,\n binary = 'claude',\n): Promise<CredentialDiagnostic> {\n const home = roleHome(layout, 'claude', role);\n const path = join(home, '.credentials.json');\n const roleEnvironment = { CLAUDE_CONFIG_DIR: home, [SECURE_STORAGE_ENV]: home };\n const login = roleCommand(roleEnvironment, binary, ['auth', 'login']);\n const status = roleCommand(roleEnvironment, binary, ['auth', 'status']);\n const state = await inspectCredentialPath(path);\n const id = `claude.auth.${role}`;\n if (state.kind !== 'missing') {\n return { path, checks: [preservedCredentialCheck({ id, agent: 'Claude', role, path, state, login, status })] };\n }\n const configured = claudeAuthMethodNames(settingsSource, new Set());\n if (configured.length > 0) return { path, checks: [configuredByNamesCheck(id, 'Claude', role, configured)] };\n const ambient = presentNames(layout.envNames, AUTH_ENV);\n if (ambient.length > 0) return { path, checks: [ambientNamesCheck(id, 'Claude', role, ambient)] };\n if (platform === 'darwin') {\n return { path, checks: [{\n id: `${id}.native-keyring-unverifiable`, status: 'warn',\n message: `Claude ${role} auth: native-keyring unverifiable; the current runtime's secure-storage location is pinned to this role home, but no Keychain entry was queried and older runtime behavior was not assumed. Token validity and freshness were not checked.`,\n fix: `Authenticate this role with: ${login}. If that subcommand is unavailable, launch ${roleCommand(roleEnvironment, binary)} and run /login. Check status with: ${status}.`,\n }] };\n }\n return { path, checks: [{\n id: `${id}.login-required`, status: 'warn',\n message: `Claude ${role} auth: login-required; no role-owned .credentials.json or configured environment/static auth method was detected. Authentication was not attempted.`,\n fix: `Authenticate this role with: ${login}. If that subcommand is unavailable, launch ${roleCommand(roleEnvironment, binary)} and run /login. Check status with: ${status}.`,\n }] };\n}\n\n/**\n * `.claude.json` is seeded once and runtime-owned afterwards, so a later change to the\n * operator's own MCP inventory never reaches a role home. That is reported rather than\n * repaired: rewriting the file would discard whatever the runtime has since stored in it.\n * Only declared names are compared — no command, URL, argument, credential or history value\n * is read for this check.\n */\nfunction mcpDriftCheck(role: Role, home: string, path: string, divergence: NameDivergence): Check {\n const parts = [\n ...(divergence.missing.length === 0 ? [] : [`not declared for this role: ${divergence.missing.join(', ')}`]),\n ...(divergence.extra.length === 0 ? [] : [`declared only for this role: ${divergence.extra.join(', ')}`]),\n ];\n return warn(`claude.mcp.drift.${role}`,\n `Claude ${role} MCP server names differ from your own Claude MCP servers (${parts.join('; ')}). ${path} is seeded once and owned by Claude afterwards, so paseo-room did not change it; only server names were compared.`,\n `If this role should have the same servers, add them with: CLAUDE_CONFIG_DIR=${home} claude mcp add ... — or delete ${path} and run setup --apply to reseed it from your current Claude state, which discards that role's other runtime state.`);\n}\n\nexport const claudeAgent: Agent = {\n id: 'claude',\n label: 'Claude Code',\n homeEnv: 'CLAUDE_CONFIG_DIR',\n // Agent View and dynamic workflows have entry points beyond model tool calls.\n providerEnv: CONTROL_PLANE_ENV,\n defaultModeId: 'bypassPermissions',\n // Keep the legacy Task name and block current native orchestration,\n // shared task/cron coordination, and cross-session paths. Paseo alone owns\n // agent lifecycle and coordination.\n pins: {\n disallowedTools: [\n 'Task', 'Agent', 'Workflow', 'ListAgents', 'SendMessage', 'TeamCreate', 'TeamDelete',\n 'TaskCreate', 'TaskGet', 'TaskList', 'TaskUpdate',\n 'CronCreate', 'CronDelete', 'CronList',\n ],\n },\n async build(layout: Layout, roles: readonly Role[], options: BuildOptions = {}): Promise<AgentPlan> {\n const home = layout.agentHome.claude;\n const binary = await which(layout.bin.claude, layout.searchPath);\n if (!binary) {\n return { entries: [], checks: [fail('claude.bin', 'Claude Code executable not found.', 'Install Claude Code, or pass --claude-bin /path/to/claude.')] };\n }\n if (!(await exists(home))) {\n return { entries: [], checks: [fail('claude.home', `No Claude config directory at ${home}.`, 'Run claude once to initialise it, or pass --claude-home.')] };\n }\n const checks: Check[] = [pass('claude.home', `Claude Code found at ${binary} using ${home}.`)];\n\n const settingsSource = await readIfPresent(join(home, 'settings.json'));\n const memorySource = await readIfPresent(join(home, 'CLAUDE.md'));\n let stateSource: string | undefined;\n let operatorServers: Record<string, unknown>;\n try {\n stateSource = await readStateIfPresent(layout.claudeState);\n // `.claude.json` is runtime-owned after the seed write, so only this one key is interpreted.\n operatorServers = jsonServerTable(stateSource, [MCP_KEY]);\n } catch {\n return { entries: [], checks: [...checks, fail('claude.mcp',\n `Could not read ${layout.claudeState} as a JSON object, so its MCP declarations could not be inspected.`,\n 'Make your Claude state file readable and fix its JSON structure, then run setup again.')] };\n }\n const stateConflict = paseoMcpCheck('claude.mcp', layout.claudeState, operatorServers);\n if (stateConflict) return { entries: [], checks: [...checks, stateConflict] };\n const shared = await existingPaths(home, SHARED);\n const entries: Entry[] = [];\n const credentials: CredentialDiagnostic[] = [];\n const providerEnv: Partial<Record<Role, Readonly<Record<string, string>>>> = {};\n // Held back so a hard conflict found in a later role is never preceded by advice.\n const drift: Check[] = [];\n for (const role of roles) {\n const target = roleHome(layout, 'claude', role);\n const statePath = join(target, '.claude.json');\n // A seeded role home keeps its own copy, so its declarations are checked as well.\n let roleStateSource: string | undefined;\n let roleServers: Record<string, unknown>;\n try {\n roleStateSource = await readStateIfPresent(statePath);\n roleServers = jsonServerTable(roleStateSource, [MCP_KEY]);\n } catch {\n return { entries: [], checks: [...checks, fail(`claude.mcp.${role}`,\n `Could not read ${statePath} as a JSON object, so its MCP declarations could not be inspected.`,\n 'Make that role-owned Claude state file readable and fix its JSON structure, then run setup again.')] };\n }\n const roleConflict = paseoMcpCheck(`claude.mcp.${role}`, statePath, roleServers);\n if (roleConflict) return { entries: [], checks: [...checks, roleConflict] };\n // Only an already-seeded role home can have drifted: an absent one is about to be\n // seeded from the same operator state this run just read.\n if (roleStateSource !== undefined) {\n const divergence = serverNameDivergence(operatorServers, roleServers);\n if (divergence) drift.push(mcpDriftCheck(role, target, statePath, divergence));\n }\n entries.push({ kind: 'dir', path: target });\n const memoryPath = join(target, 'CLAUDE.md');\n const memory = renderRoleMemory(memorySource, role, options.memoryContract ?? true);\n // Suppressed with no operator memory to carry: remove any file an earlier run wrote,\n // so a stale contract generation cannot outlive the option that turned it off.\n entries.push(memory === undefined\n ? { kind: 'absent', path: memoryPath }\n : { kind: 'file', path: memoryPath, content: memory });\n entries.push({ kind: 'file', path: join(target, 'settings.json'), content: renderRoleSettings(settingsSource, role, target) });\n entries.push({ kind: 'file', path: statePath, content: renderRoleState(stateSource), once: true });\n entries.push(...await roleResourceEntries({ role, target, home, names: SHARED, shared, executable: EXECUTABLE }));\n credentials.push(await claudeCredentialDiagnostic(layout, role, settingsSource, process.platform, binary));\n providerEnv[role] = { [SECURE_STORAGE_ENV]: target };\n }\n return { entries, credentials, checks: [...checks, ...drift], binary, providerEnv };\n },\n};\n","import { join } from 'node:path';\nimport { parse, stringify, type TomlTable } from 'smol-toml';\nimport { inspectCredentialPath, preservedCredentialCheck, roleCommand, type CredentialDiagnostic } from '../credentials.js';\nimport type { Layout } from '../layout.js';\nimport { roleHome } from '../layout.js';\nimport type { Entry } from '../fsops.js';\nimport { existingPaths, readIfPresent } from '../fsops.js';\nimport { fail, pass, type Check } from '../result.js';\nimport type { Role } from '../roles.js';\nimport { renderInstructions } from '../room/instructions.js';\nimport { probe, which } from '../which.js';\nimport { paseoMcpCheck, serverTable } from './mcp.js';\nimport { roleResourceEntries } from './resources.js';\nimport type { Agent, AgentPlan } from './types.js';\n\n/** Read-only operator resources every role shares by reference, never by copy. */\nconst SHARED = ['AGENTS.md', 'skills', 'plugins', 'hooks.json'] as const;\n/** Plugins and hooks run operator code, so Peer — which has no room tools — never loads them. */\nconst EXECUTABLE = ['plugins', 'hooks.json'] as const;\nconst CATALOG = 'model-catalog.json';\nexport type CodexCredentialStore = 'file' | 'ephemeral' | 'auto' | 'keyring' | 'unknown';\n\nfunction table(parent: TomlTable, key: string): TomlTable {\n const value = parent[key];\n if (value === undefined || typeof value !== 'object' || Array.isArray(value) || value instanceof Date) {\n return (parent[key] = {});\n }\n return value;\n}\n\n/**\n * Close Codex's native multi-agent features inside one scope: the top-level table, or an\n * active profile, which outranks it.\n */\nfunction pinMultiAgentFeatures(scope: TomlTable): void {\n const features = table(scope, 'features');\n features.multi_agent = false;\n // Newer configs represent v2 as a table; keep that shape rather than writing a\n // boolean at the same key, which would be a TOML conflict.\n if (typeof features.multi_agent_v2 === 'boolean' || features.multi_agent_v2 === undefined) features.multi_agent_v2 = false;\n else table(features, 'multi_agent_v2').enabled = false;\n}\n\nexport interface RoleConfigInput {\n readonly roleDocument: string;\n readonly catalogPath?: string;\n}\n/**\n * Copy the operator's config, then override only the keys the room owns.\n *\n * `model_instructions_file` is deliberately untouched: it *replaces* Codex's base\n * prompt, so writing it would mean vendoring and maintaining a full copy of that\n * prompt. The room contract is additive and belongs in `developer_instructions`.\n */\nexport function renderRoleConfig(source: TomlTable, input: RoleConfigInput): string {\n const config = structuredClone(source);\n config.sandbox_mode = 'danger-full-access';\n config.approval_policy = 'never';\n config.developer_instructions = input.roleDocument;\n if (input.catalogPath) config.model_catalog_json = input.catalogPath;\n // Codex's own multi-agent mode would compete with the room's role contract.\n // `[agents]` stays top-level only: Codex profiles have no such key.\n table(config, 'agents').enabled = false;\n pinMultiAgentFeatures(config);\n // An active profile outranks the top-level keys, so every room-owned key a profile can\n // also carry — sandbox, approval, catalog, features — has to land there too.\n if (typeof config.profile === 'string') {\n const profile = table(table(config, 'profiles'), config.profile);\n profile.sandbox_mode = 'danger-full-access';\n profile.approval_policy = 'never';\n if (input.catalogPath) profile.model_catalog_json = input.catalogPath;\n pinMultiAgentFeatures(profile);\n }\n return stringify(config) + '\\n';\n}\n\nexport function renderCatalog(catalog: unknown): string {\n return JSON.stringify(catalog, (key, value: unknown) => (key === 'multi_agent_version' ? null : value), 2) + '\\n';\n}\n\n/** Facts the captured catalog itself carries. Nothing is inferred beyond them. */\nexport interface CatalogEvidence {\n /** Codex reads the catalog as a JSON object, so any other top-level shape is not one. */\n readonly object: boolean;\n /** How many `multi_agent_version` fields the capture carried, and the copy therefore nulls. */\n readonly markers: number;\n}\n\nexport function catalogEvidence(catalog: unknown): CatalogEvidence {\n let markers = 0;\n const walk = (value: unknown): void => {\n if (Array.isArray(value)) { for (const item of value) walk(item); return; }\n if (value === null || typeof value !== 'object') return;\n for (const [key, nested] of Object.entries(value)) {\n if (key === 'multi_agent_version') markers += 1;\n else walk(nested);\n }\n };\n walk(catalog);\n return { object: catalog !== null && typeof catalog === 'object' && !Array.isArray(catalog), markers };\n}\n\n/** Read only the generated config's non-secret store selector. */\nexport function codexCredentialStore(config: TomlTable): CodexCredentialStore {\n const value = config.cli_auth_credentials_store;\n return value === 'file' || value === 'ephemeral' || value === 'auto' || value === 'keyring'\n ? value\n : 'unknown';\n}\n\nasync function credentialDiagnostic(\n layout: Layout,\n role: Role,\n store: CodexCredentialStore,\n binary: string,\n): Promise<CredentialDiagnostic> {\n const home = roleHome(layout, 'codex', role);\n const path = join(home, 'auth.json');\n const login = roleCommand({ CODEX_HOME: home }, binary, ['login']);\n const status = roleCommand({ CODEX_HOME: home }, binary, ['login', 'status']);\n const state = await inspectCredentialPath(path);\n const id = `codex.auth.${role}`;\n const checks: Check[] = [];\n if (state.kind !== 'missing') {\n checks.push(preservedCredentialCheck({ id, agent: 'Codex', role, path, state, login, status }));\n } else {\n if (store === 'keyring' || store === 'auto') {\n checks.push({\n id: `${id}.native-keyring-unverifiable`, status: 'warn',\n message: `Codex ${role} auth: native-keyring unverifiable; cli_auth_credentials_store is ${store}, and no keyring was queried. Token validity and freshness were not checked.`,\n fix: `Authenticate this role with: ${login}. Check status with: ${status}.`,\n });\n } else {\n const apiKey = layout.envNames.has('OPENAI_API_KEY')\n ? ' OPENAI_API_KEY is present only in the setup process; Codex has not stored it for this role and paseo-room does not copy it into the provider.'\n : '';\n const detail = store === 'ephemeral'\n ? 'cli_auth_credentials_store is ephemeral, so no persistent credential file is expected'\n : `no role-owned auth.json exists${store === 'file' ? ' for the configured file store' : ''}`;\n checks.push({\n id: `${id}.login-required`, status: 'warn',\n message: `Codex ${role} auth: login-required; ${detail}.${apiKey} Authentication was not attempted.`,\n fix: `Authenticate this role with: ${login}. Check status with: ${status}.`,\n });\n }\n }\n if (state.kind !== 'missing' && (store === 'keyring' || store === 'auto')) {\n checks.push({\n id: `${id}.native-keyring-unverifiable`, status: 'warn',\n message: `Codex ${role} auth: native-keyring unverifiable; cli_auth_credentials_store is ${store}, and the preserved auth.json does not prove what the runtime will use. No keyring was queried.`,\n fix: `Check status without exposing credentials: ${status}.`,\n });\n }\n return { path, checks };\n}\n\nexport const codexAgent: Agent = {\n id: 'codex',\n label: 'Codex',\n homeEnv: 'CODEX_HOME',\n defaultModeId: 'full-access',\n // Without these, Paseo's own mode preset (default auto-review) is sent to the\n // app-server and outranks the sandbox/approval keys in the generated config.\n pins: { params: { sandbox_mode: 'danger-full-access', approval_policy: 'never' } },\n async build(layout: Layout, roles: readonly Role[]): Promise<AgentPlan> {\n const checks: Check[] = [];\n const home = layout.agentHome.codex;\n const binary = await which(layout.bin.codex, layout.searchPath);\n if (!binary) {\n return { entries: [], checks: [fail('codex.bin', 'Codex executable not found.', 'Install Codex, or pass --codex-bin /path/to/codex.')] };\n }\n const configPath = join(home, 'config.toml');\n const raw = await readIfPresent(configPath);\n if (raw === undefined) {\n return { entries: [], checks: [fail('codex.home', `No config.toml in ${home}.`, 'Run codex once to initialise it, or pass --codex-home.')] };\n }\n let source: TomlTable;\n try { source = parse(raw); } catch {\n return { entries: [], checks: [fail('codex.config', `Could not read ${configPath} as TOML.`, 'Fix the syntax in your Codex config, then run setup again.')] };\n }\n checks.push(pass('codex.home', `Codex found at ${binary} using ${home}.`));\n // Paseo is the room's only control plane, so a Paseo-looking MCP server fails here,\n // before any managed path is written, rather than being filtered out of the copy.\n const conflict = paseoMcpCheck('codex.mcp', configPath, serverTable(source.mcp_servers));\n if (conflict) return { entries: [], checks: [...checks, conflict] };\n const store = codexCredentialStore(source);\n\n const entries: Entry[] = [];\n const credentials: CredentialDiagnostic[] = [];\n\n // The scrubbed catalog is one of the room's three native multi-agent closures, so a\n // catalog it cannot capture is a build failure, not a silent fall back to the\n // built-in catalog and its collaboration metadata.\n const capture = roleCommand({ CODEX_HOME: home }, binary, ['debug', 'models']);\n const models = await probe(binary, ['debug', 'models'], { HOME: layout.home, CODEX_HOME: home, PATH: layout.searchPath });\n if (!models.ok) {\n return { entries: [], checks: [...checks, fail('codex.catalog',\n 'Codex model catalog unavailable, so native multi-agent metadata cannot be removed.',\n `Run ${capture} to see why it failed, upgrade Codex to a version that prints the JSON catalog, then run setup again.`)] };\n }\n let catalogSource: string;\n let evidence: CatalogEvidence;\n try {\n const parsed: unknown = JSON.parse(models.stdout);\n evidence = catalogEvidence(parsed);\n catalogSource = renderCatalog(parsed);\n } catch {\n return { entries: [], checks: [...checks, fail('codex.catalog',\n 'Codex model catalog was not valid JSON, so native multi-agent metadata cannot be removed.',\n `Check the output of ${capture}, upgrade Codex if it does not print a JSON catalog, then run setup again.`)] };\n }\n // A JSON scalar or array parses but is not a catalog: writing it would point every role\n // at a file Codex cannot load, which is the same closure failure as no catalog at all.\n if (!evidence.object) {\n return { entries: [], checks: [...checks, fail('codex.catalog',\n 'Codex printed valid JSON that is not a model catalog object, so native multi-agent metadata cannot be removed.',\n `Check the output of ${capture}, upgrade Codex to a version that prints the JSON catalog object, then run setup again.`)] };\n }\n checks.push(pass('codex.catalog', evidence.markers === 0\n ? `Codex model catalog captured from ${capture}; it declared no multi_agent_version field, and each role home gets that generated copy instead of Codex's built-in catalog.`\n : `Codex model catalog captured from ${capture}; ${String(evidence.markers)} multi_agent_version field(s) are nulled in the generated copy in each role home.`));\n\n const shared = await existingPaths(home, SHARED);\n for (const role of roles) {\n const target = roleHome(layout, 'codex', role);\n const catalogPath = join(target, CATALOG);\n const roleDocument = renderInstructions(role);\n entries.push({ kind: 'dir', path: target });\n // Codex reads the brief from developer_instructions; this copy is for the operator.\n entries.push({ kind: 'file', path: join(target, 'role-instructions.md'), content: roleDocument });\n entries.push({\n kind: 'file',\n path: join(target, 'config.toml'),\n content: renderRoleConfig(source, { roleDocument, catalogPath }),\n });\n entries.push({ kind: 'file', path: catalogPath, content: catalogSource });\n entries.push(...await roleResourceEntries({ role, target, home, names: SHARED, shared, executable: EXECUTABLE }));\n credentials.push(await credentialDiagnostic(layout, role, store, binary));\n }\n return { entries, credentials, checks, binary };\n },\n};\n","import { spawn } from 'node:child_process';\nimport { mkdtemp, readFile, realpath, rm, stat } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { isAbsolute, join, resolve } from 'node:path';\nimport {\n ambientNamesCheck, inspectCredentialPath, presentNames, preservedCredentialCheck,\n type CredentialDiagnostic,\n} from '../credentials.js';\nimport { piLoginCommand } from '../auth.js';\nimport type { Entry } from '../fsops.js';\nimport { existingPaths } from '../fsops.js';\nimport type { Layout } from '../layout.js';\nimport { contains, roleHome } from '../layout.js';\nimport { fail, pass, type Check } from '../result.js';\nimport type { Role } from '../roles.js';\nimport { renderInstructions } from '../room/instructions.js';\nimport { loadPromptAsset } from '../room/prompts.js';\nimport { which } from '../which.js';\nimport { jsonServerTable, paseoMcpCheck } from './mcp.js';\nimport { roleResourceEntries } from './resources.js';\nimport type { Agent, AgentPlan } from './types.js';\n\nconst PACKAGE_NAME = 'pi-mcp-adapter';\nconst PROBE_ID = 'paseo-room-pi-mcp-probe';\nconst PROBE_TIMEOUT_MS = 10_000;\nconst PROBE_OUTPUT_LIMIT = 1024 * 1024;\nconst SHARED = ['models.json', 'AGENTS.md', 'skills', 'prompts', 'themes', 'keybindings.json', 'mcp.json'] as const;\n/** Pi prompts are its slash commands, so they execute; Peer receives no such resource. */\nconst EXECUTABLE = ['prompts'] as const;\nconst MCP_FILE = 'mcp.json';\n/** Pi accepts either key for its declaration map, so both are read and neither is rewritten. */\nconst MCP_KEYS = ['mcpServers', 'servers'] as const;\n/** Built-in provider key names only; ambient cloud credential files are deliberately not probed. */\nconst AUTH_ENV = [\n 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_OAUTH_TOKEN', 'ANTHROPIC_API_KEY',\n 'OPENAI_API_KEY', 'AZURE_OPENAI_API_KEY', 'GEMINI_API_KEY', 'GOOGLE_CLOUD_API_KEY',\n 'MISTRAL_API_KEY', 'GROQ_API_KEY', 'CEREBRAS_API_KEY', 'XAI_API_KEY',\n 'DEEPSEEK_API_KEY', 'OPENROUTER_API_KEY', 'AI_GATEWAY_API_KEY', 'FIREWORKS_API_KEY',\n 'ZAI_API_KEY', 'MINIMAX_API_KEY', 'OPENCODE_API_KEY', 'KIMI_API_KEY',\n 'COPILOT_GITHUB_TOKEN',\n] as const;\n\nfunction asObject(value: unknown): Record<string, unknown> | undefined {\n return value !== null && typeof value === 'object' && !Array.isArray(value) ? { ...value } : undefined;\n}\n\n/** Copy operator preferences but remove every declaration that can install or load packages. */\nexport function renderPiSettings(source: string | undefined): string {\n const parsed: unknown = source === undefined ? {} : JSON.parse(source);\n const settings = asObject(parsed);\n if (!settings) throw new Error('Pi settings must be a JSON object.');\n delete settings.packages;\n delete settings.extensions;\n return JSON.stringify(settings, null, 2) + '\\n';\n}\n\n/** Preserve the operator append first; room-specific guidance is additive and stronger. */\nexport function renderPiAppend(source: string | undefined, role: Role): string {\n return [\n source?.trim(),\n loadPromptAsset('pi', 'communicationStyle'),\n loadPromptAsset('pi', 'runtime'),\n renderInstructions(role),\n ].filter((part): part is string => Boolean(part)).join('\\n\\n');\n}\n\ninterface ResolvedAdapter {\n readonly entry: string;\n readonly version: string;\n}\n\nfunction adapterFailure(home: string, detail: string): Check {\n return fail('pi.adapter', detail,\n `Install ${PACKAGE_NAME} in ${join(home, 'npm')} with Pi yourself, then run setup again.`);\n}\n\n/** Resolve only Pi's intended global package and its single declared extension entry. */\nexport async function resolvePiAdapter(home: string): Promise<{ readonly adapter?: ResolvedAdapter; readonly check: Check }> {\n const packageRoot = join(home, 'npm', 'node_modules', PACKAGE_NAME);\n const manifestPath = join(packageRoot, 'package.json');\n try {\n const [canonicalRoot, manifestStat, raw] = await Promise.all([\n realpath(packageRoot), stat(manifestPath), readFile(manifestPath, 'utf8'),\n ]);\n if (!manifestStat.isFile()) return { check: adapterFailure(home, `${manifestPath} is not a regular file.`) };\n const manifest = asObject(JSON.parse(raw));\n if (!manifest || manifest.name !== PACKAGE_NAME) {\n return { check: adapterFailure(home, `${manifestPath} does not identify ${PACKAGE_NAME}.`) };\n }\n const pi = asObject(manifest.pi);\n const declared = pi?.extensions;\n if (!Array.isArray(declared) || declared.length !== 1 || typeof declared[0] !== 'string' || !declared[0].trim()) {\n return { check: adapterFailure(home, `${manifestPath} must declare one Pi extension entry.`) };\n }\n const declaration = declared[0];\n if (isAbsolute(declaration)) {\n return { check: adapterFailure(home, `${manifestPath} declares an unsafe absolute extension path.`) };\n }\n const candidate = resolve(packageRoot, declaration);\n const [canonicalEntry, entryStat] = await Promise.all([realpath(candidate), stat(candidate)]);\n if (!contains(canonicalRoot, canonicalEntry) || canonicalEntry === canonicalRoot || !entryStat.isFile()) {\n return { check: adapterFailure(home, `The declared ${PACKAGE_NAME} extension escapes its package or is not a regular file.`) };\n }\n const version = typeof manifest.version === 'string' && manifest.version.trim() ? manifest.version.trim() : 'unknown';\n return {\n adapter: { entry: canonicalEntry, version },\n check: pass('pi.adapter', `${PACKAGE_NAME} ${version} resolved to ${canonicalEntry}.`),\n };\n } catch {\n return { check: adapterFailure(home, `Could not safely resolve ${PACKAGE_NAME} from ${manifestPath}.`) };\n }\n}\n\nexport interface PiProbeOptions {\n readonly timeoutMs?: number;\n readonly outputLimit?: number;\n}\ninterface ProcessResult {\n readonly ok: boolean;\n readonly stdout: string;\n readonly reason?: 'failure' | 'timeout' | 'overflow';\n}\n\nfunction terminateProbe(child: ReturnType<typeof spawn>): void {\n if (child.pid !== undefined) {\n try { process.kill(-child.pid, 'SIGKILL'); } catch { /* the process group may already be gone */ }\n }\n try { child.kill('SIGKILL'); } catch { /* the direct child may already be gone */ }\n child.stdin?.destroy();\n child.stdout?.destroy();\n child.stderr?.destroy();\n}\n\n/** One bounded JSONL request in its own process group and isolated working directory. */\nfunction runProbeProcess(\n executable: string,\n adapterEntry: string,\n env: NodeJS.ProcessEnv,\n options: PiProbeOptions,\n cwd: string,\n): Promise<ProcessResult> {\n const timeoutMs = options.timeoutMs ?? PROBE_TIMEOUT_MS;\n const outputLimit = options.outputLimit ?? PROBE_OUTPUT_LIMIT;\n const args = ['--mode', 'rpc', '--no-session', '--no-extensions', '--extension', adapterEntry, '--no-approve'];\n return new Promise(resolveResult => {\n const child = spawn(executable, args, { cwd, detached: true, env, stdio: ['pipe', 'pipe', 'pipe'] });\n const stdout: Buffer[] = [];\n let bytes = 0;\n let settled = false;\n const finish = (result: ProcessResult): void => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n resolveResult(result);\n };\n const abort = (reason: NonNullable<ProcessResult['reason']>): void => {\n if (settled) return;\n terminateProbe(child);\n finish({ ok: false, stdout: Buffer.concat(stdout).toString('utf8'), reason });\n };\n const capture = (chunk: Buffer, keep: boolean): void => {\n if (settled) return;\n bytes += chunk.length;\n if (bytes > outputLimit) {\n abort('overflow');\n return;\n }\n if (keep) stdout.push(chunk);\n };\n const timer = setTimeout(() => { abort('timeout'); }, timeoutMs);\n child.stdout.on('data', (chunk: Buffer) => { capture(chunk, true); });\n child.stderr.on('data', (chunk: Buffer) => { capture(chunk, false); });\n child.stdout.on('error', () => { abort('failure'); });\n child.stderr.on('error', () => { abort('failure'); });\n child.on('error', () => { abort('failure'); });\n child.on('close', code => {\n const output = Buffer.concat(stdout).toString('utf8');\n finish(code === 0 ? { ok: true, stdout: output } : { ok: false, stdout: output, reason: 'failure' });\n });\n child.stdin.on('error', () => { /* a failed child is reported by close/error */ });\n child.stdin.end(`${JSON.stringify({ id: PROBE_ID, type: 'get_commands' })}\\n`);\n });\n}\n\n/** Pi runs migrations against cwd before RPC, so never probe in the caller's project. */\nasync function runProbe(\n executable: string,\n adapterEntry: string,\n env: NodeJS.ProcessEnv,\n options: PiProbeOptions,\n): Promise<ProcessResult> {\n const createdCwd = await mkdtemp(join(tmpdir(), 'paseo-room-pi-probe-'));\n const cwd = await realpath(createdCwd);\n try {\n return await runProbeProcess(executable, adapterEntry, {\n ...env,\n HOME: cwd,\n PI_CODING_AGENT_DIR: '/dev/null',\n PI_MCP_CONFIG_MODE: 'exclusive',\n PI_OFFLINE: '1',\n }, options, cwd);\n } finally {\n await rm(createdCwd, { force: true, recursive: true });\n }\n}\n\nfunction probeFailure(message: string): Check {\n return fail('pi.capability', message,\n 'Use a Pi and pi-mcp-adapter installation that exposes /mcp through the declared adapter entry.');\n}\n\n/** Authenticate the exact adapter path through Pi's correlated get_commands response. */\nexport async function probePiMcp(\n executable: string,\n adapterEntry: string,\n env: NodeJS.ProcessEnv,\n options: PiProbeOptions = {},\n): Promise<Check> {\n let result: ProcessResult;\n try {\n result = await runProbe(executable, adapterEntry, env, options);\n } catch {\n return probeFailure('Pi capability probe could not create or clean its isolated working directory.');\n }\n if (!result.ok) {\n if (result.reason === 'timeout') return probeFailure('Pi capability probe timed out.');\n if (result.reason === 'overflow') return probeFailure('Pi capability probe exceeded its output limit.');\n return probeFailure('Pi capability probe failed.');\n }\n const correlated: Record<string, unknown>[] = [];\n for (const line of result.stdout.split(/\\r?\\n/).filter(Boolean)) {\n let parsed: unknown;\n try { parsed = JSON.parse(line); } catch { return probeFailure('Pi capability probe returned malformed JSONL.'); }\n const event = asObject(parsed);\n if (!event) return probeFailure('Pi capability probe returned malformed JSONL.');\n if (event.type === 'response' && event.id === PROBE_ID) correlated.push(event);\n }\n if (correlated.length !== 1) return probeFailure('Pi capability probe did not return one correlated get_commands response.');\n const response = correlated[0];\n if (response?.command !== 'get_commands' || response.success !== true) {\n return probeFailure('Pi rejected the get_commands capability probe.');\n }\n const data = asObject(response.data);\n const commands = data?.commands;\n if (!Array.isArray(commands)) return probeFailure('Pi get_commands response was malformed.');\n const matches = commands.map(asObject).filter((command): command is Record<string, unknown> => command?.name === 'mcp');\n if (matches.length !== 1) return probeFailure('Pi did not expose exactly one /mcp command.');\n const command = matches[0];\n if (command?.source !== 'extension') return probeFailure('Pi exposed /mcp from the wrong source.');\n const sourceInfo = asObject(command.sourceInfo);\n if (typeof sourceInfo?.path !== 'string') return probeFailure('Pi did not report the /mcp extension path.');\n try {\n const sourcePath = await realpath(sourceInfo.path);\n if (sourcePath !== adapterEntry) return probeFailure('Pi loaded /mcp from a different extension path.');\n } catch {\n return probeFailure('Pi reported an unresolvable /mcp extension path.');\n }\n return pass('pi.capability', `Pi exposed /mcp from ${adapterEntry}.`);\n}\n\nasync function readPiOptional(path: string): Promise<string | undefined> {\n try {\n return await readFile(path, 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined;\n throw error;\n }\n}\n\nexport async function piCredentialDiagnostic(layout: Layout, role: Role, binary = 'pi'): Promise<CredentialDiagnostic> {\n const home = roleHome(layout, 'pi', role);\n const path = join(home, 'auth.json');\n const launch = piLoginCommand(home, binary);\n const state = await inspectCredentialPath(path);\n const id = `pi.auth.${role}`;\n if (state.kind !== 'missing') {\n return {\n path,\n checks: [preservedCredentialCheck({\n id, agent: 'Pi', role, path, state,\n login: `${launch}; this starts a minimal, non-room-equivalent interactive login session. Run /login, then exit Pi`,\n })],\n };\n }\n const configured = presentNames(layout.envNames, AUTH_ENV);\n if (configured.length > 0) return { path, checks: [ambientNamesCheck(id, 'Pi', role, configured)] };\n return { path, checks: [{\n id: `${id}.login-required`, status: 'warn',\n message: `Pi ${role} auth: login-required; no role-owned auth.json or known provider environment name was detected. Ambient provider auth may exist, but it was not inspected or validated.`,\n fix: `Start a minimal, non-room-equivalent interactive login session with: ${launch}. Run /login, then exit Pi.`,\n }] };\n}\n\nexport const piAgent: Agent = {\n id: 'pi',\n label: 'Pi',\n homeEnv: 'PI_CODING_AGENT_DIR',\n providerEnv: { PI_MCP_CONFIG_MODE: 'exclusive' },\n pins: {},\n async build(layout: Layout, roles: readonly Role[]): Promise<AgentPlan> {\n const home = layout.agentHome.pi;\n const binary = await which(layout.bin.pi, layout.searchPath);\n if (!binary) {\n return { entries: [], checks: [fail('pi.bin', 'Pi executable not found.', 'Install Pi yourself, or pass --pi-bin /path/to/pi.')] };\n }\n try {\n if (!(await stat(home)).isDirectory()) throw new Error('not a directory');\n } catch {\n return { entries: [], checks: [fail('pi.home', `No Pi config directory at ${home}.`, 'Run Pi once to initialise it, or pass --pi-home.')] };\n }\n const resolved = await resolvePiAdapter(home);\n if (!resolved.adapter) return { entries: [], checks: [resolved.check] };\n const capability = await probePiMcp(binary, resolved.adapter.entry, {\n HOME: layout.home,\n PATH: layout.searchPath,\n PI_CODING_AGENT_DIR: '/dev/null',\n PI_OFFLINE: '1',\n });\n if (capability.status === 'fail') return { entries: [], checks: [resolved.check, capability] };\n\n const settingsPath = join(home, 'settings.json');\n let settings: string;\n try { settings = renderPiSettings(await readPiOptional(settingsPath)); } catch {\n return {\n entries: [], checks: [resolved.check, capability,\n fail('pi.settings', `Could not read ${settingsPath} as a JSON object.`,\n 'Make your Pi settings readable and fix any JSON syntax, then run setup again.')],\n };\n }\n const operatorAppendPath = join(home, 'APPEND_SYSTEM.md');\n let operatorAppend: string | undefined;\n try {\n operatorAppend = await readPiOptional(operatorAppendPath);\n } catch {\n return {\n entries: [], checks: [resolved.check, capability,\n fail('pi.append', `Could not read ${operatorAppendPath}.`,\n 'Make your Pi APPEND_SYSTEM.md readable, then run setup again.')],\n };\n }\n const shared = await existingPaths(home, SHARED);\n // The adapter reads this file as its only config source, so a Paseo-looking server here\n // would be a second control plane. Fail before apply; never edit the operator's file.\n const mcpPath = join(home, MCP_FILE);\n let servers: Record<string, unknown>;\n try {\n servers = jsonServerTable(await readPiOptional(mcpPath), MCP_KEYS);\n } catch {\n return {\n entries: [], checks: [resolved.check, capability,\n fail('pi.mcp', `Could not read ${mcpPath} as a JSON object, so its MCP declarations could not be inspected.`,\n 'Make your Pi mcp.json readable and fix its JSON structure, then run setup again.')],\n };\n }\n const conflict = paseoMcpCheck('pi.mcp', mcpPath, servers);\n if (conflict) return { entries: [], checks: [resolved.check, capability, conflict] };\n const entries: Entry[] = [];\n const credentials: CredentialDiagnostic[] = [];\n const argv: Partial<Record<Role, readonly string[]>> = {};\n for (const role of roles) {\n const target = roleHome(layout, 'pi', role);\n const appendPath = join(target, 'APPEND_SYSTEM.md');\n entries.push({ kind: 'dir', path: target });\n entries.push({ kind: 'file', path: join(target, 'settings.json'), content: settings });\n entries.push({ kind: 'file', path: appendPath, content: renderPiAppend(operatorAppend, role) });\n entries.push(...await roleResourceEntries({ role, target, home, names: SHARED, shared, executable: EXECUTABLE }));\n credentials.push(await piCredentialDiagnostic(layout, role, binary));\n argv[role] = ['--no-extensions', '--extension', resolved.adapter.entry, '--no-approve', '--append-system-prompt', appendPath];\n }\n return {\n entries,\n credentials,\n checks: [pass('pi.home', `Pi found at ${binary} using ${home}.`), resolved.check, capability],\n binary,\n argv,\n };\n },\n};\n","import type { PaseoClient, PaseoClientConfig } from '@getpaseo/client';\nimport { gte, valid } from 'semver';\nimport { z } from 'zod';\nimport type { Layout } from './layout.js';\nimport { fail, pass, type Check } from './result.js';\nimport type { Profile, Provider } from './agents/types.js';\nimport type { AgentId } from './roles.js';\nimport { probe, which } from './which.js';\n\nexport const MINIMUM_VERSION = '0.8.0-beta.1';\nexport const PI_MINIMUM_VERSION = '0.8.0';\n\nexport function minimumPaseoVersion(agents: readonly AgentId[]): string {\n return agents.includes('pi') || agents.includes('claude') ? PI_MINIMUM_VERSION : MINIMUM_VERSION;\n}\n\nconst statusSchema = z.object({\n listen: z.string().min(1),\n localDaemon: z.enum(['running', 'stopped', 'stale_pid', 'unresponsive']),\n cliVersion: z.string(),\n daemonVersion: z.string().nullable(),\n});\n\nexport interface Daemon {\n readonly url: string;\n readonly version: string;\n}\nexport interface DaemonResult {\n readonly checks: readonly Check[];\n readonly daemon?: Daemon;\n}\n\nexport function normalizeUrl(listen: string): string | undefined {\n const match = /^(?:ws:\\/\\/)?([^:/]+|\\[[^\\]]+\\]):(\\d+)$/.exec(listen.trim());\n if (!match) return undefined;\n const [, host = '', port = ''] = match;\n const local = ['localhost', '127.0.0.1', '0.0.0.0', '[::1]', '[::]'].includes(host) ? '127.0.0.1' : host;\n return `ws://${local}:${port}`;\n}\n\n/** The whole compatibility story: is Paseo running, and is it new enough? */\nexport function assessStatus(raw: unknown, minimumVersion = MINIMUM_VERSION): DaemonResult {\n const parsed = statusSchema.safeParse(raw);\n if (!parsed.success) {\n return { checks: [fail('paseo.status', 'Paseo status output was not understood.', 'Upgrade Paseo, then run: paseo daemon status --json')] };\n }\n const status = parsed.data;\n if (status.localDaemon !== 'running') {\n return { checks: [fail('paseo.daemon', `Paseo daemon is ${status.localDaemon}.`, 'Start it with: paseo daemon start')] };\n }\n const cli = valid(status.cliVersion);\n const daemon = status.daemonVersion === null ? null : valid(status.daemonVersion);\n if (!cli || !daemon) {\n return { checks: [fail('paseo.version', 'Paseo did not report a usable version.', 'Upgrade Paseo to a release that reports semver versions.')] };\n }\n if (cli !== daemon) {\n return { checks: [fail('paseo.version', `Paseo CLI is ${cli} but the running daemon is ${daemon}.`, 'Restart the daemon with: paseo daemon restart')] };\n }\n if (!gte(daemon, minimumVersion)) {\n return { checks: [fail('paseo.version', `Paseo ${daemon} is older than the required ${minimumVersion}.`, 'Upgrade Paseo, then run setup again.')] };\n }\n const url = normalizeUrl(status.listen);\n if (!url) {\n return { checks: [fail('paseo.listen', `Paseo listen address ${status.listen} was not understood.`, 'Use a host:port listen address in the Paseo config.')] };\n }\n return { checks: [pass('paseo.version', `Paseo ${daemon} is running on ${url} (compatible, needs >= ${minimumVersion}).`)], daemon: { url, version: daemon } };\n}\n\nexport async function checkDaemon(layout: Layout, env: NodeJS.ProcessEnv = process.env, minimumVersion = MINIMUM_VERSION): Promise<DaemonResult> {\n const binary = await which(layout.bin.paseo, layout.searchPath);\n if (!binary) {\n return { checks: [fail('paseo.bin', 'Paseo executable not found.', 'Install Paseo, or pass --paseo-bin /path/to/paseo.')] };\n }\n const output = await probe(binary, ['daemon', 'status', '--json'], {\n HOME: layout.home, PASEO_HOME: layout.paseoHome, PATH: layout.searchPath,\n ...(env.PASEO_PASSWORD === undefined ? {} : { PASEO_PASSWORD: env.PASEO_PASSWORD }),\n });\n if (!output.ok) {\n return { checks: [fail('paseo.status', 'Could not read Paseo daemon status.', 'Run: paseo daemon status --json')] };\n }\n try { return assessStatus(JSON.parse(output.stdout), minimumVersion); }\n catch { return assessStatus(undefined, minimumVersion); }\n}\n\nconst configSchema = z.object({\n config: z.object({\n providers: z.record(z.string(), z.unknown()).optional(),\n // Read loosely: entries carry operator fields the room neither knows nor touches.\n agentProfiles: z.array(z.record(z.string(), z.unknown())).optional(),\n pluginsEnabled: z.boolean().optional(),\n }),\n});\nexport type LiveProfile = Record<string, unknown>;\nexport interface LivePlugin {\n readonly id: string;\n readonly path: string;\n readonly enabled: boolean;\n readonly status: string;\n readonly error?: string | undefined;\n}\n\nexport interface Session {\n readProviders(): Promise<Record<string, unknown>>;\n writeProviders(providers: Readonly<Record<string, Provider>>): Promise<void>;\n removeProviders(ids: readonly string[]): Promise<void>;\n readProfiles(): Promise<readonly LiveProfile[]>;\n /** Paseo has no remove-one call for profiles, so this replaces the whole array. */\n writeProfiles(profiles: readonly LiveProfile[]): Promise<void>;\n pluginsEnabled(): Promise<boolean>;\n listPlugins(): Promise<readonly LivePlugin[]>;\n installPlugin(path: string, id: string): Promise<LivePlugin>;\n reloadPlugin(id: string): Promise<LivePlugin>;\n enablePlugin(id: string): Promise<LivePlugin>;\n removePlugin(id: string): Promise<void>;\n refresh(ids: readonly string[]): Promise<void>;\n}\nexport interface RoomClient extends PaseoClient {\n listPlugins(): Promise<LivePlugin[]>;\n installDirectoryPlugin(path: string, id?: string): Promise<LivePlugin>;\n reloadPlugin(id: string): Promise<LivePlugin>;\n enablePlugin(id: string): Promise<LivePlugin>;\n removePlugin(id: string): Promise<void>;\n}\nexport type ClientFactory = (config: PaseoClientConfig) => RoomClient;\n\n/** One connection per command. No retries, no reconnects, no background state. */\nexport async function withSession<T>(\n daemon: Daemon,\n run: (session: Session) => Promise<T>,\n options: { readonly password?: string; readonly factory?: ClientFactory } = {},\n): Promise<T> {\n const quiet = { debug() { /* silent */ }, info() { /* silent */ }, warn() { /* silent */ }, error() { /* silent */ } };\n // Loaded here so the \"Paseo is not running\" path never pays for the SDK.\n const clientConfig: PaseoClientConfig = {\n url: `${daemon.url}/ws`,\n ...(options.password === undefined ? {} : { password: options.password }),\n appVersion: MINIMUM_VERSION,\n connectTimeoutMs: 10_000,\n reconnect: { enabled: false },\n logger: quiet,\n };\n let client: RoomClient;\n if (options.factory !== undefined) {\n client = options.factory(clientConfig);\n } else {\n const [{ createPaseoApi }, { DaemonClient }] = await Promise.all([\n import('@getpaseo/client'), import('@getpaseo/client/internal/daemon-client'),\n ]);\n const raw = new DaemonClient({ ...clientConfig, clientId: `paseo-room-${String(process.pid)}`, clientType: 'cli' });\n client = {\n ...createPaseoApi(raw),\n connect: () => raw.connect(), close: () => raw.close(),\n ensureConnected: () => { raw.ensureConnected(); }, getConnectionState: () => raw.getConnectionState(),\n listPlugins: () => raw.listPlugins(),\n installDirectoryPlugin: (path, id) => raw.installDirectoryPlugin(path, id),\n reloadPlugin: id => raw.reloadPlugin(id), enablePlugin: id => raw.enablePlugin(id),\n removePlugin: id => raw.removePlugin(id),\n };\n }\n try {\n await client.connect();\n return await run({\n async readProviders() {\n const response = configSchema.parse(await client.config.get());\n return response.config.providers ?? {};\n },\n async writeProviders(providers) {\n await client.config.patch({ providers } as unknown as Parameters<PaseoClient['config']['patch']>[0]);\n },\n async removeProviders(ids) {\n await client.config.patch({ removeProviders: [...ids] });\n },\n async readProfiles() {\n const response = configSchema.parse(await client.config.get());\n return response.config.agentProfiles ?? [];\n },\n async writeProfiles(profiles) {\n await client.config.patch({ agentProfiles: [...profiles] } as unknown as Parameters<PaseoClient['config']['patch']>[0]);\n },\n async pluginsEnabled() {\n const response = configSchema.parse(await client.config.get());\n return response.config.pluginsEnabled === true;\n },\n async listPlugins() {\n return await client.listPlugins();\n },\n async installPlugin(path, id) {\n return await client.installDirectoryPlugin(path, id);\n },\n async reloadPlugin(id) {\n return await client.reloadPlugin(id);\n },\n async enablePlugin(id) {\n return await client.enablePlugin(id);\n },\n async removePlugin(id) {\n await client.removePlugin(id);\n },\n async refresh(ids) {\n await client.providers.refresh({ providers: [...ids] });\n },\n });\n } finally {\n await client.close();\n }\n}\n\n/**\n * The provider environment is written whole by the room, so it is compared whole: an\n * added key can enable exactly what the pins close, and a subset test would call that a\n * match. Unrelated *top-level* provider fields remain the operator's.\n */\nfunction envMatches(live: unknown, desired: Readonly<Record<string, string>>): boolean {\n if (live === null || typeof live !== 'object' || Array.isArray(live)) return false;\n const entries = Object.entries(live as Record<string, unknown>);\n return entries.length === Object.keys(desired).length &&\n entries.every(([key, value]) => Object.hasOwn(desired, key) && value === desired[key]);\n}\n\n/** Compare only the keys the room owns; unrelated fields stay the operator's. */\nexport function providerMatches(desired: Provider, live: unknown): boolean {\n if (live === null || typeof live !== 'object') return false;\n const entry = live as Record<string, unknown>;\n const tools = entry.paseoTools;\n const same = (left: unknown, right: unknown): boolean => JSON.stringify(left ?? null) === JSON.stringify(right ?? null);\n return entry.extends === desired.extends &&\n same(entry.command, desired.command) &&\n envMatches(entry.env, desired.env) &&\n tools !== null && typeof tools === 'object' &&\n (tools as { enabled?: unknown }).enabled === desired.paseoTools.enabled &&\n // Pins are the room's guarantee: drifting them silently re-enables what they block.\n same(entry.params, desired.params) &&\n same(entry.disallowedTools, desired.disallowedTools);\n}\n\n/** Compare only the fields the room writes on an update; the rest are the operator's. */\nexport function profileMatches(desired: Profile, live: unknown): boolean {\n if (live === null || typeof live !== 'object') return false;\n const entry = live as Record<string, unknown>;\n return entry.name === desired.name && entry.icon === desired.icon && entry.color === desired.color &&\n entry.provider === desired.provider && entry.modeId === desired.modeId && entry.notes === desired.notes;\n}\n\n/**\n * Paseo stores every profile in one host-wide array, so the room rewrites that array\n * rather than patching an entry. Operator profiles pass through untouched, and so does\n * every field of a room profile that the room does not own.\n */\nexport function mergeProfiles(\n live: readonly LiveProfile[],\n desired: readonly Profile[],\n drop: readonly string[],\n): LiveProfile[] {\n const dropped = new Set(drop);\n const wanted = new Map(desired.map(profile => [profile.id, profile]));\n const seen = new Set<string>();\n const kept = live\n .filter(entry => !dropped.has(String(entry.id)))\n .map(entry => {\n const profile = wanted.get(String(entry.id));\n if (!profile) return entry;\n seen.add(profile.id);\n // Model and thinkingOptionId remain operator choices; the room owns the\n // role's visual identity and its no-prompt launch mode.\n const updated: LiveProfile = {\n ...entry, name: profile.name, icon: profile.icon, color: profile.color,\n provider: profile.provider, notes: profile.notes,\n };\n if (profile.modeId === undefined) delete updated.modeId;\n else updated.modeId = profile.modeId;\n return updated;\n });\n return [...kept, ...desired.filter(profile => !seen.has(profile.id)).map(profile => ({ ...profile }))];\n}\n","import { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { Entry } from './fsops.js';\nimport type { Layout } from './layout.js';\nimport { providerId, type Role } from './roles.js';\nimport { contractDigest, renderInstructions } from './room/instructions.js';\n\nexport const CLAUDE_CARRIER_PLUGIN_ID = 'paseo-room-claude-carrier';\nexport const CLAUDE_CARRIER_PASEO_RANGE = '>=0.8.0 <0.9.0';\n\nconst STATIC_ASSETS = [\n 'paseo-plugin.json',\n 'package.json',\n 'tsconfig.json',\n 'index.server.ts',\n 'server/carrier.ts',\n] as const;\n\nfunction loadAsset(path: string): string {\n return readFileSync(new URL(`./plugin-assets/${path}`, import.meta.url), 'utf8');\n}\n\nexport function claudeCarrierPluginDir(layout: Layout): string {\n return join(layout.roomHome, 'plugin');\n}\n\nexport function renderClaudeCarrierContract(roles: readonly Role[]): string {\n const contracts = Object.fromEntries(roles.map(role => [providerId('claude', role), renderInstructions(role)]));\n return [\n '/** Generated by paseo-room. The Markdown prompt assets remain authoritative. */',\n `export const GENERATION = ${JSON.stringify(contractDigest())};`,\n `export const CONTRACT: Readonly<Record<string, string>> = ${JSON.stringify(contracts, null, 2)};`,\n '',\n ].join('\\n');\n}\n\nexport function claudeCarrierEntries(layout: Layout, roles: readonly Role[]): Entry[] {\n const root = claudeCarrierPluginDir(layout);\n return [\n { kind: 'dir', path: root },\n { kind: 'dir', path: join(root, 'server') },\n ...STATIC_ASSETS.map(path => ({ kind: 'file' as const, path: join(root, path), content: loadAsset(path) })),\n { kind: 'file', path: join(root, 'server', 'contract.ts'), content: renderClaudeCarrierContract(roles) },\n ];\n}\n","import { join, sep } from 'node:path';\nimport { lstat, rm } from 'node:fs/promises';\nimport metadata from '../package.json' with { type: 'json' };\nimport { claudeAgent } from './agents/claude.js';\nimport { codexAgent } from './agents/codex.js';\nimport { piAgent } from './agents/pi.js';\nimport type { Agent, AgentPlan, BuildOptions, Profile, Provider } from './agents/types.js';\nimport { AUTHENTICATION_GUIDE, renderAuthenticationGuide } from './auth.js';\nimport { applyEntries, exists, planEntries, type Entry } from './fsops.js';\nimport { layoutChecks, resolveLayout, roleHome, sharedRoom, type Layout, type Options } from './layout.js';\nimport { checkDaemon, mergeProfiles, minimumPaseoVersion, profileMatches, providerMatches, withSession, type ClientFactory, type LivePlugin, type LiveProfile, type Session } from './paseo.js';\nimport { CLAUDE_CARRIER_PLUGIN_ID, claudeCarrierEntries, claudeCarrierPluginDir } from './plugin.js';\nimport { fail, failed, hasFailure, pass, warn, type Check, type Operation, type Result } from './result.js';\nimport { contractDigest, renderInstructions } from './room/instructions.js';\nimport { MARKER, readMarker, renderMarker, type Marker } from './room.js';\nimport { DELEGATING_THINKING, profileId, providerId, providerLabel, ROLES, ROLE_COLOR, ROLE_ICON, ROLE_NOTES, ROLE_PASEO_TOOLS, ROLE_THINKING, type AgentId, type Role } from './roles.js';\n\nexport const AGENTS: Record<AgentId, Agent> = { codex: codexAgent, claude: claudeAgent, pi: piAgent };\n\nexport interface RunOptions extends Options {\n readonly agents?: readonly AgentId[];\n readonly apply?: boolean;\n /**\n * Write the role contract into Claude's `CLAUDE.md` as well as the plugin. Defaults to true:\n * the plugin is the strong carrier, but whether a resumed session re-enters its creation hook\n * is unproven, so the file fallback is only dropped when asked for.\n */\n readonly claudeMemoryContract?: boolean;\n readonly env?: NodeJS.ProcessEnv;\n readonly factory?: ClientFactory;\n}\n\nfunction sessionOptions(options: RunOptions): { password?: string; factory?: ClientFactory } {\n const password = (options.env ?? process.env).PASEO_PASSWORD;\n return { ...(password === undefined ? {} : { password }), ...(options.factory ? { factory: options.factory } : {}) };\n}\n\n/** The only per-agent differences are the home variable and the provider pins. */\nfunction roleProviders(\n layout: Layout,\n agent: Agent,\n plan: { readonly binary: string; readonly argv?: AgentPlan['argv']; readonly providerEnv?: AgentPlan['providerEnv'] },\n roles: readonly Role[],\n): Record<string, Provider> {\n return Object.fromEntries(roles.map(role => [providerId(agent.id, role), {\n extends: agent.id,\n label: providerLabel(agent.id, role),\n command: [plan.binary, ...(plan.argv?.[role] ?? [])],\n env: { ...agent.providerEnv, ...plan.providerEnv?.[role], [agent.homeEnv]: roleHome(layout, agent.id, role) },\n paseoTools: { enabled: ROLE_PASEO_TOOLS[role] },\n ...agent.pins,\n }]));\n}\n\n/** The picker preset that points at a provider, so a seat is one click rather than four. */\nfunction roleProfiles(agent: Agent, roles: readonly Role[]): Profile[] {\n return roles.map(role => ({\n id: profileId(agent.id, role),\n name: providerLabel(agent.id, role),\n icon: ROLE_ICON[role],\n color: ROLE_COLOR[role],\n provider: providerId(agent.id, role),\n ...(agent.defaultModeId === undefined ? {} : { modeId: agent.defaultModeId }),\n thinkingOptionId: ROLE_THINKING[role],\n notes: ROLE_NOTES[role],\n }));\n}\n\ninterface Desired {\n readonly entries: readonly Entry[];\n readonly providers: Readonly<Record<string, Provider>>;\n readonly profiles: readonly Profile[];\n readonly checks: readonly Check[];\n readonly pluginPath?: string;\n}\nasync function buildDesired(\n layout: Layout,\n agents: readonly AgentId[],\n roles: readonly Role[],\n build: BuildOptions = {},\n): Promise<Desired> {\n // Template, not linked into any seat: each repo owns its own root WORKSPACE_PROTOCOL.md.\n // Named exactly as Workspace Protocol Precedence names it, so a copy needs no rename.\n const entries: Entry[] = [\n { kind: 'dir', path: layout.roomHome },\n { kind: 'dir', path: sharedRoom(layout) },\n { kind: 'file', path: join(sharedRoom(layout), 'WORKSPACE_PROTOCOL.md'), content: renderInstructions('workspace') },\n ];\n const providers: Record<string, Provider> = {};\n const profiles: Profile[] = [];\n const checks: Check[] = [];\n const binaries: Partial<Record<AgentId, string>> = {};\n for (const id of agents) {\n const agent = AGENTS[id];\n const plan = await agent.build(layout, roles, build);\n entries.push(...plan.entries);\n checks.push(...plan.checks);\n const credentials = plan.credentials ?? [];\n checks.push(...credentials.flatMap(credential => credential.checks));\n const credentialPaths = new Set(credentials.map(credential => credential.path));\n const collisions = plan.entries.filter(entry => credentialPaths.has(entry.path));\n if (collisions.length > 0) {\n checks.push(fail(`${id}.credentials`,\n `${agent.label} produced managed entries for preserve-only credential paths: ${collisions.map(entry => entry.path).join(', ')}.`,\n 'This is an adapter defect; do not apply the plan.'));\n }\n if (plan.binary === undefined) continue;\n binaries[id] = plan.binary;\n Object.assign(providers, roleProviders(layout, agent, {\n binary: plan.binary,\n ...(plan.argv ? { argv: plan.argv } : {}),\n ...(plan.providerEnv ? { providerEnv: plan.providerEnv } : {}),\n }, roles));\n profiles.push(...roleProfiles(agent, roles));\n }\n if (agents.every(id => binaries[id] !== undefined)) {\n entries.push({\n kind: 'file',\n path: join(layout.roomHome, AUTHENTICATION_GUIDE),\n content: renderAuthenticationGuide(layout.roomHome, binaries, agents, roles),\n });\n checks.push(warn('room.authentication-not-validated',\n `Role authentication was not validated. Login instructions are managed at ${join(layout.roomHome, AUTHENTICATION_GUIDE)}.`,\n 'After setup --apply, follow that guide or run: paseo-room auth login <agent> <role>'));\n }\n const pluginPath = agents.includes('claude') ? claudeCarrierPluginDir(layout) : undefined;\n if (pluginPath !== undefined) entries.push(...claudeCarrierEntries(layout, roles));\n entries.push({ kind: 'file', path: join(layout.roomHome, MARKER), content: renderMarker(metadata.version, agents, roles, contractDigest(), markerMemoryContract(agents, build.memoryContract ?? true)) });\n return { entries, providers, profiles, checks, ...(pluginPath === undefined ? {} : { pluginPath }) };\n}\n\n/**\n * The marker records which rendered contract generation installed this room, so an operator\n * who upgrades the package can see that the seats now hold older text. A room installed\n * before provenance existed has no digest, which is reported the same way rather than\n * treated as a broken marker.\n */\nfunction contractProvenance(previous: Marker | undefined): Check[] {\n const digest = contractDigest();\n if (!previous) return [];\n if (previous.contract === digest) {\n return [pass('room.contract', `Role contract generation ${digest} matches this package.`)];\n }\n const held = previous.contract === undefined\n ? `was installed before the room recorded its contract generation (package ${previous.version})`\n : `holds contract generation ${previous.contract}`;\n return [warn('room.contract',\n `This room ${held}; this package renders ${digest}. Managed role documents are rewritten by setup, and a running seat keeps the text it started with.`,\n 'Run: paseo-room setup --apply, then restart the affected seats.')];\n}\n\n/**\n * `thinkingOptionId` is seeded once and the operator's afterwards, so a risky selection is\n * reported rather than corrected. Nothing here changes provider selection, profile writes, or\n * exit status.\n */\nfunction thinkingDiagnostics(live: readonly LiveProfile[], desired: readonly Profile[]): Check[] {\n const owned = new Set(desired.map(profile => profile.id));\n const selected = live\n .filter(entry => owned.has(String(entry.id)))\n .filter(entry => DELEGATING_THINKING.some(option => option === entry.thinkingOptionId))\n .map(entry => `${String(entry.id)} (${String(entry.thinkingOptionId)})`)\n .sort();\n if (selected.length === 0) return [];\n return [warn('room.thinking',\n `${String(selected.length)} room seats are set to a top reasoning option that Paseo describes as including automatic task delegation: ${selected.join(', ')}. Whether that option can actually delegate once the room has closed the native multi-agent paths is unverified: paseo-room has not verified whether those closures prevent that option from delegating, and left your selection in place.`,\n `Choose a lower reasoning option for those seats in Paseo if you want the room's own defaults (${ROLE_THINKING.supervisor} for Supervisor, ${ROLE_THINKING.lead} for Lead and Peer).`)];\n}\n\n/**\n * Names what kind of drift was found. A path the room suppressed needs deleting rather than\n * rewriting, so reporting every difference as \"missing or outdated\" would name the wrong fix.\n */\nfunction fileDriftSummary(drifted: readonly Operation[]): string {\n const removals = drifted.filter(operation => operation.action === 'remove').length;\n const count = String(drifted.length);\n const subject = drifted.length === 1 ? 'managed role file is' : 'managed role files are';\n if (removals === 0) return `${count} ${subject} missing or outdated.`;\n if (removals === drifted.length) return `${count} ${subject} present but suppressed by this room.`;\n return `${count} ${subject} missing or outdated, and ${String(removals)} of them are present but suppressed by this room.`;\n}\n\n/** Catalog copies are one of the room's three native multi-agent closures, so their drift is named. */\nfunction fileDriftDetail(targets: readonly string[]): string {\n const catalogs = targets.filter(target => target.endsWith(`${sep}model-catalog.json`));\n if (catalogs.length === 0) return '';\n const count = catalogs.length === 1 ? 'One of them is a generated Codex model catalog' : `${String(catalogs.length)} of them are generated Codex model catalogs`;\n return ` ${count}, so those seats currently lack the scrubbed catalog closure rather than only older contract text.`;\n}\n\ninterface Stale {\n readonly providerIds: readonly string[];\n readonly profileIds: readonly string[];\n readonly removePlugin: boolean;\n /** Role homes are retained during setup because runtime-owned credentials may be inside. */\n readonly retainedDirectories: readonly string[];\n}\nconst NOTHING_STALE: Stale = { providerIds: [], profileIds: [], removePlugin: false, retainedDirectories: [] };\n\nasync function safeDirectory(path: string, checks: Check[]): Promise<boolean> {\n try {\n const stat = await lstat(path);\n if (stat.isDirectory()) return true;\n checks.push(fail('room.path-safety',\n `Refusing to traverse ${path}: every existing room directory ancestor must be a real directory, not a symbolic link or another file type.`,\n 'Move the path aside manually after checking it for role-owned credentials, then run the command again.'));\n return false;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;\n checks.push(fail('room.path-safety', `Could not inspect room directory ${path} without following links.`,\n 'Fix its parent permissions or move the path manually, then run the command again.'));\n return false;\n }\n}\n\n/** Refuse managed writes through any existing room-relative directory alias. */\nasync function roomPathSafety(layout: Layout, agents: readonly AgentId[], roles: readonly Role[]): Promise<Check[]> {\n const checks: Check[] = [];\n if (!await safeDirectory(layout.roomHome, checks)) return checks;\n await safeDirectory(sharedRoom(layout), checks);\n const rolesHome = join(layout.roomHome, 'roles');\n if (!await safeDirectory(rolesHome, checks)) return checks;\n for (const agent of agents) {\n const agentHome = join(rolesHome, agent);\n if (!await safeDirectory(agentHome, checks)) continue;\n for (const role of roles) await safeDirectory(roleHome(layout, agent, role), checks);\n }\n return checks;\n}\n\n/** A previous setup may have seated agents or roles this one does not: drop those. */\nasync function staleFrom(layout: Layout, previous: Marker | undefined, agents: readonly AgentId[], roles: readonly Role[]): Promise<Stale> {\n if (!previous) return NOTHING_STALE;\n const kept = new Set(agents.flatMap(agent => roles.map(role => providerId(agent, role))));\n const providerIds: string[] = [];\n const profileIds: string[] = [];\n const retainedDirectories: string[] = [];\n for (const agent of previous.agents) {\n for (const role of previous.roles) {\n if (kept.has(providerId(agent, role))) continue;\n providerIds.push(providerId(agent, role));\n profileIds.push(profileId(agent, role));\n const path = roleHome(layout, agent, role);\n if (await exists(path)) retainedDirectories.push(path);\n }\n }\n return {\n providerIds,\n profileIds,\n removePlugin: previous.agents.includes('claude') && !agents.includes('claude'),\n retainedDirectories,\n };\n}\n\ninterface Plan {\n readonly operations: readonly Operation[];\n /** Carried out of the plan so apply rewrites the array it actually compared against. */\n readonly liveProfiles: readonly LiveProfile[];\n readonly livePlugin?: LivePlugin;\n readonly pluginChecks: readonly Check[];\n}\n\nfunction pluginPlan(desired: Desired, stale: Stale, plugins: readonly LivePlugin[], expectedPath: string): {\n operation?: Operation; livePlugin?: LivePlugin; checks: Check[];\n} {\n const livePlugin = plugins.find(plugin => plugin.id === CLAUDE_CARRIER_PLUGIN_ID);\n const shouldManage = desired.pluginPath !== undefined || stale.removePlugin;\n if (!shouldManage) return { checks: [] };\n if (livePlugin !== undefined && livePlugin.path !== expectedPath) {\n return {\n livePlugin,\n checks: [fail('claude.plugin.path',\n `Plugin ${CLAUDE_CARRIER_PLUGIN_ID} is registered from ${livePlugin.path}, not the room-owned path ${expectedPath}.`,\n 'Move or remove that conflicting plugin registration manually, then run setup again.')],\n };\n }\n if (desired.pluginPath !== undefined) {\n const healthy = livePlugin?.enabled === true && livePlugin.status === 'running' && livePlugin.error === undefined;\n return {\n ...(livePlugin === undefined ? {} : { livePlugin }),\n operation: { action: livePlugin === undefined ? 'create' : healthy ? 'noop' : 'update', kind: 'plugin', target: CLAUDE_CARRIER_PLUGIN_ID },\n checks: [],\n };\n }\n return {\n ...(livePlugin === undefined ? {} : { livePlugin }),\n operation: { action: livePlugin === undefined ? 'noop' : 'remove', kind: 'plugin', target: CLAUDE_CARRIER_PLUGIN_ID },\n checks: [],\n };\n}\n\n/** One definition of drift, shared by the command that fixes it and the one that reports it. */\nasync function planRoom(session: Session, desired: Desired, stale: Stale, expectedPluginPath: string): Promise<Plan> {\n const inspectPlugins = desired.pluginPath !== undefined || stale.removePlugin;\n const [live, liveProfiles, plugins] = await Promise.all([\n session.readProviders(), session.readProfiles(), inspectPlugins ? session.listPlugins() : Promise.resolve([]),\n ]);\n const byId = new Map(liveProfiles.map(entry => [String(entry.id), entry]));\n const plugin = pluginPlan(desired, stale, plugins, expectedPluginPath);\n return {\n liveProfiles,\n ...(plugin.livePlugin === undefined ? {} : { livePlugin: plugin.livePlugin }),\n pluginChecks: plugin.checks,\n operations: [\n ...await planEntries(desired.entries),\n ...Object.entries(desired.providers).map(([id, provider]) => ({\n action: !(id in live) ? 'create' : providerMatches(provider, live[id]) ? 'noop' : 'update',\n kind: 'provider',\n target: id,\n }) satisfies Operation),\n ...desired.profiles.map(profile => ({\n action: !byId.has(profile.id) ? 'create' : profileMatches(profile, byId.get(profile.id)) ? 'noop' : 'update',\n kind: 'profile',\n target: profile.id,\n }) satisfies Operation),\n ...stale.providerIds.filter(id => id in live).map(id => ({ action: 'remove', kind: 'provider', target: id }) satisfies Operation),\n ...stale.profileIds.filter(id => byId.has(id)).map(id => ({ action: 'remove', kind: 'profile', target: id }) satisfies Operation),\n ...(plugin.operation === undefined ? [] : [plugin.operation]),\n ],\n };\n}\n\nfunction pluginsEnabledCheck(enabled: boolean): Check {\n return enabled\n ? pass('claude.plugin.enabled', 'Paseo plugins are enabled for the required Claude contract carrier.')\n : fail('claude.plugin.enabled',\n 'Claude rooms require the paseo-room trusted server plugin, but Paseo plugins are disabled. Plugins are trusted, unsandboxed code with access to the daemon machine.',\n 'Review that trust boundary, enable plugins in Paseo Settings, reload Paseo, then run setup again.');\n}\n\nfunction pluginRuntimeCheck(plugin: LivePlugin | undefined, expectedPath: string): Check {\n if (plugin === undefined) {\n return fail('claude.plugin.runtime', `Plugin ${CLAUDE_CARRIER_PLUGIN_ID} is not registered.`, 'Run: paseo-room setup --apply');\n }\n if (plugin.path !== expectedPath) {\n return fail('claude.plugin.runtime', `Plugin ${CLAUDE_CARRIER_PLUGIN_ID} is registered from ${plugin.path}, not ${expectedPath}.`,\n 'Move or remove that conflicting plugin registration manually, then run setup again.');\n }\n if (!plugin.enabled || plugin.status !== 'running' || plugin.error !== undefined) {\n const detail = plugin.error === undefined ? `status ${plugin.status}` : `${plugin.status}: ${plugin.error}`;\n return fail('claude.plugin.runtime', `Plugin ${CLAUDE_CARRIER_PLUGIN_ID} is not running (${detail}).`, 'Run: paseo-room setup --apply');\n }\n return pass('claude.plugin.runtime', `Claude contract carrier plugin is running from ${expectedPath}.`);\n}\n\nasync function reconcilePlugin(\n session: Session, desired: Desired, plan: Plan, pending: readonly Operation[], expectedPath: string,\n): Promise<Check[]> {\n if (desired.pluginPath === undefined) {\n if (plan.livePlugin !== undefined) await session.removePlugin(CLAUDE_CARRIER_PLUGIN_ID);\n return [];\n }\n let plugin = plan.livePlugin;\n if (plugin === undefined) {\n plugin = await session.installPlugin(expectedPath, CLAUDE_CARRIER_PLUGIN_ID);\n } else {\n if (!plugin.enabled) plugin = await session.enablePlugin(CLAUDE_CARRIER_PLUGIN_ID);\n const filesChanged = pending.some(operation =>\n (operation.kind === 'file' || operation.kind === 'dir') && operation.target.startsWith(`${expectedPath}${sep}`),\n );\n const needsReload = filesChanged || plugin.status !== 'running' || plugin.error !== undefined;\n if (needsReload) plugin = await session.reloadPlugin(CLAUDE_CARRIER_PLUGIN_ID);\n }\n return [pluginRuntimeCheck(plugin, expectedPath)];\n}\n\n/**\n * The marker value for the Claude memory-contract choice. A room with no Claude seat records\n * nothing: the choice only describes Claude's `CLAUDE.md`, and storing it anyway would leave\n * state in the marker that nothing generated and nothing reads.\n */\nfunction markerMemoryContract(agents: readonly AgentId[], memoryContract: boolean): boolean | undefined {\n return agents.includes('claude') ? memoryContract : undefined;\n}\n\n/**\n * With the file carrier suppressed, the plugin is the room's only Claude carrier. The plugin\n * is verified, so this is not a silent risk — but whether a resumed session re-enters the\n * creation hook is unproven, so the operator is told what they gave up rather than reassured.\n */\nfunction memoryContractDiagnostic(agents: readonly AgentId[], memoryContract: boolean): Check[] {\n if (memoryContract || !agents.includes('claude')) return [];\n return [warn('claude.memory-contract',\n 'Claude role CLAUDE.md files carry your global memory only: the role contract was not written to them, so the trusted server plugin is this room\\'s only Claude carrier. Only a newly created agent passes through its creation hook, and whether a resumed session re-enters that hook is unproven.',\n 'Drop --no-claude-memory-contract and run setup --apply to restore the file fallback.')];\n}\n\n/** The whole product: write the role homes, then register them with Paseo. */\nexport async function setup(options: RunOptions = {}): Promise<Result> {\n const layout = resolveLayout(options, options.env);\n const agents = options.agents ?? ['codex'];\n const memoryContract = options.claudeMemoryContract ?? true;\n const invalid = layoutChecks(layout, agents);\n if (invalid.length > 0) return failed('setup', invalid);\n const rootSafety = await roomPathSafety(layout, [], []);\n if (hasFailure(rootSafety)) return failed('setup', rootSafety);\n const previous = await readMarker(layout);\n const safetyAgents = [...new Set([...agents, ...(previous?.agents ?? [])])];\n const pathSafety = await roomPathSafety(layout, safetyAgents, ROLES);\n if (hasFailure(pathSafety)) return failed('setup', pathSafety);\n // Cleanup uses the APIs required by the old selection too (notably Claude's plugin API).\n const compatibilityAgents = [...new Set([...agents, ...(previous?.agents ?? [])])];\n const daemon = await checkDaemon(layout, options.env, minimumPaseoVersion(compatibilityAgents));\n if (!daemon.daemon) return failed('setup', daemon.checks);\n const desired = await buildDesired(layout, agents, ROLES, { memoryContract });\n const stale = await staleFrom(layout, previous, agents, ROLES);\n const retained = stale.retainedDirectories.length === 0 ? [] : [warn(\n 'room.stale-role-homes-preserved',\n `Preserved ${String(stale.retainedDirectories.length)} deselected role homes because they may contain role-owned credentials or runtime state.`,\n `Use paseo-room remove --apply to delete the entire room after reviewing its credential warning, or remove deselected homes manually: ${stale.retainedDirectories.join(', ')}`,\n )];\n const checks = [...daemon.checks, ...desired.checks, ...retained];\n if (hasFailure(checks)) return failed('setup', checks);\n\n return withSession(daemon.daemon, async session => {\n const expectedPluginPath = claudeCarrierPluginDir(layout);\n const plan = await planRoom(session, desired, stale, expectedPluginPath);\n const { operations, liveProfiles } = plan;\n const pending = operations.filter(operation => operation.action !== 'noop');\n const pluginPreconditions = desired.pluginPath === undefined\n ? plan.pluginChecks\n : [pluginsEnabledCheck(await session.pluginsEnabled()), ...plan.pluginChecks];\n // Diagnostics last: nothing above may be reached only through a warning.\n const preApplyDiagnostics = [...checks, ...pluginPreconditions, ...memoryContractDiagnostic(agents, memoryContract), ...contractProvenance(previous), ...thinkingDiagnostics(liveProfiles, desired.profiles)];\n if (hasFailure(preApplyDiagnostics) || !options.apply) {\n return {\n command: 'setup',\n outcome: hasFailure(preApplyDiagnostics) ? 'failed' : pending.length > 0 ? 'changes-planned' : 'ok',\n changed: false, checks: preApplyDiagnostics, operations,\n } satisfies Result;\n }\n // Keep the old marker until daemon reconciliation succeeds. If a remote write fails,\n // rerunning setup can still discover every stale provider/profile/plugin it must remove.\n const markerPath = join(layout.roomHome, MARKER);\n const markerEntries = desired.entries.filter(entry => entry.path === markerPath);\n await applyEntries(desired.entries.filter(entry => entry.path !== markerPath));\n const ids = Object.keys(desired.providers);\n await session.writeProviders(desired.providers);\n if (stale.providerIds.length > 0) await session.removeProviders(stale.providerIds);\n // Profiles point at providers, so they are written once the providers exist — and\n // only when something changed, since one write replaces the host's whole array.\n let appliedProfiles = liveProfiles;\n if (pending.some(operation => operation.kind === 'profile')) {\n appliedProfiles = mergeProfiles(liveProfiles, desired.profiles, stale.profileIds);\n await session.writeProfiles(appliedProfiles);\n }\n await session.refresh(ids);\n const pluginChecks = await reconcilePlugin(session, desired, plan, pending, expectedPluginPath);\n await applyEntries(markerEntries);\n const appliedMarker: Marker = {\n version: metadata.version, agents: [...agents], roles: [...ROLES], contract: contractDigest(),\n ...(markerMemoryContract(agents, memoryContract) === false ? { claudeMemoryContract: false } : {}),\n };\n const appliedChecks = [...checks, ...pluginPreconditions, ...pluginChecks,\n pass('room.applied', `Room ready at ${layout.roomHome} with ${String(ids.length)} Paseo providers.`),\n ...memoryContractDiagnostic(agents, memoryContract),\n ...contractProvenance(appliedMarker), ...thinkingDiagnostics(appliedProfiles, desired.profiles)];\n return {\n command: 'setup', outcome: hasFailure(appliedChecks) ? 'failed' : 'ok', changed: pending.length > 0,\n checks: appliedChecks, operations,\n } satisfies Result;\n }, sessionOptions(options));\n}\n\nexport async function verify(options: RunOptions = {}): Promise<Result> {\n const layout = resolveLayout(options, options.env);\n const rootSafety = await roomPathSafety(layout, [], []);\n if (hasFailure(rootSafety)) return failed('verify', rootSafety);\n const marker = await readMarker(layout);\n if (!marker) {\n return failed('verify', [fail('room.marker', `No room found at ${layout.roomHome}.`, 'Run: paseo-room setup --apply')]);\n }\n const invalid = layoutChecks(layout, marker.agents);\n if (invalid.length > 0) return failed('verify', invalid);\n const pathSafety = await roomPathSafety(layout, marker.agents, marker.roles);\n if (hasFailure(pathSafety)) return failed('verify', pathSafety);\n const daemon = await checkDaemon(layout, options.env, minimumPaseoVersion(marker.agents));\n if (!daemon.daemon) return failed('verify', daemon.checks);\n const desired = await buildDesired(layout, marker.agents, marker.roles, {\n // The room's own recorded choice, so verify compares against what setup wrote.\n memoryContract: marker.claudeMemoryContract ?? true,\n });\n const checks = [...daemon.checks, ...desired.checks];\n if (hasFailure(checks)) return failed('verify', checks);\n\n return withSession(daemon.daemon, async session => {\n const expectedPluginPath = claudeCarrierPluginDir(layout);\n const plan = await planRoom(session, desired, NOTHING_STALE, expectedPluginPath);\n const { operations, liveProfiles } = plan;\n const drifted = operations.filter(operation => operation.action !== 'noop');\n const count = (kind: Operation['kind']): number => drifted.filter(operation => operation.kind === kind).length;\n const providers = count('provider');\n const profiles = count('profile');\n const driftedFiles = drifted.filter(operation => !['provider', 'profile', 'plugin'].includes(operation.kind));\n const files = driftedFiles.length;\n const pluginChecks = desired.pluginPath === undefined ? [] : [\n pluginsEnabledCheck(await session.pluginsEnabled()),\n ...plan.pluginChecks,\n pluginRuntimeCheck(plan.livePlugin, expectedPluginPath),\n ];\n const all: Check[] = [...checks,\n files === 0\n ? pass('room.files', 'Every managed role file matches the current definition.')\n : fail('room.files', `${fileDriftSummary(driftedFiles)}${fileDriftDetail(driftedFiles.map(operation => operation.target))}`, 'Run: paseo-room setup --apply'),\n providers === 0\n ? pass('room.providers', `All ${String(Object.keys(desired.providers).length)} Paseo providers are registered as expected.`)\n : fail('room.providers', `${String(providers)} Paseo providers are missing or differ.`, 'Run: paseo-room setup --apply'),\n profiles === 0\n ? pass('room.profiles', `All ${String(desired.profiles.length)} Paseo agent profiles are registered as expected.`)\n : fail('room.profiles', `${String(profiles)} Paseo agent profiles are missing or differ.`, 'Run: paseo-room setup --apply'),\n ...pluginChecks,\n // Diagnostics last: a warning never precedes the failure it might be mistaken for.\n ...memoryContractDiagnostic(marker.agents, marker.claudeMemoryContract ?? true),\n ...contractProvenance(marker),\n ...thinkingDiagnostics(liveProfiles, desired.profiles),\n ];\n return {\n command: 'verify', outcome: hasFailure(all) ? 'failed' : 'ok', changed: false, checks: all, operations,\n } satisfies Result;\n }, sessionOptions(options));\n}\n\nexport async function remove(options: RunOptions = {}): Promise<Result> {\n const layout = resolveLayout(options, options.env);\n const rootSafety = await roomPathSafety(layout, [], []);\n if (hasFailure(rootSafety)) return failed('remove', rootSafety);\n const marker = await readMarker(layout);\n if (!marker) {\n return failed('remove', [fail('room.marker', `No room found at ${layout.roomHome}.`, 'Nothing to remove; the room home was never created here.')]);\n }\n // A recursive delete needs a floor, so the layout rules gate this command too.\n const invalid = layoutChecks(layout, marker.agents);\n if (invalid.length > 0) return failed('remove', invalid);\n const ids = marker.agents.flatMap(agent => marker.roles.map(role => providerId(agent, role)));\n const profiles = new Set(marker.agents.flatMap(agent => marker.roles.map(role => profileId(agent, role))));\n const hasClaude = marker.agents.includes('claude');\n const operations: Operation[] = [\n ...ids.map(id => ({ action: 'remove', kind: 'provider', target: id }) satisfies Operation),\n ...[...profiles].map(id => ({ action: 'remove', kind: 'profile', target: id }) satisfies Operation),\n ...(hasClaude ? [{ action: 'remove', kind: 'plugin', target: CLAUDE_CARRIER_PLUGIN_ID } satisfies Operation] : []),\n { action: 'remove', kind: 'dir', target: layout.roomHome },\n ];\n const credentialWarning = warn('room.remove.credentials',\n `Deleting ${layout.roomHome} will delete role-owned credential files stored inside it. Native OS keyring entries are not inspected or deleted and may remain. Operator agent-home credentials are untouched.`);\n if (!options.apply) {\n return { command: 'remove', outcome: 'changes-planned', changed: false, checks: [credentialWarning], operations };\n }\n const daemon = await checkDaemon(layout, options.env);\n const checks: Check[] = [credentialWarning];\n if (!daemon.daemon) {\n return failed('remove', [\n credentialWarning,\n ...daemon.checks,\n fail(\n 'room.files',\n `Preserved ${layout.roomHome}, including its room marker, because Paseo cleanup could not start.`,\n 'Start Paseo, then run: paseo-room remove --apply',\n ),\n ]);\n }\n try {\n await withSession(daemon.daemon, async session => {\n if (hasClaude) {\n const plugin = (await session.listPlugins()).find(entry => entry.id === CLAUDE_CARRIER_PLUGIN_ID);\n const expectedPath = claudeCarrierPluginDir(layout);\n if (plugin !== undefined && plugin.path !== expectedPath) {\n throw new Error(`refusing to remove foreign plugin path ${plugin.path}`);\n }\n if (plugin !== undefined) await session.removePlugin(CLAUDE_CARRIER_PLUGIN_ID);\n }\n await session.removeProviders(ids);\n const live = await session.readProfiles();\n const kept = live.filter(entry => !profiles.has(String(entry.id)));\n if (kept.length !== live.length) await session.writeProfiles(kept);\n }, sessionOptions(options));\n checks.push(pass('room.providers', `Removed ${String(ids.length)} Paseo providers and their agent profiles.`));\n } catch {\n return failed('remove', [\n credentialWarning,\n fail(\n 'room.providers',\n `Paseo provider/profile cleanup did not complete; ${layout.roomHome} and its room marker were preserved.`,\n 'Restore Paseo connectivity, then run: paseo-room remove --apply',\n ),\n ]);\n }\n // Explicit remove owns the whole room home, including runtime-owned role credentials.\n try {\n await rm(layout.roomHome, { recursive: true, force: true });\n } catch (error) {\n const detail = error instanceof Error ? error.message : 'unknown filesystem error';\n checks.push(fail(\n 'room.files',\n `Removed the Paseo providers and profiles, but could not fully delete ${layout.roomHome}: ${detail}`,\n 'Delete that directory manually after reviewing it for role-owned credentials; the Paseo side is already clean.',\n ));\n const completedOperations = operations.filter(operation => operation.kind !== 'dir');\n return { command: 'remove', outcome: 'failed', changed: true, checks, operations: completedOperations };\n }\n checks.push(pass('room.files', `Deleted ${layout.roomHome}.`));\n return { command: 'remove', outcome: 'ok', changed: true, checks, operations };\n}\n","import * as clack from '@clack/prompts';\nimport { AGENTS, remove, setup, verify, type RunOptions } from './commands.js';\nimport type { Result } from './result.js';\nimport { AGENT_IDS, type AgentId } from './roles.js';\n\nexport interface Prompts {\n select(options: { readonly message: string; readonly options: readonly { readonly value: string; readonly label: string }[] }): Promise<string | symbol>;\n multiselect(options: { readonly message: string; readonly options: readonly { readonly value: AgentId; readonly label: string }[] }): Promise<AgentId[] | symbol>;\n confirm(options: { readonly message: string }): Promise<boolean | symbol>;\n}\nexport const terminalPrompts: Prompts = {\n select: options => clack.select({ message: options.message, options: [...options.options] }),\n multiselect: options => clack.multiselect({ message: options.message, options: [...options.options], required: true }),\n confirm: options => clack.confirm({ message: options.message, initialValue: false }),\n};\n\n/** Guided path over the same commands the flags use; nothing extra happens here. */\nexport async function runWizard(\n prompts: Prompts,\n emit: (result: Result) => number,\n write: (text: string) => void,\n options: RunOptions = {},\n onAction?: (action: string) => void,\n): Promise<number> {\n const cancelled = (): number => { write('Cancelled; nothing was changed.\\n'); return 0; };\n const action = await prompts.select({\n message: 'What do you want to do?',\n options: [\n { value: 'setup', label: 'Set up / update the room (login stays separate)' },\n { value: 'verify', label: 'Verify the current room' },\n { value: 'remove', label: 'Remove the room' },\n ],\n });\n if (typeof action === 'symbol') return cancelled();\n onAction?.(action);\n if (action === 'verify') return emit(await verify(options));\n if (action === 'remove') {\n const preview = await remove(options);\n const status = emit(preview);\n if (preview.outcome !== 'changes-planned') return status;\n const approved = await prompts.confirm({ message: 'Delete the room home, including role credentials, and its Paseo providers?' });\n return approved === true ? emit(await remove({ ...options, apply: true })) : cancelled();\n }\n const agents = await prompts.multiselect({\n message: 'Which coding agents should the room use?',\n options: AGENT_IDS.map(value => ({ value, label: AGENTS[value].label })),\n });\n if (typeof agents === 'symbol' || agents.length === 0) return cancelled();\n // Only meaningful for Claude: the other adapters have no plugin carrier to fall back from.\n let claudeMemoryContract = true;\n if (agents.includes('claude')) {\n const carrier = await prompts.select({\n message: 'Claude role contract carrier: the room plugin is always used. Also write the contract into each role CLAUDE.md?',\n options: [\n { value: 'both', label: 'Yes — keep it as a fallback (recommended; resume behaviour is unproven)' },\n { value: 'plugin', label: 'No — plugin only; CLAUDE.md keeps your global memory alone' },\n ],\n });\n if (typeof carrier === 'symbol') return cancelled();\n claudeMemoryContract = carrier === 'both';\n }\n const setupOptions = { ...options, agents, claudeMemoryContract };\n const preview = await setup(setupOptions);\n const status = emit(preview);\n if (preview.outcome !== 'changes-planned') return status;\n const approved = await prompts.confirm({ message: 'Apply these changes? Authentication will not be validated or started.' });\n if (approved !== true) return cancelled();\n return emit(await setup({ ...setupOptions, apply: true }));\n}\n","import { Command, CommanderError, InvalidArgumentError } from 'commander';\nimport metadata from '../package.json' with { type: 'json' };\nimport { loginRole, type LoginSpawner } from './auth.js';\nimport { remove, setup, verify, type RunOptions } from './commands.js';\nimport { renderHuman, renderJson } from './render.js';\nimport { exitCode, fail, failed, type Result } from './result.js';\nimport { AGENT_IDS, type AgentId } from './roles.js';\nimport { PromptAssetError } from './room/prompts.js';\nimport type { Prompts } from './wizard.js';\n\nexport interface Output {\n readonly stdout: (text: string) => void;\n readonly stderr: (text: string) => void;\n}\nexport interface CliContext {\n readonly isTTY?: boolean;\n readonly prompts?: Prompts;\n readonly options?: RunOptions;\n readonly loginSpawn?: LoginSpawner;\n}\n\n/** Commander passes no initial value, so the first call starts the list. */\nfunction collectAgent(value: string, previous: AgentId[] | undefined): AgentId[] {\n const agent = AGENT_IDS.find(id => id === value);\n if (!agent) throw new InvalidArgumentError(`Unknown agent: ${value}`);\n const seated = previous ?? [];\n return seated.includes(agent) ? seated : [...seated, agent];\n}\n\nconst PATH_FLAGS = ['roomHome', 'codexHome', 'claudeHome', 'piHome', 'codexBin', 'claudeBin', 'piBin', 'paseoBin'] as const;\n\nfunction optionsFrom(raw: Record<string, unknown>, base: RunOptions): RunOptions {\n const paths: Record<string, string> = {};\n for (const flag of PATH_FLAGS) {\n const value = raw[flag];\n if (typeof value === 'string' && value.trim()) paths[flag] = value.trim();\n }\n const agents = Array.isArray(raw.agent) && raw.agent.length > 0 ? (raw.agent as AgentId[]) : undefined;\n return {\n ...base, ...paths, ...(agents ? { agents } : {}), ...(raw.apply === true ? { apply: true } : {}),\n // Commander defaults a --no- flag to true, so only an explicit opt-out is carried.\n ...(raw.claudeMemoryContract === false ? { claudeMemoryContract: false } : {}),\n };\n}\n\nfunction failedFromThrown(command: string, error: unknown): Result {\n if (error instanceof PromptAssetError) {\n return failed(command, [fail(\n `${command}.prompt-asset`,\n error.message,\n 'Reinstall paseo-room, then try again.',\n )]);\n }\n const detail = error instanceof Error ? error.message : 'unknown error';\n return failed(command, [fail(\n `${command}.error`,\n detail,\n 'Check that Paseo is running and reachable, then try again.',\n )]);\n}\n\nexport async function runCli(argv: readonly string[], output: Output, context: CliContext = {}): Promise<number> {\n const password = (context.options?.env ?? process.env).PASEO_PASSWORD;\n const redact = (text: string): string => (password ? text.split(password).join('[redacted]') : text);\n // Set once the flags are parsed; the wizard path never sees flags, so text output is right there.\n let json = false;\n const emit = (result: Result): number => {\n output.stdout(redact(json ? renderJson(result) : renderHuman(result)));\n return exitCode(result);\n };\n const isTTY = context.isTTY ?? (process.stdin.isTTY && process.stdout.isTTY && process.stderr.isTTY);\n const base = context.options ?? {};\n\n if (argv.length === 0) {\n if (!isTTY) {\n output.stderr('paseo-room: no command given. Try: paseo-room setup, verify, remove, auth login, or --help.\\n');\n return 2;\n }\n let wizardCommand = 'wizard';\n try {\n // @clack/prompts is only reachable here, so keep it off the scripted path.\n const { runWizard, terminalPrompts } = await import('./wizard.js');\n return await runWizard(\n context.prompts ?? terminalPrompts,\n emit,\n text => { output.stdout(text); },\n base,\n action => { wizardCommand = action; },\n );\n } catch (error) {\n return emit(failedFromThrown(wizardCommand, error));\n }\n }\n const program = new Command()\n .name('paseo-room')\n .description('Configure Codex/Claude/Pi role homes in $HOME and register them with your local Paseo daemon.')\n .version(metadata.version)\n .usage('<setup|verify|remove> [options]\\n auth login <codex|claude|pi> <supervisor|lead|peer> [options]')\n .argument('<command>', 'setup | verify | remove | auth')\n .argument('[command-arguments...]', 'auth login <agent> <role>')\n .option('--agent <agent>', 'codex, claude, or pi; repeat to combine (default: codex)', collectAgent)\n .option('--apply', 'actually make the changes (default: dry run)')\n .option('--json', 'machine-readable output')\n .option('--no-claude-memory-contract', 'omit the role contract from Claude role CLAUDE.md files, leaving the room plugin as the only Claude carrier')\n .option('--room-home <path>', 'where role homes are written (default: ~/.paseo-room)')\n .option('--codex-home <path>', 'source Codex config (default: ~/.codex)')\n .option('--claude-home <path>', 'source Claude Code config (default: ~/.claude)')\n .option('--pi-home <path>', 'source Pi config (default: ~/.pi/agent)')\n .option('--codex-bin <path>', 'Codex executable (default: found on PATH)')\n .option('--claude-bin <path>', 'Claude Code executable (default: found on PATH)')\n .option('--pi-bin <path>', 'Pi executable (default: found on PATH)')\n .option('--paseo-bin <path>', 'Paseo executable (default: found on PATH)')\n .configureOutput({ writeOut: text => { output.stdout(text); }, writeErr: text => { output.stderr(text); } })\n .exitOverride();\n\n let command: string;\n let commandArguments: string[];\n let options: RunOptions;\n let raw: Record<string, unknown>;\n try {\n program.parse([...argv], { from: 'user' });\n raw = program.opts<Record<string, unknown>>();\n json = raw.json === true;\n command = program.args[0] ?? '';\n commandArguments = program.args.slice(1);\n options = optionsFrom(raw, base);\n } catch (error) {\n if (error instanceof CommanderError && error.exitCode === 0) return 0;\n return 2;\n }\n\n try {\n // Only setup chooses this: verify and remove read the room's recorded choice instead, and\n // auth does not carry it at all. Silently ignoring it would misreport what the run did.\n if (raw.claudeMemoryContract === false && (command === 'verify' || command === 'remove')) {\n output.stderr(`paseo-room ${command}: --no-claude-memory-contract is a setup choice recorded in the room marker; ${command} reads it from there.\\n`);\n return 2;\n }\n if (command === 'auth') {\n if (raw.claudeMemoryContract === false) {\n output.stderr('paseo-room auth login only authenticates a role and does not use --no-claude-memory-contract.\\n');\n return 2;\n }\n if (raw.apply === true) {\n output.stderr('paseo-room auth login is already explicit and does not use --apply.\\n');\n return 2;\n }\n if (raw.json === true) {\n output.stderr('paseo-room auth login is interactive and does not support --json.\\n');\n return 2;\n }\n if (raw.agent !== undefined) {\n output.stderr('paseo-room auth login takes exactly one positional agent and does not use --agent.\\n');\n return 2;\n }\n if (commandArguments.length !== 3 || commandArguments[0] !== 'login') {\n output.stderr('Usage: paseo-room auth login <codex|claude|pi> <supervisor|lead|peer>\\n');\n return 2;\n }\n return await loginRole(commandArguments[1] ?? '', commandArguments[2] ?? '', {\n ...options,\n isTTY,\n ...(context.loginSpawn ? { spawn: context.loginSpawn } : {}),\n }, output);\n }\n if (commandArguments.length > 0) {\n output.stderr(`paseo-room ${command}: unexpected arguments: ${commandArguments.join(' ')}\\n`);\n return 2;\n }\n if (command === 'setup') return emit(await setup(options));\n if (command === 'verify') return emit(await verify(options));\n if (command === 'remove') return emit(await remove(options));\n } catch (error) {\n return emit(failedFromThrown(command, error));\n }\n output.stderr(`paseo-room: unknown command \"${command}\". Try: setup, verify, remove, or auth login.\\n`);\n return 2;\n}\n","import type { Result } from './result.js';\n\nexport function renderJson(result: Result): string {\n return `${JSON.stringify({ schemaVersion: 2, ...result }, null, 2)}\\n`;\n}\n\nconst ICONS = { pass: '✓', warn: '!', fail: '✗' } as const;\n\nexport function renderHuman(result: Result): string {\n const lines: string[] = [];\n for (const check of result.checks) {\n lines.push(`${ICONS[check.status]} ${check.message}`);\n if (check.fix) lines.push(` → ${check.fix}`);\n }\n const changes = result.operations.filter(operation => operation.action !== 'noop');\n if (changes.length > 0) {\n lines.push('', result.changed ? 'Applied:' : 'Planned changes:');\n for (const operation of changes) lines.push(` ${operation.action} ${operation.kind} ${operation.target}`);\n const unchanged = result.operations.length - changes.length;\n if (unchanged > 0) lines.push(` (${String(unchanged)} already up to date)`);\n } else if (result.operations.length > 0) {\n lines.push('', 'Everything is already up to date.');\n }\n lines.push('', `${result.command}: ${result.outcome}`);\n return `${lines.join('\\n')}\\n`;\n}\n","#!/usr/bin/env node\nimport { runCli } from './cli.js';\n\nprocess.exitCode = await runCli(process.argv.slice(2), {\n stdout: text => { process.stdout.write(text); },\n stderr: text => { process.stderr.write(text); },\n});\n"],"mappings":";;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA,MACE,MAAQ;AAAA,MACR,SAAW;AAAA,MACX,aAAe;AAAA,MACf,UAAY;AAAA,QACV;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MACA,UAAY;AAAA,MACZ,MAAQ;AAAA,MACR,YAAc;AAAA,QACZ,MAAQ;AAAA,QACR,KAAO;AAAA,MACT;AAAA,MACA,SAAW;AAAA,MACX,QAAU;AAAA,MACV,MAAQ;AAAA,MACR,SAAW;AAAA,QACT,MAAQ;AAAA,MACV;AAAA,MACA,KAAO;AAAA,QACL,cAAc;AAAA,MAChB;AAAA,MACA,OAAS;AAAA,QACP;AAAA,MACF;AAAA,MACA,SAAW;AAAA,QACT,WAAa;AAAA,QACb,MAAQ;AAAA,QACR,MAAQ;AAAA,QACR,gBAAgB;AAAA,QAChB,OAAS;AAAA,QACT,SAAW;AAAA,QACX,QAAU;AAAA,MACZ;AAAA,MACA,cAAgB;AAAA,QACd,kBAAkB;AAAA,QAClB,oBAAoB;AAAA,QACpB,WAAa;AAAA,QACb,QAAU;AAAA,QACV,aAAa;AAAA,QACb,KAAO;AAAA,MACT;AAAA,MACA,iBAAmB;AAAA,QACjB,cAAc;AAAA,QACd,eAAe;AAAA,QACf,iBAAiB;AAAA,QAC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AAE,YAAQ,OAAO,MAAM,IAAI;AAAA,EAAG;AAAA,EAC9C,QAAQ,UAAQ;AAAE,YAAQ,OAAO,MAAM,IAAI;AAAA,EAAG;AAChD,CAAC;","names":["stat","lstat","readlink","join","stat","title","join","join","resolve","constants","join","lstat","env","argv","resolve","table","readdir","join","readFile","join","join","SHARED","EXECUTABLE","evidence","spawn","readFile","rm","isAbsolute","join","resolve","asObject","command","AUTH_ENV","SHARED","EXECUTABLE","z","run","readFileSync","join","join","sep","lstat","rm","stat","preview","status","approved","runWizard","terminalPrompts"]}