{"version":3,"sources":["../src/api.ts","../src/key.ts","../src/redact.ts","../src/server-names.ts","../src/runtime-manifest.ts","../src/runtime-spec-override.ts","../src/signer-runtime.ts","../src/connect-error.ts","../src/tombstone.ts","../src/storage.ts","../src/config-writers.ts","../src/local-mcp-consent.ts","../src/probes.ts","../src/local-mcp-runtime.ts","../src/skill-install.ts","../src/runtime-registry.ts","../src/signer-consent.ts","../src/runtime-install.ts","../src/installed-clients.ts","../src/wiring-collision.ts","../src/unwire.ts","../src/runtime.ts","../src/rekey-messages.ts","../src/prune-runtimes.ts","../src/rekey.ts","../src/rekey-restart.ts","../src/doctor.ts","../src/args.ts","../src/index.ts","../src/cli.ts"],"names":["Wallet","crypto","MCP_RUNTIME_MANIFEST","MCP_VERSION","HAVEN_MINIMUM_NODE_VERSION","registeredToolNames","signerToolSchemas","createHash","homedir","resolve","join","mkdir","chmod","readFile","dirname","writeFile","access","promisify","execFile","ConnectError","nextAction","readdir","connectorRerunCommand","stat","CONNECT_OUTCOME_FILENAME","rm","basename","rename","path","parseDocument","isMap","replacement","needsTrailingNewline","stringify","unlink","merged","platform","ensureConsent","computeConsentHash","loadCredentials","consentInputFromClient","spawn","installRuntimePackages","installedRuntimeMatches","assertFileExists","readInstalledVersions","writeWrapper","writeRuntimeSidecar","isSupportedNodeVersion","execFileAsync","readPackageJson","unsupportedNodeVersionMessage","SKILL_FOLDER_NAME","HAVEN_SKILL_MD","HAVEN_SKILL_BODY_MD","RUNTIME_FLAG_VALUES","ensureSignerConsent","writeLogChunk","computeSignerConsentHash","loadSignerCredentials","signer","createEdgeSigner","toolSchemas","signerCredentialReady","errorCode","fsReadFile","createInterface","pathExists","MAX_PROMPT_ATTEMPTS","CONNECTOR_VERSION","CONNECT_OUTCOME_SCHEMA_VERSION","resolveTokenFromAddress","realpath","identity","pruneSignerRuntimes","writeAgentTombstone","tombstonesDirForAgentDirectory","unwireAgent","resolveAgentDirectoryBySlug","startRekey","finishRekey","restartGuidance","result","runDoctor","runRepair","realp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BAAA,CAAkB,OAAO,OAAA,CAAQ,OAAA,EAAS,GAAG,CAAC,CAAC;AAAA,CAAI,CAAA;AAAA,IACjF,CAAA,MAAO;AACL,MAAA,EAAA,CAAG,MAAA,CAAO,CAAA,EAAG,aAAA,CAAc,GAAA,YAAe,KAAA,GAAQ,IAAI,OAAA,GAAU,MAAA,CAAO,GAAG,CAAC,CAAC;AAAA,CAAI,CAAA;AAAA,IAClF;AACA,IAAA,OAAO,CAAA;AAAA,EACT;AACF;AAEA,eAAe,IAAA,GAAsB;AACnC,EAAA,MAAM,WAAW,MAAM,MAAA,CAAO,QAAQ,IAAA,CAAK,KAAA,CAAM,CAAC,CAAC,CAAA;AACnD,EAAA,IAAI,QAAA,KAAa,CAAA,EAAG,OAAA,CAAQ,QAAA,GAAW,QAAA;AACzC;AAQO,SAAS,eAAA,CACd,WAA+B,OAAA,CAAQ,IAAA,CAAK,CAAC,CAAA,EAC7C,SAAA,GAAoB,2PAAY,EACvB;AACT,EAAA,IAAI,CAAC,UAAU,OAAO,KAAA;AACtB,EAAA,IAAI;AACF,IAAA,OAAOE,gBAAa,QAAQ,CAAA,KAAMA,eAAA,CAAaC,iBAAA,CAAc,SAAS,CAAC,CAAA;AAAA,EACzE,CAAA,CAAA,MAAQ;AAGN,IAAA,OAAOC,iBAAA,CAAc,QAAQ,CAAA,CAAE,IAAA,KAAS,SAAA;AAAA,EAC1C;AACF;AAEA,IAAI,eAAA,EAAgB,EAAG,KAAK,IAAA,EAAK;;;ADzhBjC,oBAAA,EAAA;AAMA,mBAAA,EAAA;AAKA,qBAAA,EAAA;AAUA,kBAAA,EAAA;AACA,sBAAA,EAAA;AAUA,YAAA,EAAA;AAWA,qBAAA,EAAA","file":"index.cjs","sourcesContent":["export interface ConnectApiClient {\n  resolveSetup(input: ResolveSetupInput): Promise<ResolvedSetup>\n  registerSetup(input: RegisterSetupInput): Promise<RegisterSetupResponse>\n  updateInstallStatus(\n    setupId: string,\n    apiKey: string,\n    input: UpdateInstallStatusInput,\n  ): Promise<void>\n  /**\n   * #1377 D: the narrow status read the connector polls after registering,\n   * authenticated with the agent API key it just minted (works while the\n   * agent is still `setup_pending` — the endpoint exists for exactly that\n   * window). Returns status plus the approved budget once approval lands;\n   * never any secret material.\n   */\n  getConnectorStatus(setupId: string, apiKey: string): Promise<ConnectorStatusResponse>\n  /**\n   * #1700: the agent behind an API key. Used by the re-key flow on both sides\n   * of the dashboard hand-off — see {@link AgentIdentity}.\n   */\n  getAgentIdentity(apiKey: string): Promise<AgentIdentity>\n  /**\n   * #3772: tell Haven which agents this run's `--replace` retired locally, so\n   * their own reads can warn a still-running session. Authenticated with the\n   * NEW agent's key. `null` when the backend predates the route (404); any\n   * other failure throws for the caller to log. Warning-only on the backend:\n   * nothing is paused or revoked.\n   */\n  reportRetiredAgents?(input: ReportRetiredAgentsInput): Promise<{ recordedAgentIds: string[] } | null>\n}\n\nexport interface ReportRetiredAgentsInput {\n  setupId: string\n  apiKey: string\n  retiredAgentIds: readonly string[]\n}\n\nexport interface ConnectorStatusResponse {\n  status: string\n  approved_budget: {\n    token_symbol: string\n    token_address: string\n    amount: string\n    reset_period_min: number\n  } | null\n}\n\nexport interface ResolveSetupInput {\n  setupToken: string\n  connectorVersion: string\n  runtime?: string\n}\n\nexport interface RegisterSetupInput extends ResolveSetupInput {\n  challengeId: string\n  delegateAddress: string\n  proofSignature: string\n  apiKeyHash: string\n  apiKeyPrefix: string\n  /**\n   * #1878: the RESOLVED hosted MCP server name this agent is being wired as —\n   * `haven` for the bare pair, `haven-<slug>` for a named one. Sent so the\n   * dashboard can tell two agents in one harness apart; it is a display aid\n   * and Haven keys nothing off it.\n   *\n   * Always sent by a connector that supports it, bare pair included. Omitting\n   * it for the bare pair would make \"absent\" ambiguous between *this is the\n   * unnamed pair* and *an older connector said nothing*, and only the second\n   * of those may render as unknown.\n   */\n  mcpServerName?: string\n  /**\n   * #2528: how this run was invoked — `'json'` when `--json` was passed,\n   * `'prose'` otherwise. The connector is the only party that can report it:\n   * the register call is byte-identical over the wire either way, so there is\n   * no header, user agent or timing signal the backend could recover it from.\n   * Optional on the wire so an older backend simply ignores it.\n   */\n  runMode?: 'json' | 'prose'\n  connectorContext?: ConnectorContext\n  installCapabilities?: {\n    canWriteRuntimeConfig?: boolean\n    restartRequired?: boolean\n  }\n}\n\nexport interface UpdateInstallStatusInput {\n  runtime?: string\n  connectorVersion: string\n  runtimeMcpMode?: string\n  hostedMcpConfigured: boolean\n  localSignerConfigured: boolean\n  localMcpConfigured?: boolean\n  credentialFilesWritten?: boolean\n  signerAcknowledged?: boolean\n  localMcpAcknowledged?: boolean\n  activationCommandAvailable?: boolean\n  skillInstalled?: boolean\n  /**\n   * Omitted on the #1543 early config-written report — no probe has run yet,\n   * and the backend merge keeps the key absent until the final report sets it.\n   */\n  probeResult?: string\n  restartRequired: boolean\n  nextUserAction: string\n  errorCode?: string | null\n  environmentLabel?: string\n  /**\n   * The other agent directories this machine holds, so the DASHBOARD can list\n   * them for the owner (#2561). Every other directory, not a replace set: the\n   * dashboard calls none of them replaced and offers no revoke (#3830).\n   *\n   * A tri-state, and the middle case is why it is not a plain array:\n   *\n   * - a list  — the scan ran and found these;\n   * - `[]`    — the scan ran and found none;\n   * - `null` or absent — the scan could not run.\n   *\n   * The connector cannot revoke and must not: `POST /agents/:id/revoke` is\n   * owner-authenticated, and an agent credential retiring a sibling agent is\n   * the \"agent editing its own authority\" the re-key routes already refuse.\n   * So this reports, and a human clicks.\n   *\n   * `null` matters because the alternative is a dashboard telling somebody\n   * \"nothing to revoke\" about a machine nobody managed to read.\n   */\n  supersededAgentIds?: readonly string[] | null\n}\n\nexport interface ConnectorContext {\n  environment_label?: string\n  runtime_version?: string\n  config_target?: string\n}\n\nexport interface ResolvedSetup {\n  setup_id: string\n  status: string\n  agent: {\n    name: string\n    description?: string | null\n  }\n  haven_wallet: {\n    id: string\n    name: string\n    address: string\n    chain_id: number\n    network: string\n  }\n  agent_budget: Array<{\n    token_address: string\n    token_symbol: string\n    allowance_amount: string\n    reset_period_min: number\n  }>\n  hosted_mcp_url: string\n  // Address the edge signer verifies x402 expected-context signatures against.\n  // null/absent when the backend has no x402 binding key configured.\n  x402_binding_signer?: string | null\n  challenge: {\n    id: string\n    message: string\n    expires_at: string\n  }\n}\n\nexport interface RegisterSetupResponse {\n  setup_id: string\n  agent_id: string\n  status: string\n  agent_status: string\n  api_key_prefix: string\n  api_key_scope: string\n  delegate_address: string\n  hosted_mcp_url: string\n  next_action: string\n  /**\n   * #2528: the absolute link that lands the user on this setup's budget\n   * approval. Optional because a backend older than #2528 does not send it,\n   * and the connector must degrade to its previous prose rather than print\n   * `undefined` — see `approvalCtaLine`.\n   */\n  approval_url?: string\n}\n\n/**\n * The agent identity behind an API key (#1700).\n *\n * Read from `GET /machine-payments/agent`, the same agent-authenticated\n * endpoint the SDK's `getAgent()` uses. Re-key needs it twice and for two\n * different questions: BEFORE, to refuse a legacy-rail account the way the\n * backend would rather than let the owner discover it five signed steps later;\n * and AFTER, to prove the API key the owner pasted really belongs to this\n * agent and really names the key this machine just generated.\n */\nexport interface AgentIdentity {\n  id: string\n  name: string\n  status: string\n  /** The Haven account (smart account) address. The server emits this ONLY as of #2914 — `safe_address` is retired. */\n  account_address: string | null\n  delegate_address: string | null\n  chain_id: number | null\n  execution_rail: 'legacy' | 'delegation' | string\n}\n\n/**\n * @param clientIdentity #3303: `@haven_ai/connect/<version>`, sent as\n *   `X-Haven-Client` on every request so the backend can tell an outdated\n *   connector what to run. Passed in by the callers that own\n *   `CONNECTOR_VERSION` (`runtime.ts` imports this file, so it cannot be\n *   imported here).\n */\nexport function createConnectApiClient(\n  baseUrl: string,\n  fetchImpl: typeof fetch = fetch,\n  clientIdentity?: string,\n): ConnectApiClient {\n  const root = baseUrl.replace(/\\/+$/, '')\n  const send = <T>(url: string, init: RequestInit): Promise<T> =>\n    request<T>(fetchImpl, url, clientIdentity\n      ? { ...init, headers: { ...(init.headers as Record<string, string> | undefined), 'X-Haven-Client': clientIdentity } }\n      : init)\n  return {\n    resolveSetup: (input) =>\n      send(`${root}/agent-connection-setups/resolve`, {\n        method: 'POST',\n        body: JSON.stringify({\n          setup_token: input.setupToken,\n          connector_version: input.connectorVersion,\n          runtime: input.runtime,\n        }),\n      }),\n\n    registerSetup: (input) =>\n      send(`${root}/agent-connection-setups/register`, {\n        method: 'POST',\n        body: JSON.stringify({\n          setup_token: input.setupToken,\n          challenge_id: input.challengeId,\n          delegate_address: input.delegateAddress,\n          proof_signature: input.proofSignature,\n          api_key_hash: input.apiKeyHash,\n          api_key_prefix: input.apiKeyPrefix,\n          runtime: input.runtime,\n          connector_version: input.connectorVersion,\n          mcp_server_name: input.mcpServerName,\n          run_mode: input.runMode,\n          connector_context: input.connectorContext,\n          install_capabilities: input.installCapabilities && {\n            can_write_runtime_config: input.installCapabilities.canWriteRuntimeConfig,\n            restart_required: input.installCapabilities.restartRequired,\n          },\n        }),\n      }),\n\n    getAgentIdentity: (apiKey) =>\n      send(`${root}/machine-payments/agent`, {\n        method: 'GET',\n        headers: { Authorization: `Bearer ${apiKey}` },\n      }),\n\n    getConnectorStatus: (setupId, apiKey) =>\n      send(`${root}/agent-connection-setups/${encodeURIComponent(setupId)}/connector-status`, {\n        method: 'GET',\n        headers: { Authorization: `Bearer ${apiKey}` },\n      }),\n\n    reportRetiredAgents: async (input) => {\n      try {\n        const body = await send<{ recorded_agent_ids?: unknown } | null>(\n          `${root}/agent-connection-setups/${encodeURIComponent(input.setupId)}/retired-agents`,\n          {\n            method: 'POST',\n            headers: { Authorization: `Bearer ${input.apiKey}` },\n            body: JSON.stringify({ retired_agent_ids: input.retiredAgentIds }),\n          },\n        )\n        const recorded = body?.recorded_agent_ids\n        return {\n          recordedAgentIds: Array.isArray(recorded) ? recorded.filter((id): id is string => typeof id === 'string') : [],\n        }\n      } catch (err) {\n        // An older backend has no such route: not a failure, nothing to retry.\n        if (err instanceof ConnectRequestError && err.status === 404) return null\n        throw err\n      }\n    },\n\n    updateInstallStatus: async (setupId, apiKey, input) => {\n      await send(`${root}/agent-connection-setups/${encodeURIComponent(setupId)}/install-status`, {\n        method: 'POST',\n        headers: { Authorization: `Bearer ${apiKey}` },\n        body: JSON.stringify({\n          runtime: input.runtime,\n          connector_version: input.connectorVersion,\n          runtime_mcp_mode: input.runtimeMcpMode,\n          hosted_mcp_configured: input.hostedMcpConfigured,\n          local_signer_configured: input.localSignerConfigured,\n          local_mcp_configured: input.localMcpConfigured,\n          credential_files_written: input.credentialFilesWritten,\n          signer_acknowledged: input.signerAcknowledged,\n          local_mcp_acknowledged: input.localMcpAcknowledged,\n          activation_command_available: input.activationCommandAvailable,\n          skill_installed: input.skillInstalled,\n          probe_result: input.probeResult,\n          restart_required: input.restartRequired,\n          next_user_action: input.nextUserAction,\n          error_code: input.errorCode ?? null,\n          environment_label: input.environmentLabel,\n          // Three states on the wire, and ABSENT is a fourth (#2561 review).\n          // `?? null` alone collapsed the fourth into the third: a report that\n          // simply had nothing to say — the early config-written ping, which\n          // fires before the scan has started — asserted \"the scan could not\n          // run\" instead of leaving the key alone. Inert today, because the\n          // complete report overwrites it seconds later and nothing reads the\n          // row in between; a landmine the moment any caller relies on\n          // \"absent = unchanged\", which is what the backend's jsonb merge\n          // means and what this field's own contract says.\n          //\n          // So: a caller that passes the field says something (`null` included,\n          // deliberately, since \"could not run\" is a claim worth making); a\n          // caller that omits it says nothing.\n          ...(input.supersededAgentIds !== undefined\n            ? { superseded_agent_ids: input.supersededAgentIds }\n            : {}),\n        }),\n      })\n    },\n  }\n}\n\n/**\n * Request failure carrying the HTTP status, so callers can tell a permanent\n * verdict (401 revoked key, 404 gone) from transient noise (5xx, network).\n * The approval poll loop (#1377 D) branches on this: retrying a 401 for the\n * full window and then saying \"still pending\" is actively wrong when the user\n * cancelled the setup and the key was revoked.\n */\nexport class ConnectRequestError extends Error {\n  constructor(message: string, readonly status: number) {\n    super(message)\n    this.name = 'ConnectRequestError'\n  }\n}\n\nasync function request<T>(\n  fetchImpl: typeof fetch,\n  url: string,\n  init: RequestInit,\n): Promise<T> {\n  const response = await fetchImpl(url, {\n    ...init,\n    headers: {\n      'Content-Type': 'application/json',\n      ...(init.headers ?? {}),\n    },\n  })\n  const text = await response.text()\n  const body = text ? JSON.parse(text) : null\n  if (!response.ok) {\n    const message = body?.error ?? body?.message ?? `${response.status} ${response.statusText}`\n    throw new ConnectRequestError(`Haven setup request failed: ${message}`, response.status)\n  }\n  return body as T\n}\n","import crypto from 'node:crypto'\nimport { Wallet } from 'ethers'\n\nexport interface LocalDelegateKey {\n  privateKey: string\n  address: string\n  signChallenge(message: string): Promise<string>\n}\n\nexport function generateDelegateKey(): LocalDelegateKey {\n  return delegateKeyFromPrivateKey(Wallet.createRandom().privateKey)\n}\n\nexport function delegateKeyFromPrivateKey(privateKey: string): LocalDelegateKey {\n  const wallet = new Wallet(privateKey)\n  return {\n    privateKey: wallet.privateKey,\n    address: wallet.address,\n    signChallenge: (message: string) => wallet.signMessage(message),\n  }\n}\n\nexport function generateAgentApiKey(): string {\n  return `sk_agent_${crypto.randomBytes(24).toString('hex')}`\n}\n\nexport function hashAgentApiKey(apiKey: string): string {\n  return crypto.createHash('sha256').update(apiKey).digest('hex')\n}\n\nexport function agentApiKeyPrefix(apiKey: string): string {\n  return apiKey.slice(0, 12)\n}\n","const API_KEY_RE = /sk_agent_[A-Za-z0-9]+/g\nconst PRIVATE_KEY_RE = /0x[0-9a-fA-F]{64}/g\n\nexport function redactSecrets(value: string): string {\n  return value\n    .replace(API_KEY_RE, 'sk_agent_[redacted]')\n    .replace(PRIVATE_KEY_RE, '0x[redacted-private-key]')\n}\n\n/**\n * Sanitizer for messages that enter the machine-readable `--json` contract\n * (#2091). The failure record used to omit the message entirely because it\n * \"can contain server or filesystem detail\"; keeping that stance made every\n * refusal opaque to automation. Redact instead of omit: secrets always, plus\n * the credential-file paths the human log already masks in redact-paths mode.\n */\nexport function redactForAutomation(value: string): string {\n  return redactSecrets(value)\n    .replace(/(?:~|\\/)[^\\s`\"']*\\/(?:identity|signer|agent)\\.json\\b/g, '[credential-file-redacted]')\n    .replace(/(?:~|\\/)[^\\s`\"']*\\/\\.env\\b/g, '[credential-env-redacted]')\n}\n\n/**\n * A URL with any `user:pass@` userinfo removed and trailing slashes dropped —\n * for log lines, `--json` records, the binding record's `api_url` and every\n * place a stored record is echoed or compared (#3154 reviews N6 / doc r2 /\n * doc r4: a record written before the write-side strip may still carry\n * userinfo, so the doctor strips on read as well). Unparseable input is\n * returned unchanged.\n */\nexport function withoutUserinfo(url: string): string {\n  try {\n    const parsed = new URL(url)\n    parsed.username = ''\n    parsed.password = ''\n    return parsed.toString().replace(/\\/+$/, '')\n  } catch {\n    return url\n  }\n}\n\nexport function shortAddress(address: string): string {\n  if (!/^0x[0-9a-fA-F]{40}$/.test(address)) return address\n  return `${address.slice(0, 6)}...${address.slice(-4)}`\n}\n","/**\n * MCP server-name pairs (#1695, epic #1694).\n *\n * One runtime config can hold several Haven agents, each as its own\n * hosted+signer MCP pair keyed by server name. The names are the wiring\n * contract every host depends on (server name = tool prefix), so:\n *\n * - The UNNAMED pair keeps today's exact names — bare `haven` /\n *   `haven-signer`, and Codex's historical `haven_signer` table — because a\n *   rename would break every currently-wired host (#1694 owner decision).\n * - A NAMED pair suffixes the slug: `haven-<slug>` / `haven-signer-<slug>`.\n *   The slug is fixed at connect time and never changes (#1694: editable\n *   display name, immutable wiring slug). #1696 wires the `--name` flag.\n *\n * Hermes stores each pair's API key in its dotenv file, so a named pair also\n * needs its own env key — two agents sharing `MCP_HAVEN_API_KEY` would both\n * authenticate as whichever setup ran last.\n */\n\nexport interface ServerNames {\n  /** Hosted MCP entry name in JSON/YAML configs and the Claude Code registry. */\n  hosted: string\n  /** Signer entry name in JSON/YAML configs and the Claude Code registry. */\n  signer: string\n  /** Codex TOML table name for the hosted entry (`mcp_servers.<name>`). */\n  codexHosted: string\n  /** Codex TOML table name for the signer entry. */\n  codexSigner: string\n  /** Hermes dotenv key holding this pair's hosted API key. */\n  hermesEnvKey: string\n}\n\n/**\n * Slug shape: lowercase alphanumerics and single hyphens, 1–32 chars. Strict\n * on purpose — the slug becomes a server name, a TOML bare key, part of an\n * env var, and a tool prefix, and it is immutable once wired.\n */\nconst SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/\n\nexport function assertValidServerSlug(slug: string): void {\n  if (slug.length === 0 || slug.length > 32 || !SLUG_RE.test(slug)) {\n    throw new Error(\n      `Invalid server name ${JSON.stringify(slug)}: use 1-32 lowercase letters, digits, and single hyphens (e.g. \"research\").`,\n    )\n  }\n  // Collision-freedom (#1695 review, blocking finding): every derived name\n  // must be unique across ALL valid slugs and the bare pair, or \"a writer\n  // touches only its own pair\" is false. The only cross-collisions the\n  // haven-<slug> / haven-signer-<slug> scheme admits are:\n  //   hosted(A) === bare signer      ⇔ A === 'signer'\n  //   hosted(A) === signer(B), A≠B   ⇔ A === `signer-${B}`\n  // (signer(A) === signer(B) and hosted(A) === hosted(B) already force A===B.)\n  // Rejecting 'signer' and the 'signer-' prefix therefore closes the whole\n  // family, not just the literal case — proven by the adversarial-pair test.\n  // #1696: the bare pair's own names are refused as slugs outright — not a\n  // collision ('haven' would yield 'haven-haven'), but an operator typing\n  // --name haven means the bare pair, and silently minting a doubled name\n  // would wire an agent nobody can find again.\n  if (slug === 'haven' || slug === 'haven-signer') {\n    throw new Error(\n      `Invalid server name ${JSON.stringify(slug)}: \"haven\" and \"haven-signer\" are the unnamed pair's own names — omit --name for the bare pair.`,\n    )\n  }\n  if (slug === 'signer' || slug.startsWith('signer-')) {\n    throw new Error(\n      `Invalid server name ${JSON.stringify(slug)}: \"signer\" and \"signer-*\" are reserved — ` +\n        \"they would collide with another pair's haven-signer-* entry.\",\n    )\n  }\n}\n\nexport function serverNamesFor(slug?: string): ServerNames {\n  if (slug === undefined) {\n    return {\n      hosted: 'haven',\n      signer: 'haven-signer',\n      // Historical Codex table names — every wired Codex host has these.\n      codexHosted: 'haven',\n      codexSigner: 'haven_signer',\n      hermesEnvKey: 'MCP_HAVEN_API_KEY',\n    }\n  }\n  assertValidServerSlug(slug)\n  return {\n    hosted: `haven-${slug}`,\n    signer: `haven-signer-${slug}`,\n    // Hyphens are valid TOML bare keys, so named Codex tables match the\n    // JSON/YAML names instead of inheriting the legacy underscore.\n    codexHosted: `haven-${slug}`,\n    codexSigner: `haven-signer-${slug}`,\n    hermesEnvKey: `MCP_HAVEN_${slug.toUpperCase().replace(/-/g, '_')}_API_KEY`,\n  }\n}\n","import { MCP_VERSION, registeredToolNames } from '@haven_ai/mcp'\nimport { toolSchemas as signerToolSchemas } from '@haven_ai/signer'\nimport { HAVEN_MINIMUM_NODE_VERSION } from '@haven_ai/sdk'\n\n// The required-tools list is derived from `@haven_ai/mcp`'s canonical\n// `registeredToolNames()` rather than maintained as a literal here. An earlier\n// hand-maintained list drifted out of sync with the MCP package (it advertised\n// tools the local MCP no longer exposed, and missed `haven_pay_x402` when it\n// landed), which broke the consent screen and the post-setup probe. Sourcing\n// from the MCP package directly is now the only way new tools can ship.\nexport const MCP_RUNTIME_MANIFEST = {\n  mcpPackage: '@haven_ai/mcp',\n  mcpVersion: MCP_VERSION,\n  sdkPackage: '@haven_ai/sdk',\n  sdkVersion: '0.10.0-alpha.0',\n  signerPackage: '@haven_ai/signer',\n  signerVersion: '0.10.0-alpha.0',\n  // Sourced from the SDK, never a literal (#1161). This field read '20.0.0'\n  // while every package's `engines` said `>=24` and the docs said `>=24.0.0`,\n  // so the guard that was supposed to enforce the floor waved Node v23 through\n  // — including on the `--local` path where it does run. A hand-maintained\n  // second copy of a number is a drift waiting to happen; a guard test pins\n  // this against `package.json`'s `engines.node`.\n  minimumNodeVersion: HAVEN_MINIMUM_NODE_VERSION,\n  supportedClients: ['codex-cli', 'codex-desktop', 'claude-code'] as const,\n  requiredTools: registeredToolNames() as readonly string[],\n  /**\n   * The signer MCP's tool surface, DERIVED from the pinned @haven_ai/signer\n   * package (#1587) — same anti-drift rule as `requiredTools` above: a\n   * literal list here would rot the first time the signer gains a tool.\n   * The handshake probe requires all of them.\n   */\n  requiredSignerTools: Object.keys(signerToolSchemas) as readonly string[],\n} as const\n\nexport function mcpPackageSpec(): string {\n  return `${MCP_RUNTIME_MANIFEST.mcpPackage}@${MCP_RUNTIME_MANIFEST.mcpVersion}`\n}\n\nexport function sdkPackageSpec(): string {\n  return `${MCP_RUNTIME_MANIFEST.sdkPackage}@${MCP_RUNTIME_MANIFEST.sdkVersion}`\n}\n\nexport function signerPackageSpec(): string {\n  return `${MCP_RUNTIME_MANIFEST.signerPackage}@${MCP_RUNTIME_MANIFEST.signerVersion}`\n}\n","/**\n * Local runtime-spec override (#2424, slice 4 of epic #2420).\n *\n * `prepareSignerRuntime` and `prepareLocalMcpRuntime` install the connector's\n * PINNED siblings — `@haven_ai/signer@<pin>`, `@haven_ai/sdk@<pin>`,\n * `@haven_ai/mcp@<pin>` from `runtime-manifest.ts` — into a version-named\n * directory under `~/.haven`. That is right for every user and wrong for the\n * one developer iterating on the signer or SDK, who until now had to publish\n * to find out whether a change works end to end.\n *\n * Three environment variables let that developer name a different spec:\n *\n *   HAVEN_SIGNER_SPEC   what `npm install` gets instead of `@haven_ai/signer@<pin>`\n *   HAVEN_SDK_SPEC      … instead of `@haven_ai/sdk@<pin>`\n *   HAVEN_MCP_SPEC      … instead of `@haven_ai/mcp@<pin>` (the `--local` topology)\n *\n * A value is anything `npm install` accepts as a package spec whose name is\n * fixed by the variable: `file:/abs/path/to/packages/signer`, a `.tgz` from\n * `npm pack`, or an explicit version such as `@haven_ai/signer@0.0.0-dev.…`.\n *\n * ## Why environment variables and not a `--runtime-spec` flag\n *\n * - The install runs from THREE entry points — `--setup`, `--doctor --repair`\n *   and `--rekey-finish` — and every one of them has to honour the same\n *   override or the developer's re-key silently reinstalls the registry build.\n *   One env read inside the two `prepare*Runtime` functions covers all three;\n *   a flag would have to be plumbed through each argv parser and each result\n *   type separately, and the first one forgotten is a hole.\n * - The connector command is minted by the dashboard and pasted verbatim, often by\n *   an agent. An override that lived in argv would have to be spliced into a\n *   command the developer did not write; an env var sits beside it.\n * - It is out of band by construction: an agent following the printed command\n *   cannot pass it by accident, and it never appears in the copy-pasted line.\n * - It matches the vocabulary the backend already uses for the same axis\n *   (`HAVEN_CONNECTOR_CHANNEL`, #2422/#2423).\n *\n * ## What an active override changes, and what it never changes\n *\n * - The runtime directory is keyed by a short hash of the RESOLVED specs\n *   (`override-<hash>`) instead of the manifest version, so an override can\n *   never poison the pinned directory the normal path reuses.\n * - An override install is never reused from an earlier run: a rebuilt local\n *   package must not be shadowed by a cache hit, and `npm install` of an\n *   already-satisfied spec is cheap.\n * - The override is printed loudly in setup output, recorded in the sidecar,\n *   written as a comment into the wrapper the agent client launches, and\n *   reported by `--doctor` as a failing check.\n * - The post-setup handshake probe still requires every tool in\n *   `requiredTools` / `requiredSignerTools`, so a local build that dropped a\n *   tool fails setup exactly like a bad registry version would.\n * - No variable set → nothing here runs. `resolveRuntimeSpecOverride` returns\n *   `undefined`, the callers fall through to the manifest specs, and the\n *   install args, directory, sidecar and wrapper are byte-for-byte what they\n *   were before this module existed. `signer-runtime.test.ts` pins that.\n *\n * ## Validation\n *\n * A set-but-malformed value is refused BEFORE `npm` is invoked, naming the\n * variable: empty or whitespace-only, containing whitespace or a control\n * character, or containing a shell metacharacter. The install runs through\n * `execFile` (no shell), so a metacharacter could not inject anything — the\n * refusal is because such a value is almost never a spec npm would accept, and\n * when it is not, the failure would otherwise surface minutes later as an npm\n * error that does not name the variable. The one legitimate casualty is a\n * `file:` path whose segments contain `*`, `[`, `]`, `{` or `}` — legal in a\n * filesystem name, refused here on purpose: the check fails closed, the\n * message names the variable, and a developer can rename the checkout.\n */\n\nimport { createHash } from 'node:crypto'\n\nexport const RUNTIME_SPEC_ENV = {\n  signer: 'HAVEN_SIGNER_SPEC',\n  sdk: 'HAVEN_SDK_SPEC',\n  mcp: 'HAVEN_MCP_SPEC',\n} as const\n\nexport type RuntimeSpecPackage = keyof typeof RUNTIME_SPEC_ENV\n\n/** Every override that is set — absent keys mean \"the pinned manifest spec\". */\nexport type RuntimeSpecOverride = Partial<Record<RuntimeSpecPackage, string>>\n\n/**\n * Characters that can never appear in a spec `npm install` accepts and that,\n * in a shell, would mean something else. Whitespace and control characters\n * are checked separately so the message can say which.\n */\nconst SHELL_METACHARACTERS = /[;&|<>$`'\"()!#*?[\\]{}\\\\]/\n\nexport class RuntimeSpecOverrideError extends Error {\n  readonly code = 'runtime_spec_override_invalid'\n  readonly variable: string\n\n  constructor(variable: string, reason: string) {\n    super(`${variable} is set but not usable as an npm package spec: ${reason}. Unset it, or set it to a spec npm install accepts (file:/abs/path, a .tgz, or @haven_ai/<pkg>@<version>).`)\n    this.name = 'RuntimeSpecOverrideError'\n    this.variable = variable\n  }\n}\n\n/**\n * Read the override from `env`. Returns `undefined` when no variable is set —\n * the production case, and the only case in which callers must behave exactly\n * as before. Throws `RuntimeSpecOverrideError` on a set-but-malformed value.\n */\nexport function resolveRuntimeSpecOverride(env: NodeJS.ProcessEnv): RuntimeSpecOverride | undefined {\n  const override: RuntimeSpecOverride = {}\n  for (const pkg of Object.keys(RUNTIME_SPEC_ENV) as RuntimeSpecPackage[]) {\n    const variable = RUNTIME_SPEC_ENV[pkg]\n    const raw = env[variable]\n    if (raw === undefined) continue\n    override[pkg] = validateSpec(variable, raw)\n  }\n  return Object.keys(override).length > 0 ? override : undefined\n}\n\nfunction validateSpec(variable: string, raw: string): string {\n  if (raw.length === 0 || raw.trim().length === 0) {\n    throw new RuntimeSpecOverrideError(variable, 'it is empty')\n  }\n  if (/\\s/.test(raw)) {\n    throw new RuntimeSpecOverrideError(variable, 'it contains whitespace')\n  }\n  // eslint-disable-next-line no-control-regex\n  if (/[\\u0000-\\u001f\\u007f]/.test(raw)) {\n    throw new RuntimeSpecOverrideError(variable, 'it contains a control character')\n  }\n  const meta = SHELL_METACHARACTERS.exec(raw)\n  if (meta) {\n    throw new RuntimeSpecOverrideError(variable, `it contains the shell metacharacter ${JSON.stringify(meta[0])}`)\n  }\n  return raw\n}\n\n/**\n * The directory key for an override install: `override-` plus the first 12\n * hex characters of a SHA-256 over the resolved specs, in a fixed order. Two\n * setups with the same resolved specs share a directory; any difference in\n * any spec — including the NON-overridden sibling's pinned version — gets a\n * fresh one, so a pinned-sdk bump never reuses a directory built against the\n * previous pin.\n */\nexport function runtimeSpecOverrideDirectoryKey(resolvedSpecs: readonly string[]): string {\n  const digest = createHash('sha256').update(resolvedSpecs.join('\\n')).digest('hex')\n  return `override-${digest.slice(0, 12)}`\n}\n\n/** True when `override` touches any of `packages`. */\nexport function overrideApplies(\n  override: RuntimeSpecOverride | undefined,\n  packages: readonly RuntimeSpecPackage[],\n): override is RuntimeSpecOverride {\n  return override !== undefined && packages.some((pkg) => override[pkg] !== undefined)\n}\n\n/**\n * The record written into the runtime sidecar and read back by `--doctor`.\n * `specs` holds only the overridden packages; `resolved_specs` holds every\n * spec the install actually ran with, overridden or pinned, in the order the\n * directory key hashes them.\n */\nexport interface RuntimeSpecOverrideRecord {\n  specs: RuntimeSpecOverride\n  resolved_specs: string[]\n  directory_key: string\n}\n\n/**\n * The lines setup prints when an override is active. Deliberately loud and\n * deliberately first: a developer who forgot the variable is set in their\n * shell should not have to read the sidecar to learn why the signer differs.\n */\nexport function runtimeSpecOverrideNotice(\n  runtimeLabel: string,\n  override: RuntimeSpecOverride,\n  pinned: Partial<Record<RuntimeSpecPackage, string>>,\n  runtimeDirectory: string,\n): string[] {\n  const lines = [`RUNTIME SPEC OVERRIDE ACTIVE for the local Haven ${runtimeLabel} — this is NOT the pinned manifest.`]\n  for (const pkg of Object.keys(RUNTIME_SPEC_ENV) as RuntimeSpecPackage[]) {\n    const spec = override[pkg]\n    if (spec === undefined) continue\n    const pin = pinned[pkg]\n    lines.push(`  ${RUNTIME_SPEC_ENV[pkg]}=${spec}${pin ? ` (instead of ${pin})` : ''}`)\n  }\n  lines.push(`  Installing into ${runtimeDirectory} — the pinned runtime directory is untouched.`)\n  lines.push('  Unset the variable(s) and re-run to return to the pinned manifest.')\n  return lines\n}\n\n/** One-line summary for wrapper comments and doctor output. */\nexport function describeRuntimeSpecOverride(override: RuntimeSpecOverride): string {\n  return (Object.keys(RUNTIME_SPEC_ENV) as RuntimeSpecPackage[])\n    .filter((pkg) => override[pkg] !== undefined)\n    .map((pkg) => `${RUNTIME_SPEC_ENV[pkg]}=${override[pkg]}`)\n    .join(' ')\n}\n","import { execFile } from 'node:child_process'\nimport { access, chmod, mkdir, readFile, writeFile } from 'node:fs/promises'\nimport { homedir } from 'node:os'\nimport { dirname, join, resolve } from 'node:path'\nimport { promisify } from 'node:util'\nimport { MCP_RUNTIME_MANIFEST, sdkPackageSpec, signerPackageSpec } from './runtime-manifest.js'\nimport {\n  describeRuntimeSpecOverride,\n  overrideApplies,\n  resolveRuntimeSpecOverride,\n  runtimeSpecOverrideDirectoryKey,\n  runtimeSpecOverrideNotice,\n  type RuntimeSpecOverride,\n  type RuntimeSpecOverrideRecord,\n} from './runtime-spec-override.js'\n\nconst execFileAsync = promisify(execFile)\n\nexport interface PrepareSignerRuntimeInput {\n  credentialDirectory: string\n  signerPath: string\n  homeDir?: string\n  /** #1696: wiring slug, recorded in the sidecar for per-agent inventory (#1697). */\n  serverName?: string\n}\n\nexport interface PreparedSignerRuntime {\n  /** Absolute command to register as the signer MCP `command`. */\n  command: string\n  /** Args to register alongside `command` (credentials are baked into the wrapper). */\n  args: string[]\n  wrapperPath: string\n  runtimeDirectory: string\n  npmCacheDirectory: string\n  cliPath: string\n  messages: string[]\n  /** #2424: present only when the install ran under a runtime-spec override. */\n  runtimeSpecOverride?: RuntimeSpecOverrideRecord\n}\n\nexport interface SignerRuntimeDeps {\n  runCommand?: (command: string, args: string[]) => Promise<void>\n  /** Heartbeats during the (possibly minutes-long) npm install (#1586). */\n  onProgress?: (message: string) => void\n  /**\n   * #2424: where `HAVEN_SIGNER_SPEC` / `HAVEN_SDK_SPEC` are read from.\n   * Defaults to `process.env`; injected so tests can prove both that an\n   * override is honoured and that its absence changes nothing.\n   */\n  env?: NodeJS.ProcessEnv\n}\n\n/**\n * Honest budget for a COLD-cache install over a slow link (#1586). The old\n * 120s budget was exactly what broke the 2026-08-18 Codex Desktop setup: a\n * 6+ minute cold install was killed at 2 minutes, the failure fell back to\n * npx silently, and the resulting config structurally could not start.\n */\nexport const SIGNER_INSTALL_TIMEOUT_MS = 600_000\n\n/** How often the console hears from a long install instead of going silent. */\nexport const SIGNER_INSTALL_HEARTBEAT_MS = 15_000\n\n/**\n * Pre-install the edge signer into a version-pinned, connector-managed\n * directory and write a stable wrapper that launches it with an absolute Node\n * path. The signer MCP is then registered as `command: <wrapper>` instead of a\n * runtime `npx -y @haven_ai/signer@…` invocation.\n *\n * Why: launching the signer via bare `npx` at every MCP spawn made it depend on\n * the PATH/environment the agent runtime hands the stdio subprocess, which is\n * not the user's interactive shell — the failure mode that left `haven-signer`\n * stuck at \"Failed to connect\" while the hosted HTTP server connected fine. The\n * local MCP topology already avoids this with the same pre-install + wrapper\n * pattern (see prepareLocalMcpRuntime); this brings the default hosted+signer\n * topology to parity. Version stays pinned (no unpinned `npm i -g`), and the\n * wrapper lives under ~/.haven so the reset flow already cleans it up.\n */\nexport async function prepareSignerRuntime(\n  input: PrepareSignerRuntimeInput,\n  deps: SignerRuntimeDeps = {},\n): Promise<PreparedSignerRuntime> {\n  const homeDir = input.homeDir ?? homedir()\n  // #2424: resolved BEFORE any directory is created or npm is invoked, so a\n  // malformed variable is refused with nothing on disk to clean up.\n  const override = resolveSignerRuntimeOverride(deps.env ?? process.env)\n  const signerSpec = override?.signer ?? signerPackageSpec()\n  const sdkSpec = override?.sdk ?? sdkPackageSpec()\n  const resolvedSpecs = [signerSpec, sdkSpec]\n  const overrideRecord: RuntimeSpecOverrideRecord | undefined = override\n    ? { specs: override, resolved_specs: resolvedSpecs, directory_key: runtimeSpecOverrideDirectoryKey(resolvedSpecs) }\n    : undefined\n  const runtimeDirectory = resolve(\n    homeDir,\n    '.haven',\n    'signer-runtime',\n    overrideRecord ? overrideRecord.directory_key : MCP_RUNTIME_MANIFEST.signerVersion,\n  )\n  const npmCacheDirectory = resolve(homeDir, '.haven', 'npm-cache')\n  const cliPath = join(runtimeDirectory, 'node_modules', '@haven_ai', 'signer', 'dist', 'cli.js')\n  const messages: string[] = []\n\n  if (override) {\n    messages.push(...runtimeSpecOverrideNotice(\n      'signer runtime',\n      override,\n      { signer: signerPackageSpec(), sdk: sdkPackageSpec() },\n      runtimeDirectory,\n    ))\n  }\n\n  await mkdir(runtimeDirectory, { recursive: true, mode: 0o700 })\n  await chmod(runtimeDirectory, 0o700).catch(() => undefined)\n  await mkdir(npmCacheDirectory, { recursive: true, mode: 0o700 })\n  await chmod(npmCacheDirectory, 0o700).catch(() => undefined)\n\n  if (override) {\n    // Never reused: a rebuilt `file:` package must not be shadowed by a\n    // version check that cannot tell two local builds apart.\n    await installRuntimePackages(runtimeDirectory, npmCacheDirectory, resolvedSpecs, deps)\n    messages.push(`Installed local Haven signer runtime from override (${resolvedSpecs.join(' ')}).`)\n  } else if (await installedRuntimeMatches(runtimeDirectory, cliPath)) {\n    messages.push(`Using existing local Haven signer runtime ${signerPackageSpec()}.`)\n  } else {\n    await installRuntimePackages(runtimeDirectory, npmCacheDirectory, resolvedSpecs, deps)\n    messages.push(`Installed local Haven signer runtime ${signerPackageSpec()}.`)\n  }\n\n  await assertFileExists(cliPath, 'local Haven signer CLI')\n  // Under an override the manifest is not the truth about what is installed;\n  // the sidecar records what npm actually laid down so `--doctor` can compare\n  // the directory against the run that wrote it.\n  const installedVersions = override ? await readInstalledVersions(runtimeDirectory) : undefined\n\n  // .mjs so the wrapper is unambiguously ESM when the runtime exec's it via the\n  // shebang — Node < 20.10 has no automatic module detection, and there is no\n  // package.json with \"type\":\"module\" under ~/.haven to disambiguate otherwise.\n  const wrapperPath = join(input.credentialDirectory, 'bin', 'haven-signer.mjs')\n  await writeWrapper({\n    wrapperPath,\n    cliPath,\n    signerPath: input.signerPath,\n    overrideComment: override ? describeRuntimeSpecOverride(override) : undefined,\n  })\n\n  await writeRuntimeSidecar({\n    path: join(input.credentialDirectory, 'signer-runtime.json'),\n    wrapperPath,\n    runtimeDirectory,\n    npmCacheDirectory,\n    cliPath,\n    serverName: input.serverName,\n    override: overrideRecord,\n    installedVersions,\n  })\n\n  messages.push(`Prepared stable local Haven signer wrapper: ${wrapperPath}`)\n\n  return {\n    command: wrapperPath,\n    args: [],\n    wrapperPath,\n    runtimeDirectory,\n    npmCacheDirectory,\n    cliPath,\n    messages,\n    ...(overrideRecord ? { runtimeSpecOverride: overrideRecord } : {}),\n  }\n}\n\n/**\n * The signer runtime's slice of the override: `signer` and `sdk`. A lone\n * `HAVEN_MCP_SPEC` belongs to the `--local` MCP runtime and must not turn this\n * install into an override one.\n */\nfunction resolveSignerRuntimeOverride(env: NodeJS.ProcessEnv): RuntimeSpecOverride | undefined {\n  const override = resolveRuntimeSpecOverride(env)\n  if (!overrideApplies(override, ['signer', 'sdk'])) return undefined\n  const { signer, sdk } = override\n  return { ...(signer !== undefined ? { signer } : {}), ...(sdk !== undefined ? { sdk } : {}) }\n}\n\nasync function installRuntimePackages(\n  runtimeDirectory: string,\n  npmCacheDirectory: string,\n  packageSpecs: readonly string[],\n  deps: SignerRuntimeDeps,\n): Promise<void> {\n  const { runCommand, onProgress } = deps\n  // Fast path: install against the user's default npm cache with\n  // `--prefer-offline`. `npx @haven_ai/connect` just downloaded the signer + sdk\n  // tarballs (plus their closure) into that cache moments earlier, so this\n  // resolves from disk instead of re-fetching over the network — the single\n  // biggest avoidable cost in cold setup.\n  const baseArgs = [\n    'install',\n    '--prefix',\n    runtimeDirectory,\n    '--no-audit',\n    '--no-fund',\n    '--omit=dev',\n    '--prefer-offline',\n    ...packageSpecs,\n  ]\n  const run = async (args: string[]): Promise<void> => {\n    // Heartbeat while npm works: a cold install can legitimately take\n    // minutes, and a silent console reads as a hang (#1586).\n    const startedAt = Date.now()\n    const heartbeat = setInterval(() => {\n      const seconds = Math.round((Date.now() - startedAt) / 1000)\n      onProgress?.(`Still installing the local Haven signer runtime… (${seconds}s — a cold cache can take several minutes)`)\n    }, SIGNER_INSTALL_HEARTBEAT_MS)\n    heartbeat.unref?.()\n    try {\n      if (runCommand) await runCommand('npm', args)\n      else await execFileAsync('npm', args, { timeout: SIGNER_INSTALL_TIMEOUT_MS, maxBuffer: 1024 * 1024 })\n    } finally {\n      clearInterval(heartbeat)\n    }\n  }\n\n  try {\n    await run(baseArgs)\n  } catch {\n    // Fallback: the default `~/.npm` can be corrupted or root-owned (a real,\n    // documented failure mode — see docs/operations/mcp-runtime-compatibility.md).\n    // Retry against the isolated Haven-owned cache so a broken global cache can't\n    // break agent setup. This path may hit the network; that is the acceptable\n    // cost of recovering from an unusable default cache.\n    try {\n      await run([...baseArgs, '--cache', npmCacheDirectory])\n    } catch (err) {\n      throw new Error(\n        `Could not install local Haven signer runtime ${packageSpecs.join(' ')}: ${err instanceof Error ? err.message : String(err)}`,\n      )\n    }\n  }\n}\n\nexport async function installedRuntimeMatches(runtimeDirectory: string, cliPath: string): Promise<boolean> {\n  return installedRuntimeMatchesVersions(runtimeDirectory, cliPath, {\n    signerVersion: MCP_RUNTIME_MANIFEST.signerVersion,\n    sdkVersion: MCP_RUNTIME_MANIFEST.sdkVersion,\n  })\n}\n\n/**\n * #2424: the same check against an explicit pair of versions. `--doctor`\n * uses it for an override install, where the reference is the sidecar's\n * record of what npm laid down rather than the manifest pin.\n */\nexport async function installedRuntimeMatchesVersions(\n  runtimeDirectory: string,\n  cliPath: string,\n  expected: { signerVersion: string; sdkVersion: string },\n): Promise<boolean> {\n  try {\n    await assertFileExists(cliPath, 'local Haven signer CLI')\n    const installed = await readInstalledVersions(runtimeDirectory)\n    return installed.signerVersion === expected.signerVersion && installed.sdkVersion === expected.sdkVersion\n  } catch {\n    return false\n  }\n}\n\nasync function readInstalledVersions(runtimeDirectory: string): Promise<{ signerVersion: string; sdkVersion: string }> {\n  const [signerPackage, sdkPackage] = await Promise.all([\n    readPackageJson(join(runtimeDirectory, 'node_modules', '@haven_ai', 'signer', 'package.json')),\n    readPackageJson(join(runtimeDirectory, 'node_modules', '@haven_ai', 'sdk', 'package.json')),\n  ])\n  return { signerVersion: signerPackage.version ?? '', sdkVersion: sdkPackage.version ?? '' }\n}\n\nasync function readPackageJson(path: string): Promise<{ version?: string }> {\n  return JSON.parse(await readFile(path, 'utf8')) as { version?: string }\n}\n\nasync function writeWrapper(input: {\n  wrapperPath: string\n  cliPath: string\n  signerPath: string\n  /** #2424: present only under an override; the wrapper says so to whoever opens it. */\n  overrideComment?: string\n}): Promise<void> {\n  await mkdir(dirname(input.wrapperPath), { recursive: true, mode: 0o700 })\n  await chmod(dirname(input.wrapperPath), 0o700).catch(() => undefined)\n  const source = [\n    '#!/usr/bin/env node',\n    ...(input.overrideComment\n      ? [`// HAVEN RUNTIME SPEC OVERRIDE (#2424): ${input.overrideComment} — this wrapper launches a NON-pinned signer build.`]\n      : []),\n    \"import { spawn } from 'node:child_process'\",\n    '',\n    `const cliPath = ${JSON.stringify(input.cliPath)}`,\n    `const signerPath = ${JSON.stringify(input.signerPath)}`,\n    '',\n    \"const child = spawn(process.execPath, [cliPath, '--credentials', signerPath, ...process.argv.slice(2)], {\",\n    \"  stdio: 'inherit',\",\n    '})',\n    '',\n    \"child.on('exit', (code, signal) => {\",\n    '  if (signal) process.kill(process.pid, signal)',\n    '  else process.exit(code ?? 1)',\n    '})',\n    '',\n  ].join('\\n')\n  await writeFile(input.wrapperPath, source, { mode: 0o700 })\n  await chmod(input.wrapperPath, 0o700).catch(() => undefined)\n}\n\n/** The sidecar `prepareSignerRuntime` writes next to the credentials (#1589). */\nexport interface SignerRuntimeSidecar {\n  /** #1696: present when this credential dir belongs to a NAMED pair. */\n  server_name?: string\n  signer_package: string\n  signer_version: string\n  sdk_package: string\n  sdk_version: string\n  wrapper_path: string\n  runtime_directory: string\n  npm_cache_directory: string\n  cli_path: string\n  /**\n   * #2424: present ONLY when the install ran under `HAVEN_SIGNER_SPEC` /\n   * `HAVEN_SDK_SPEC`. Then `signer_version` / `sdk_version` above are what\n   * npm actually installed (read back from the package.json files), not the\n   * manifest pins, and `--doctor` reports the override as a finding.\n   */\n  runtime_spec_override?: RuntimeSpecOverrideRecord\n}\n\nexport async function readRuntimeSidecar(credentialDirectory: string): Promise<SignerRuntimeSidecar | null> {\n  try {\n    return JSON.parse(\n      await readFile(join(credentialDirectory, 'signer-runtime.json'), 'utf8'),\n    ) as SignerRuntimeSidecar\n  } catch {\n    return null\n  }\n}\n\nasync function writeRuntimeSidecar(input: {\n  path: string\n  wrapperPath: string\n  runtimeDirectory: string\n  npmCacheDirectory: string\n  cliPath: string\n  serverName?: string\n  override?: RuntimeSpecOverrideRecord\n  installedVersions?: { signerVersion: string; sdkVersion: string }\n}): Promise<void> {\n  const value = {\n    ...(input.serverName ? { server_name: input.serverName } : {}),\n    signer_package: MCP_RUNTIME_MANIFEST.signerPackage,\n    signer_version: input.installedVersions?.signerVersion ?? MCP_RUNTIME_MANIFEST.signerVersion,\n    sdk_package: MCP_RUNTIME_MANIFEST.sdkPackage,\n    sdk_version: input.installedVersions?.sdkVersion ?? MCP_RUNTIME_MANIFEST.sdkVersion,\n    wrapper_path: input.wrapperPath,\n    runtime_directory: input.runtimeDirectory,\n    npm_cache_directory: input.npmCacheDirectory,\n    cli_path: input.cliPath,\n    ...(input.override ? { runtime_spec_override: input.override } : {}),\n  }\n  await writeFile(input.path, `${JSON.stringify(value, null, 2)}\\n`, { mode: 0o600 })\n  await chmod(input.path, 0o600).catch(() => undefined)\n}\n\nasync function assertFileExists(path: string, label: string): Promise<void> {\n  try {\n    await access(path)\n  } catch {\n    throw new Error(`Missing ${label}: ${path}`)\n  }\n}\n","/**\n * The connector's machine-readable failure vocabulary (#1719).\n *\n * Before this, a refusal was a bare `throw new Error(...)` and the automation\n * contract recovered a code by regex-matching the message in\n * `failedConnectOutcome`. That works only for as long as nobody rewords a\n * sentence, and it gives the caller nothing to branch on that the wording did\n * not accidentally provide. Every refusal this module fronts carries:\n *\n * - `code` — stable, snake_case, safe to switch on;\n * - `nextAction` — the one thing to do next, in the same snake_case shape the\n *   install-status contract already uses for `next_action`;\n * - `message` — human/agent prose, still the thing printed to a terminal.\n *\n * Codes are additive and never renamed: a consumer pinned to an older\n * connector must keep recognising the ones it already knows.\n */\nexport interface ConnectErrorDetails {\n  /**\n   * The `--runtime` values a retry may use, when the refusal is about runtime\n   * selection (#2091). The values lived only in `message` prose, which the\n   * `--json` contract discards entirely — while the backend's setup prompt\n   * instructs an agent to retry only with \"one of the values that refusal\n   * lists\". Carrying them structurally is what makes that retry reachable\n   * from automation.\n   */\n  allowedRuntimes?: readonly string[]\n  /**\n   * What the #1719 installed-client scan found on this machine (#2174), when\n   * the refusal is `runtime_undetermined`. `installedClients` is ordered\n   * likeliest-first; `suggestedRuntime` appears only when one candidate is\n   * unambiguously top.\n   *\n   * A HINT, never a decision. The scan populates choices and never selects —\n   * carrying it here does not let the connector proceed on it, and the retry\n   * stays the agent's explicit `--runtime <name>`.\n   */\n  installedClients?: readonly string[]\n  suggestedRuntime?: string\n  /**\n   * #2551: the agents a bare-pair setup would displace, when the refusal is\n   * `wiring_collision`. Carried structurally for the same reason as\n   * `allowedRuntimes`: a `--json` caller discards prose, and the ids are what\n   * the human it relays to needs in order to decide.\n   */\n  supersededAgentIds?: readonly string[]\n  /**\n   * #2551: a valid, collision-checked `--name` the run could be re-issued\n   * with to install alongside. A proposal the human may take, never a\n   * selection the connector acts on.\n   */\n  suggestedServerName?: string\n}\n\nexport class ConnectError extends Error {\n  readonly code: string\n  readonly nextAction: string\n  readonly details: ConnectErrorDetails\n\n  constructor(code: string, message: string, nextAction: string, details: ConnectErrorDetails = {}) {\n    super(message)\n    this.name = 'ConnectError'\n    this.code = code\n    this.nextAction = nextAction\n    this.details = details\n  }\n}\n\nexport function isConnectError(err: unknown): err is ConnectError {\n  return err instanceof ConnectError\n}\n","/**\n * Agent-directory tombstones (#1681) — for the RECREATION case, where an old\n * directory is abandoned. (#1700's --rekey deliberately writes no tombstone:\n * it rewrites credentials in place at a stable path, so no dead path exists —\n * owner decision on epic #1694, 2026-08-21.)\n *\n * A long-lived MCP host loads its wiring snapshot once, at process start.\n * When an agent is recreated and its old directory is later removed, every\n * such host keeps spawning the OLD wrapper path — and the spawn fails with a\n * FileNotFoundError the host masks as \"Connection closed\", parked and\n * re-probed every five minutes, indefinitely. The field report behind this\n * counted 5,356 occurrences of one dead UUID, and TWO different long-lived\n * processes each parked on a DIFFERENT dead UUID, because each holds the\n * snapshot from its own start time.\n *\n * A tombstone replaces the wrapper with a script that tells the truth: which\n * agent this was, when and why it was retired, and that THIS host must be\n * restarted. The park loop does not disappear — nothing local can reach into\n * a running host's memory — but every five-minute probe now logs the\n * diagnosis instead of a masked symptom, in exactly the stderr log where the\n * original investigation had to dig it out by hand.\n *\n * What a tombstone deliberately does NOT do:\n * - It never touches key material. identity.json / signer.json are left\n *   exactly as found — connect never revokes and never deletes credentials\n *   (#1688's standing rule). A retirement flow that wants the keys gone\n *   deletes them itself, and the tombstone survives to keep the path honest.\n * - It does not try to speak MCP. A well-formed JSON-RPC error needs the\n *   request id, which means reading stdin and racing client timeouts; a\n *   fast, loud stderr exit lands in the host's MCP stderr log — the place\n *   the #1681 forensics actually looked — on every probe, with no protocol\n *   to get subtly wrong.\n */\n\nimport { chmod, mkdir, readFile, readdir, stat, writeFile } from 'node:fs/promises'\nimport { connectorRerunCommand } from '@haven_ai/sdk'\nimport { homedir } from 'node:os'\nimport { dirname, join, resolve } from 'node:path'\nimport { redactSecrets } from './redact.js'\nimport { ConnectError } from './connect-error.js'\n\nexport const TOMBSTONE_FILENAME = 'TOMBSTONE.json'\n\nexport interface TombstoneInfo {\n  agent_id: string\n  retired_at: string\n  reason: string\n  replaced_by?: string\n}\n\nexport interface WriteTombstoneInput {\n  /** The agent credential directory being retired. */\n  directory: string\n  agentId: string\n  /** Why the directory was retired — rendered verbatim in the diagnosis. */\n  reason: string\n  /** The agent that superseded this one, when there is one. */\n  replacedBy?: string\n  /** Injectable for tests; defaults to now. */\n  retiredAt?: string\n  /** Root for the SURVIVING mirror record; defaults to ~/.haven/tombstones. */\n  tombstonesDir?: string\n}\n\n/**\n * Where tombstone records survive OUTSIDE the retired agent directory.\n *\n * A tombstone written only inside the per-agent dir dies the moment that dir\n * is deleted — and the whole point of a tombstone is to keep speaking for an\n * OLD, possibly already-removed path. The mirror is keyed by agent id (the\n * durable identity; dirs may be uuid- or slug-named) so `--doctor` and humans\n * can always find WHO was retired and WHY even after `~/.haven/agents/<id>`\n * is long gone. Same redaction as the in-place record; no key material.\n * (#1681 review follow-up: the tombstone must live outside the per-agent tree\n * to survive a reset.)\n */\nexport function defaultTombstonesDir(baseDir?: string): string {\n  return join(baseDir ?? join(homedir(), '.haven'), 'tombstones')\n}\n\n/** The ledger directory name used INSIDE a custom credential root. */\nexport const ROOT_TOMBSTONES_DIRNAME = '.tombstones'\n\n/**\n * The ledger for a credential ROOT — the directory that holds the agent\n * directories (`--credentials-dir`, default `~/.haven/agents`). The default\n * root keeps `~/.haven/tombstones`, unchanged. Any other root keeps its ledger\n * INSIDE itself, at `<root>/.tombstones` — never beside it: the parent of a\n * root the user named may be `/`, their home, or read-only, and the mirror\n * write is fatal to a retirement (#3251 review). Every enumerator over a root\n * gates on files inside an agent directory (`identity.json`, a sidecar, a\n * parked key), so the ledger directory is never mistaken for an agent.\n *\n * `homeDir` names the home whose `.haven/agents` is the default root — the\n * doctor passes its own, never the ambient one.\n */\nexport function tombstonesDirForCredentialRoot(credentialRoot?: string, homeDir: string = homedir()): string {\n  if (!credentialRoot) return defaultTombstonesDir(join(homeDir, '.haven'))\n  const root = resolve(credentialRoot)\n  if (root === resolve(homeDir, '.haven', 'agents')) return defaultTombstonesDir(join(homeDir, '.haven'))\n  return join(root, ROOT_TOMBSTONES_DIRNAME)\n}\n\n/** The ledger for an agent DIRECTORY: its parent is its credential root. */\nexport function tombstonesDirForAgentDirectory(directory: string, homeDir: string = homedir()): string {\n  return tombstonesDirForCredentialRoot(dirname(resolve(directory)), homeDir)\n}\n\nconst MIRROR_MODE = 0o600\n\n/**\n * Every tombstone record mirrored under the tombstones root — INCLUDING\n * retirees whose credential directory has since been deleted, which is the\n * case the in-place record cannot cover. Non-throwing: a missing or\n * unreadable record file is skipped, like every other enumeration path.\n */\nexport async function readTombstoneRecords(\n  tombstonesDir?: string,\n): Promise<Array<TombstoneInfo & { recordPath: string }>> {\n  const root = tombstonesDir ?? defaultTombstonesDir()\n  let entries: string[] = []\n  try {\n    entries = await readdir(root)\n  } catch {\n    return []\n  }\n  const records: Array<TombstoneInfo & { recordPath: string }> = []\n  for (const entry of entries) {\n    if (!entry.endsWith('.json')) continue\n    const recordPath = join(root, entry)\n    try {\n      const parsed = JSON.parse(await readFile(recordPath, 'utf8')) as TombstoneInfo\n      if (typeof parsed?.agent_id === 'string') {\n        records.push({ ...parsed, recordPath })\n      }\n    } catch {\n      // unreadable record — skip; the in-place copy (if any) still speaks\n    }\n  }\n  return records\n}\n\n/** The marker string hosts and humans can grep their MCP stderr logs for. */\nexport const TOMBSTONE_MARKER = 'HAVEN-TOMBSTONE'\n\nfunction tombstoneScript(info: TombstoneInfo): string {\n  const lines = [\n    `${TOMBSTONE_MARKER}: this Haven agent was retired.`,\n    '',\n    `  agent:      ${info.agent_id}`,\n    `  retired at: ${info.retired_at}`,\n    `  reason:     ${info.reason}`,\n    ...(info.replaced_by ? [`  replaced by: ${info.replaced_by}`] : []),\n    '',\n    'This process is running with a wiring snapshot that predates the',\n    'retirement — it loaded its MCP config at startup and has kept it since.',\n    'Restart THIS host to pick up the current wiring. If several long-lived',\n    'hosts are running (a gateway, a TUI worker, an editor), restart EVERY',\n    'one of them: each holds the snapshot from its own start time, so after',\n    'a chain of recreations each can be parked on a DIFFERENT old agent.',\n    '',\n    `Then verify with: ${connectorRerunCommand('--doctor --runtime <runtime>')}`,\n  ]\n  // Fully self-contained: no imports, no reads — a tombstone that could\n  // itself fail to start would recreate the exact masking it exists to end.\n  return [\n    '#!/usr/bin/env node',\n    `// ${TOMBSTONE_MARKER} — written by @haven_ai/connect (#1681). Safe to delete`,\n    '// once every long-lived MCP host on this machine has been restarted.',\n    `process.stderr.write(${JSON.stringify(lines.join('\\n') + '\\n')})`,\n    'process.exit(1)',\n    '',\n  ].join('\\n')\n}\n\n/**\n * Replace the directory's signer wrapper with a tombstone, record the\n * retirement in TOMBSTONE.json, and MIRROR the record under the tombstones\n * root so it survives the directory's later deletion. Key files are not\n * touched. Idempotent — a re-run overwrites the tombstone with the same\n * content shape.\n *\n * Returns the tombstone info plus the MIRROR path (`recordPath`), so callers\n * can point at the record that outlives the directory.\n *\n * The mirror is BEST-EFFORT (#3259). The in-place TOMBSTONE.json is the\n * authoritative record and is already on disk when the mirror is written, so\n * a mirror failure must not read as \"not retired\": it used to throw here,\n * and `--replace` then skipped the key teardown, leaving a directory that\n * looked retired and could still spend. A failed mirror returns\n * `recordPath: null` and `mirrorError`, and every caller reports it.\n */\nexport async function writeAgentTombstone(\n  input: WriteTombstoneInput,\n): Promise<WrittenTombstone> {\n  // The directory must already exist: a mistyped path would otherwise be\n  // silently created and reported as a successful retirement. (#1681 review)\n  const dirStat = await stat(input.directory).catch(() => null)\n  if (!dirStat?.isDirectory()) {\n    // A ConnectError rather than a bare Error (#2175): this is the refusal an\n    // automating caller actually hits, and the overwhelmingly likely cause is\n    // a path built from the AGENT ID when the directory is slug-named (#1696).\n    // A stable code lets that caller tell \"wrong path\" apart from every other\n    // reason a retirement did not happen.\n    throw new ConnectError(\n      'tombstone_directory_not_found',\n      `Not a directory: ${input.directory} — nothing to tombstone. ` +\n        'Agent directories are named by their wiring SLUG when the agent has one, and by the ' +\n        'agent id otherwise — so a path built from an agent id will not exist for a named agent. ' +\n        'List ~/.haven/agents (or read the directories from --doctor --json) and pass one of those.',\n      'retry_with_an_existing_agent_directory',\n    )\n  }\n  const info: TombstoneInfo = {\n    // reason / replaced_by are persisted to disk and re-emitted to the host's\n    // MCP stderr log on EVERY stale probe, potentially for months — redact\n    // like every other output path, at the write layer so any future caller\n    // inherits it. (#1681 review, finding 1)\n    agent_id: input.agentId,\n    retired_at: input.retiredAt ?? new Date().toISOString(),\n    reason: redactSecrets(input.reason),\n    ...(input.replacedBy ? { replaced_by: redactSecrets(input.replacedBy) } : {}),\n  }\n  const binDir = join(input.directory, 'bin')\n  await mkdir(binDir, { recursive: true })\n  const wrapperPath = join(binDir, 'haven-signer.mjs')\n  await writeFile(wrapperPath, tombstoneScript(info), 'utf8')\n  await chmod(wrapperPath, 0o755)\n  const record = JSON.stringify(info, null, 2) + '\\n'\n  await writeFile(join(input.directory, TOMBSTONE_FILENAME), record, 'utf8')\n  // Surviving mirror (#1681 follow-up): keyed by agent id, OUTSIDE the dir, so\n  // a retirement flow that then deletes the agent directory cannot silence\n  // the diagnosis. Same redaction; no key material. Collisions (same agent id\n  // tombstoned twice) overwrite — latest retirement wins, in-place records\n  // remain authoritative.\n  const root = input.tombstonesDir ?? defaultTombstonesDir()\n  const recordPath = join(root, `${info.agent_id}.json`)\n  try {\n    await mkdir(root, { recursive: true, mode: 0o700 })\n    await writeFile(recordPath, record, { mode: MIRROR_MODE })\n  } catch (err) {\n    // The errno CODE only — never the raw OS message, which carries local\n    // path detail and would reach `--json` stdout (#2175 discipline).\n    const code = (err as NodeJS.ErrnoException | null)?.code\n    return { ...info, recordPath: null, mirrorError: typeof code === 'string' && /^E[A-Z]+$/.test(code) ? code : 'mirror_write_failed' }\n  }\n  return { ...info, recordPath }\n}\n\n/**\n * A written tombstone. `recordPath` is the surviving mirror, or `null` when the\n * mirror could not be written — then `mirrorError` is the errno code (e.g.\n * `EACCES`, or `mirror_write_failed` when there is none), and the\n * retirement still stands on the in-place TOMBSTONE.json (#3259).\n */\nexport type WrittenTombstone = TombstoneInfo & { recordPath: string | null; mirrorError?: string }\n\n/** The tombstone record for a directory, or null when it is not tombstoned. */\nexport async function readAgentTombstone(directory: string): Promise<TombstoneInfo | null> {\n  try {\n    const parsed = JSON.parse(await readFile(join(directory, TOMBSTONE_FILENAME), 'utf8')) as TombstoneInfo\n    if (typeof parsed?.agent_id !== 'string') return null\n    return parsed\n  } catch {\n    return null\n  }\n}\n","import { access, chmod, mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'\nimport crypto from 'node:crypto'\nimport { basename } from 'node:path'\nimport { homedir } from 'node:os'\nimport { join, resolve } from 'node:path'\nimport { assertValidServerSlug } from './server-names.js'\nimport { readRuntimeSidecar } from './signer-runtime.js'\nimport { TOMBSTONE_FILENAME } from './tombstone.js'\n\nexport interface StoredCredentialPaths {\n  directory: string\n  identityPath: string\n  signerPath: string\n  /** Non-secret orientation file (identity + configured budget, no keys). */\n  agentPath: string\n}\n\nexport interface WriteCredentialInput {\n  baseDir?: string\n  agentId: string\n  /**\n   * #1696: wiring slug. Named agents live at ~/.haven/agents/<slug>/ (stable\n   * across a re-key by construction — the slug never rotates); unnamed keep\n   * the historical ~/.haven/agents/<agent-uuid>/. Both schemes coexist.\n   */\n  serverName?: string\n  apiKey: string\n  delegateKey: string\n  delegateAddress: string\n  /**\n   * The Haven account (smart account) address. Written to every credential\n   * file as `account_address` ONLY (#2908 — write the new name, never the\n   * old; the readers in `@haven_ai/signer` / `@haven_ai/mcp` fall back to the\n   * pre-#2908 `safe_address` permanently, so a file from either era loads).\n   */\n  accountAddress?: string\n  chainId?: number\n  network?: string\n  agentBudget?: Array<{\n    token_symbol: string\n    allowance_amount: string\n    reset_period_min: number\n  }>\n  apiUrl: string\n  hostedMcpUrl: string\n  x402BindingSigner?: string\n  warn?: (message: string) => void\n}\n\nexport interface PreflightCredentialStorageInput {\n  baseDir?: string\n  warn?: (message: string) => void\n}\n\nexport async function preflightCredentialStorage(\n  input: PreflightCredentialStorageInput = {},\n): Promise<string> {\n  const directory = defaultCredentialRoot(input.baseDir)\n  await mkdir(directory, { recursive: true, mode: 0o700 })\n  await restrictPermissions(directory, 0o700, input.warn)\n\n  const probePath = join(directory, `.haven-connect-preflight-${crypto.randomBytes(8).toString('hex')}`)\n  try {\n    await writeOwnerOnlyJson(probePath, { ok: true }, input.warn)\n  } finally {\n    await rm(probePath, { force: true }).catch(() => undefined)\n  }\n\n  return directory\n}\n\nexport async function writeCredentialFiles(input: WriteCredentialInput): Promise<StoredCredentialPaths> {\n  const directory = defaultAgentDirectory(input.serverName ?? input.agentId, input.baseDir)\n  await mkdir(directory, { recursive: true, mode: 0o700 })\n  await restrictPermissions(directory, 0o700, input.warn)\n\n  const identityPath = join(directory, 'identity.json')\n  const signerPath = join(directory, 'signer.json')\n  const agentPath = join(directory, 'agent.json')\n\n  await assertDoesNotExist(identityPath)\n  await assertDoesNotExist(signerPath)\n  await assertDoesNotExist(agentPath)\n\n  await writeOwnerOnlyJson(signerPath, signerPayload(input), input.warn)\n\n  try {\n    await writeOwnerOnlyJson(identityPath, identityPayload(input), input.warn)\n  } catch (err) {\n    await rm(signerPath, { force: true }).catch(() => undefined)\n    throw err\n  }\n\n  // Non-secret orientation file. Lets the agent answer \"who am I and what may I\n  // spend\" on its first turn by reading one local file — no MCP round trip and\n  // no exposure of the API key (identity.json) or delegate key (signer.json) in\n  // the agent's transcript. Holds the *configured* budget; live remaining budget\n  // still comes from haven_get_allowances before a payment.\n  try {\n    await writeOwnerOnlyJson(agentPath, agentPayload(input), input.warn)\n  } catch (err) {\n    // Roll back every file so a partial write (e.g. writeFile succeeds but chmod\n    // fails) can't leave agent.json behind and block reconnection via\n    // assertDoesNotExist on the next run.\n    await rm(signerPath, { force: true }).catch(() => undefined)\n    await rm(identityPath, { force: true }).catch(() => undefined)\n    await rm(agentPath, { force: true }).catch(() => undefined)\n    throw err\n  }\n\n  return { directory, identityPath, signerPath, agentPath }\n}\n\n// ── The three credential payloads, in one place ────────────────────────────\n//\n// Shared by the create path above and the re-key rewrite below (#1700). A\n// second copy of these shapes is how a re-key ends up writing a credential set\n// that setup would never have produced — a missing `x402_binding_signer`, a\n// dropped budget — which nothing downstream would flag, because each file is\n// individually well-formed.\n\nfunction signerPayload(input: WriteCredentialInput): Record<string, unknown> {\n  return {\n    delegate_key: input.delegateKey,\n    delegate_address: input.delegateAddress,\n    agent_id: input.agentId,\n    account_address: input.accountAddress,\n    chain_id: input.chainId,\n    network: input.network,\n    x402_binding_signer: input.x402BindingSigner,\n    note: 'Local signer credential. Haven backend never receives this private key.',\n  }\n}\n\nfunction identityPayload(input: WriteCredentialInput): Record<string, unknown> {\n  return {\n    api_key: input.apiKey,\n    agent_id: input.agentId,\n    account_address: input.accountAddress,\n    chain_id: input.chainId,\n    network: input.network,\n    api_url: input.apiUrl,\n    hosted_mcp_url: input.hostedMcpUrl,\n    agent_budget: input.agentBudget,\n    note: 'Haven API key identifies the agent only. It cannot spend without the local signer key and on-chain Haven wallet rules.',\n  }\n}\n\nfunction agentPayload(input: WriteCredentialInput): Record<string, unknown> {\n  return {\n    agent_id: input.agentId,\n    delegate_address: input.delegateAddress,\n    account_address: input.accountAddress,\n    chain_id: input.chainId,\n    network: input.network,\n    agent_budget: input.agentBudget,\n    note: 'Non-secret orientation for the agent: public delegate/Haven wallet identity + configured budget. Contains no API key or signing key. For the live remaining budget, call haven_get_allowances.',\n  }\n}\n\n// ── Re-key: rewriting a credential set IN PLACE (#1700) ────────────────────\n\n/** What a re-key found on disk before it rewrote anything. */\nexport interface StoredCredentialSnapshot {\n  directory: string\n  agentId: string\n  apiKey: string\n  delegateAddress?: string\n  /**\n   * #3737 owner decision 3: set only when the directory was DISCOVERED (no\n   * `--name`/agent-id key given) and its MCP binding names a valid hosted\n   * slug — so the printed `--rekey-finish` line can carry the exact\n   * `--name` instead of relying on the sole-agent discovery holding until\n   * phase two. Absent for a bare agent (no slug to print) and for an\n   * explicitly keyed call.\n   */\n  discoveredSlug?: string\n  accountAddress?: string\n  /**\n   * Which key the stored files carried the account address under — `--doctor`\n   * reports it (#2908). `account_address` from this release on; `safe_address`\n   * for a set written before it (still read, rewritten on the next re-key).\n   */\n  accountAddressKey?: 'account_address' | 'safe_address'\n  chainId?: number\n  network?: string\n  apiUrl: string\n  hostedMcpUrl: string\n  x402BindingSigner?: string\n  agentBudget?: WriteCredentialInput['agentBudget']\n}\n\n/**\n * Read the existing credential set a re-key is about to replace.\n *\n * Deliberately strict about the three fields a rewrite cannot invent — the\n * agent id, the current API key and the API URL. A directory missing any of\n * them is not a re-keyable agent, and guessing (say, defaulting the API URL to\n * localhost) would produce a credential set that authenticates against the\n * wrong Haven.\n */\nexport async function readStoredCredentials(\n  serverName: string | undefined,\n  agentIdOrSlug: string | undefined,\n  baseDir?: string,\n): Promise<StoredCredentialSnapshot> {\n  // #3799: --name resolves by the pair the directory RECORDS, not by assuming\n  // the folder is named after the slug — the same rule --doctor/--repair and\n  // --unwire now use. Legacy agent-id keyed directories keep their path.\n  const directory = serverName\n    ? await resolveAgentDirectoryBySlug(serverName, { root: baseDir })\n    : agentIdOrSlug\n      ? defaultAgentDirectory(agentIdOrSlug, baseDir)\n      : await discoverSoleAgentDirectory(baseDir)\n\n  const identity = await readJsonFile(join(directory, 'identity.json'))\n  if (!identity) {\n    throw new Error(\n      `No Haven credentials at ${directory}. Nothing to re-key — connect this agent first, ` +\n        'or pass the --name you wired it under.',\n    )\n  }\n  // #3737 owner decision 3: a discovered directory reports its own slug, so\n  // the repair line names it exactly — the sole-agent discovery that selected\n  // it must not have to hold until phase two.\n  let discoveredSlug: string | undefined\n  if (!serverName && !agentIdOrSlug) {\n    const binding = await readJsonFile(join(directory, 'mcp-server-binding.json'))\n    const hostedName = binding && typeof binding === 'object' ? asString((binding as Record<string, unknown>).server_name) : undefined\n    if (hostedName && hostedName.startsWith('haven-')) {\n      const slug = hostedName.slice('haven-'.length)\n      try {\n        assertValidServerSlug(slug)\n        discoveredSlug = slug\n      } catch {\n        // Not a slug-shaped suffix (or a reserved name): print no --name and\n        // let phase two rediscover, rather than print a wrong one.\n      }\n    }\n  }\n  const agent = (await readJsonFile(join(directory, 'agent.json'))) ?? {}\n  const signer = (await readJsonFile(join(directory, 'signer.json'))) ?? {}\n\n  const agentId = asString(identity.agent_id)\n  const apiKey = asString(identity.api_key)\n  const apiUrl = asString(identity.api_url)\n  const hostedMcpUrl = asString(identity.hosted_mcp_url)\n  if (!agentId || !apiKey || !apiUrl || !hostedMcpUrl) {\n    throw new Error(\n      `The credential set at ${directory} is incomplete (identity.json is missing agent_id, ` +\n        'api_key, api_url or hosted_mcp_url). Re-key cannot rebuild it — reconnect the agent instead.',\n    )\n  }\n\n  return {\n    directory,\n    agentId,\n    apiKey,\n    ...(discoveredSlug ? { discoveredSlug } : {}),\n    apiUrl,\n    hostedMcpUrl,\n    delegateAddress: asString(agent.delegate_address) ?? asString(signer.delegate_address),\n    ...readStoredAccountAddress(identity, agent),\n    chainId: typeof identity.chain_id === 'number' ? identity.chain_id : undefined,\n    network: asString(identity.network),\n    x402BindingSigner: asString(signer.x402_binding_signer),\n    agentBudget: Array.isArray(identity.agent_budget)\n      ? (identity.agent_budget as WriteCredentialInput['agentBudget'])\n      : undefined,\n  }\n}\n\n/**\n * The account address off a stored credential set, new name first (#2908):\n * `account_address` (what this package writes from this release on) across\n * both non-secret files, then the pre-#2908 `safe_address` across both. The\n * old fallback is PERMANENT — a credential set written before this release\n * never rewrites itself until the next re-key runs through `rewriteCredentialFiles`.\n *\n * Also says WHICH key was found, so `--doctor` can report it. Exported for\n * the mutation tests: dropping `account_address` fails the new-shape test,\n * dropping `safe_address` fails the old-shape test.\n */\nexport function readStoredAccountAddress(\n  identity: Record<string, unknown>,\n  agent: Record<string, unknown>,\n): Pick<StoredCredentialSnapshot, 'accountAddress' | 'accountAddressKey'> {\n  const fresh = asString(identity.account_address) ?? asString(agent.account_address)\n  if (fresh) return { accountAddress: fresh, accountAddressKey: 'account_address' }\n  const legacy = asString(identity.safe_address) ?? asString(agent.safe_address)\n  if (legacy) return { accountAddress: legacy, accountAddressKey: 'safe_address' }\n  return {}\n}\n\n/**\n * Find the one wired agent on this machine, when no `--name` was given.\n *\n * The unnamed agent's directory is keyed by its AGENT ID\n * (`~/.haven/agents/<agent-uuid>/`), which the person running the command does\n * not know and has no reason to — they never typed it. Requiring it was the\n * defect review caught: `--rekey` was unusable for the DEFAULT setup, the one\n * the help text describes as \"omit --name for the bare pair\", while working\n * fine for the named case the tests happened to cover.\n *\n * Discovery, not guessing. Exactly one candidate is resolved; several is an\n * ambiguity only the user can settle, so it refuses and NAMES them rather than\n * picking the newest — \"newest wins\" is the heuristic #1695 removed, and\n * silently re-keying the wrong agent is the worst outcome available here.\n * A tombstoned directory (#1681) is skipped: it is a deliberately retired\n * agent, never a re-key target.\n */\nasync function discoverSoleAgentDirectory(baseDir?: string): Promise<string> {\n  const root = defaultCredentialRoot(baseDir)\n  let entries: string[] = []\n  try {\n    entries = await readdir(root)\n  } catch {\n    throw new Error(`No Haven credentials found under ${root}. Connect an agent on this machine first.`)\n  }\n\n  const candidates: string[] = []\n  for (const entry of entries) {\n    const directory = join(root, entry)\n    const identity = await readJsonFile(join(directory, 'identity.json'))\n    if (!identity) continue\n    // #3737 owner decision 3: a LIVE agent only — one that still holds a\n    // stored API key. A key-removed directory (unwired or reset) is not one\n    // --rekey can act for, and under named-by-default the credential root\n    // carries retired directories of every shape.\n    if (!asString(identity.api_key)) continue\n    if (await readJsonFile(join(directory, 'TOMBSTONE.json'))) continue\n    candidates.push(directory)\n  }\n\n  if (candidates.length === 1) return candidates[0]\n  if (candidates.length === 0) {\n    throw new Error(`No Haven credentials found under ${root}. Connect an agent on this machine first.`)\n  }\n  throw new Error(\n    `Several agents are wired on this machine, so --rekey cannot tell which one you mean:\\n` +\n      candidates.map((d) => `  ${d}`).join('\\n') +\n      '\\nRe-run with --name <slug> to pick one.',\n  )\n}\n\n// ── One --name resolver, shared by --doctor/--repair/--rekey/--unwire (#3799) ──\n//\n// Every stored-state subcommand that takes `--name <slug>` resolves the agent\n// directory through THIS rule, not by assuming the folder is named after the\n// slug. A directory claims a slug when one of its OWN records says so: the\n// signer-runtime sidecar (`server_name`, what repair reads back) or the local\n// MCP server-name binding record. Which record decides: the sidecar wins; the\n// binding corroborates — a directory with neither record can still be reached\n// by its legacy folder name (pre-#1696 shape) so nothing already wired breaks.\n\nexport interface ResolveAgentDirectoryOptions {\n  /** The credential ROOT to scan. Default: ~/.haven/agents. */\n  root?: string\n  /**\n   * Retired (tombstoned) directories may claim a slug. Only --unwire wants\n   * this: it must reach a retired agent to release its name. Selection for\n   * --doctor/--repair/--rekey never matches a tombstoned directory.\n   */\n  allowRetired?: boolean\n}\n\n/** Does THIS directory record the pair for `slug`? Shared agree-check for `--name` + `--credentials-dir`. */\nexport async function assertDirectoryRecordsSlug(directory: string, slug: string): Promise<void> {\n  assertValidServerSlug(slug)\n  const sidecar = await readRuntimeSidecar(directory)\n  const bindingRecord = await readJsonFile(join(directory, 'mcp-server-binding.json'))\n  const bindingSlug = bindingRecord ? asString(bindingRecord.server_name) : undefined\n  const claimed = sidecar?.server_name ?? bindingSlug\n  if (claimed === slug) return\n  // Pre-#1696: no record at all, folder named after the slug — the assumption\n  // every --name consumer made before this resolver existed.\n  if (!claimed && basename(directory) === slug) return\n  throw new Error(\n    `--name ${slug} and --credentials-dir ${directory} disagree: that directory records ` +\n      (claimed ? `the pair 'haven-${claimed}'` : 'no named pair') +\n      `. Pass one of them, not both — or point --credentials-dir at the directory that records 'haven-${slug}'.`,\n  )\n}\n\nexport async function resolveAgentDirectoryBySlug(\n  slug: string,\n  opts: ResolveAgentDirectoryOptions = {},\n): Promise<string> {\n  assertValidServerSlug(slug)\n  const root = defaultCredentialRoot(opts.root)\n  let entries: string[] = []\n  try {\n    entries = await readdir(root)\n  } catch {\n    throw new Error(\n      `No agent directories under ${root} — nothing records the pair 'haven-${slug}'. ` +\n        'Connect this agent first, or pass --credentials-dir <path> for the exact directory.',\n    )\n  }\n  interface Claim {\n    directory: string\n    agentId: string | null\n    retired: boolean\n  }\n  const claims: Claim[] = []\n  const recordedSlugs: string[] = []\n  let barePairCount = 0\n  let legacyFolder: string | undefined\n  for (const entry of entries.sort()) {\n    const directory = join(root, entry)\n    const retired = (await readJsonFile(join(directory, TOMBSTONE_FILENAME))) !== null\n    const sidecar = await readRuntimeSidecar(directory)\n    const bindingRecord = await readJsonFile(join(directory, 'mcp-server-binding.json'))\n    const bindingSlug = bindingRecord ? asString(bindingRecord.server_name) : undefined\n    const claimedSlug = sidecar?.server_name ?? bindingSlug\n    if (claimedSlug && !recordedSlugs.includes(claimedSlug)) recordedSlugs.push(claimedSlug)\n    // A sidecar without a server_name is the bare `haven` / `haven-signer` pair.\n    if (sidecar && !sidecar.server_name) barePairCount++\n    if (retired && !opts.allowRetired) continue\n    if (claimedSlug === slug) {\n      const identity = await readJsonFile(join(directory, 'identity.json'))\n      claims.push({ directory, agentId: identity ? (asString(identity.agent_id) ?? null) : null, retired })\n    }\n    // Legacy fallback: no record claims anything, and the folder carries the\n    // slug as its name — exactly where the old `join(root, slug)` look landed.\n    if (!claimedSlug && !retired && entry === slug) legacyFolder = directory\n  }\n  if (claims.length > 1) {\n    throw new Error(\n      `${claims.length} agent directories on this machine record the pair 'haven-${slug}' — the MCP server name ` +\n        `changed hands (mcp_server_name_rebound):\\n` +\n        claims\n          .map((c) => `  • ${c.agentId ? `agent ${c.agentId}` : 'agent (no agent_id recorded)'} — ${c.directory}${c.retired ? ' (retired)' : ''}`)\n          .join('\\n') +\n        '\\nRetire the earlier one with --unwire, or name the directory exactly with --credentials-dir <path>. Nothing was changed.',\n    )\n  }\n  if (claims.length === 1) return claims[0].directory\n  if (legacyFolder) return legacyFolder\n  const known = [\n    ...recordedSlugs.map((s) => `'haven-${s}'`),\n    ...(barePairCount > 0 ? [`${barePairCount} unnamed 'haven' / 'haven-signer' pair${barePairCount === 1 ? '' : 's'} (no --name)`] : []),\n  ]\n  throw new Error(\n    `No agent directory on this machine records the pair 'haven-${slug}'.` +\n      (known.length > 0 ? ` Directories under ${root} record: ${known.join(', ')}.` : ` Nothing under ${root} records a named pair.`) +\n      ' Check the agent id against the Haven agent page, or name the directory exactly with --credentials-dir <path>.',\n  )\n}\n\n/**\n * Replace an existing credential set in place, all-or-nothing.\n *\n * This is the ONLY path allowed to overwrite credential files, and the reason\n * `assertDoesNotExist` is not consulted here. That guard exists to stop a\n * re-run silently replacing a live agent's keys; a re-key is the one operation\n * whose whole purpose is to replace them, at a path that deliberately does not\n * move (#1694 owner decision — no new directory, no tombstone, so nothing\n * downstream has a dead path to chase).\n *\n * **Why the temp-then-rename dance.** The acceptance bar is that a failure\n * never leaves a MIXED set — the old signer key beside the new API key, or the\n * reverse. That pairing is worse than either generation intact: the agent\n * authenticates as itself and then signs with a key its delegation no longer\n * names, which is precisely the payer/signer mismatch #1690 exists to catch.\n * So every file is written and permission-set as a sibling temp FIRST, and only\n * once all three are safely on disk are they renamed into place. A failure\n * before the first rename touches nothing; a failure during the renames is\n * rolled back from the in-memory snapshot of the originals.\n *\n * The residual window is a hard process kill (SIGKILL, power loss) between two\n * renames — not an exception, which is handled. Closing that needs a\n * write-ahead marker and a recovery pass at startup; it is out of scope here\n * and named rather than papered over. `doctor` already reports a credential\n * set whose delegate address disagrees with the backend, which is what such a\n * kill would leave behind.\n */\nexport async function rewriteCredentialFiles(\n  input: WriteCredentialInput,\n): Promise<StoredCredentialPaths> {\n  const directory = defaultAgentDirectory(input.serverName ?? input.agentId, input.baseDir)\n  const identityPath = join(directory, 'identity.json')\n  const signerPath = join(directory, 'signer.json')\n  const agentPath = join(directory, 'agent.json')\n\n  const targets: Array<{ path: string; payload: Record<string, unknown> }> = [\n    { path: signerPath, payload: signerPayload(input) },\n    { path: identityPath, payload: identityPayload(input) },\n    { path: agentPath, payload: agentPayload(input) },\n  ]\n\n  // The originals, so a failure mid-rename can put back exactly what was there.\n  const originals = new Map<string, string | null>()\n  for (const { path } of targets) {\n    originals.set(path, await readRawFile(path))\n  }\n\n  const temps: Array<{ from: string; to: string }> = []\n  try {\n    for (const { path, payload } of targets) {\n      const temp = `${path}.rekey-${crypto.randomBytes(6).toString('hex')}.tmp`\n      await writeOwnerOnlyJson(temp, payload, input.warn)\n      temps.push({ from: temp, to: path })\n    }\n    // Every temp is on disk and mode-restricted before ANY of them lands.\n    for (const { from, to } of temps) {\n      await rename(from, to)\n    }\n  } catch (err) {\n    for (const { from } of temps) await rm(from, { force: true }).catch(() => undefined)\n    for (const [path, contents] of originals) {\n      if (contents === null) {\n        await rm(path, { force: true }).catch(() => undefined)\n      } else {\n        await writeFile(path, contents, { mode: 0o600 }).catch(() => undefined)\n      }\n    }\n    throw err\n  }\n\n  return { directory, identityPath, signerPath, agentPath }\n}\n\n// ── The pending key, between the two re-key phases (#1700) ─────────────────\n//\n// `--rekey` generates the new keypair and then STOPS, because the dashboard\n// needs its public address before it can run the five owner-signed steps that\n// end in a new API key. The private half has to survive that gap.\n//\n// It lives in the agent's own credential directory, at 0600, beside the live\n// signer key it is going to replace — the same directory, the same mode, the\n// same machine. That is the point: it widens no boundary that the live key has\n// not already crossed. It is a SECOND copy until `--rekey-finish` consumes it,\n// which is why it expires and why both the finish and a fresh `--rekey` delete\n// it rather than leaving it to rot.\n//\n// It is deliberately NOT a tombstone and NOT in a temp dir: a tombstone marks a\n// dead path (#1681's recreation case) and there is no dead path here, while a\n// temp dir is exactly the kind of world-traversable location a private key\n// should never sit in.\n\nexport const REKEY_PENDING_FILENAME = 'rekey-pending.json'\n\n/** How long a started re-key stays resumable. */\nexport const REKEY_PENDING_TTL_MS = 24 * 60 * 60 * 1000\n\nexport interface RekeyPending {\n  agent_id: string\n  new_delegate_address: string\n  new_delegate_key: string\n  started_at: string\n  expires_at: string\n}\n\nexport async function writeRekeyPending(\n  directory: string,\n  pending: RekeyPending,\n  warn?: (message: string) => void,\n): Promise<string> {\n  const path = join(directory, REKEY_PENDING_FILENAME)\n  // Overwrite deliberately: starting a re-key again replaces an earlier\n  // unfinished attempt. Keeping the first would strand the owner on an address\n  // the dashboard no longer shows, with no way to tell which is live.\n  await rm(path, { force: true }).catch(() => undefined)\n  await writeOwnerOnlyJson(path, { ...pending }, warn)\n  return path\n}\n\n/**\n * Read a started re-key, or explain why there is nothing to finish.\n *\n * An EXPIRED pending file is an error rather than a silent miss: the owner\n * asked to finish a re-key, and \"no pending re-key found\" would send them\n * looking for a typo when the real answer is that it timed out and the address\n * in their dashboard is stale.\n */\nexport async function readRekeyPending(directory: string, now = Date.now()): Promise<RekeyPending> {\n  const path = join(directory, REKEY_PENDING_FILENAME)\n  const raw = await readJsonFile(path)\n  if (!raw) {\n    throw new Error(\n      `No re-key in progress at ${directory}. Run the connector with --rekey first — it prints ` +\n        'the new signing address to paste into the Haven agent page.',\n    )\n  }\n  const pending = raw as unknown as RekeyPending\n  if (!pending.new_delegate_key || !pending.new_delegate_address || !pending.agent_id) {\n    throw new Error(`The pending re-key at ${path} is unreadable. Delete it and start again with --rekey.`)\n  }\n  if (pending.expires_at && Date.parse(pending.expires_at) < now) {\n    throw new Error(\n      `The re-key started at ${pending.started_at} has expired. Start again with --rekey — the ` +\n        'address currently shown in your dashboard is no longer the one this machine holds.',\n    )\n  }\n  return pending\n}\n\n/**\n * What a pending re-key IS, for anything that only needs to report it (#1911).\n *\n * Deliberately a separate return type from {@link RekeyPending}: it has no\n * `new_delegate_key` field at all, so a caller that reports this cannot leak\n * the private half by forgetting to strip it. The diagnostic surface uses this\n * accessor and never {@link readRekeyPending} — key material is unreachable\n * from that side by construction, not by discipline.\n *\n * Also a non-throwing read, where `readRekeyPending` throws: `--rekey-finish`\n * asked to consume one and deserves an error, but the doctor is enumerating\n * every directory on the machine and \"there isn't one\" is the normal answer.\n */\nexport interface RekeyPendingStatus {\n  /** `pending` — still resumable; `expired` — past its TTL; `unreadable` — present but malformed. */\n  state: 'pending' | 'expired' | 'unreadable'\n  /** Where the file is, so the owner can act on it without hunting. */\n  path: string\n  agentId?: string\n  /** PUBLIC address. The private half is never read into this shape. */\n  newDelegateAddress?: string\n  startedAt?: string\n  expiresAt?: string\n}\n\nexport async function inspectRekeyPending(\n  directory: string,\n  now = Date.now(),\n): Promise<RekeyPendingStatus | null> {\n  const path = join(directory, REKEY_PENDING_FILENAME)\n  const raw = await readJsonFile(path)\n  if (!raw) {\n    // Distinguish \"no file\" from \"file that will not parse\". A file present\n    // but unparseable still holds bytes that were a private key, so it is\n    // reportable — reporting nothing would be the observability gap this\n    // accessor exists to close.\n    const present = (await readRawFile(path)) !== null\n    return present ? { state: 'unreadable', path } : null\n  }\n  const agentId = asString(raw.agent_id)\n  const newDelegateAddress = asString(raw.new_delegate_address)\n  const startedAt = asString(raw.started_at)\n  const expiresAt = asString(raw.expires_at)\n  if (!agentId || !newDelegateAddress) {\n    return { state: 'unreadable', path, ...(startedAt ? { startedAt } : {}) }\n  }\n  const expired = expiresAt !== undefined && Date.parse(expiresAt) < now\n  return {\n    state: expired ? 'expired' : 'pending',\n    path,\n    agentId,\n    newDelegateAddress,\n    ...(startedAt ? { startedAt } : {}),\n    ...(expiresAt ? { expiresAt } : {}),\n  }\n}\n\nexport async function clearRekeyPending(directory: string): Promise<void> {\n  await rm(join(directory, REKEY_PENDING_FILENAME), { force: true }).catch(() => undefined)\n}\n\nasync function readJsonFile(path: string): Promise<Record<string, unknown> | null> {\n  const raw = await readRawFile(path)\n  if (raw === null) return null\n  try {\n    const parsed = JSON.parse(raw) as unknown\n    return parsed && typeof parsed === 'object' && !Array.isArray(parsed)\n      ? (parsed as Record<string, unknown>)\n      : null\n  } catch {\n    return null\n  }\n}\n\nasync function readRawFile(path: string): Promise<string | null> {\n  try {\n    return await readFile(path, 'utf8')\n  } catch {\n    return null\n  }\n}\n\nfunction asString(value: unknown): string | undefined {\n  return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\n\n/**\n * #1696: a wiring slug keys a credential directory, and connect never\n * overwrites credential files — a taken slug is refused before any side\n * effect. A leftover EMPTY slug directory (no identity.json) does not count\n * as taken. Replacing a named agent's credentials in place is #1700's\n * explicit re-key path, never a re-run.\n */\nexport async function assertServerSlugAvailable(serverName: string, baseDir?: string): Promise<void> {\n  const directory = defaultAgentDirectory(serverName, baseDir)\n  try {\n    await stat(join(directory, 'identity.json'))\n  } catch {\n    return\n  }\n  throw new Error(\n    `The name \"${serverName}\" is already wired on this machine (${directory} holds credentials). ` +\n      'Pick a different --name, or revoke and remove that agent first — connect never overwrites credentials.',\n  )\n}\n\nexport function defaultAgentDirectory(agentId: string, baseDir = join(homedir(), '.haven', 'agents')): string {\n  return resolve(defaultCredentialRoot(baseDir), safePathPart(agentId))\n}\n\nexport function defaultCredentialRoot(baseDir = join(homedir(), '.haven', 'agents')): string {\n  return resolve(baseDir)\n}\n\nasync function writeOwnerOnlyJson(\n  path: string,\n  value: Record<string, unknown>,\n  warn: ((message: string) => void) | undefined,\n): Promise<void> {\n  const json = JSON.stringify(dropUndefined(value), null, 2)\n  await writeFile(path, `${json}\\n`, { mode: 0o600, flag: 'wx' })\n  await restrictPermissions(path, 0o600, warn)\n}\n\nfunction safePathPart(value: string): string {\n  return value.replace(/[^A-Za-z0-9_.-]/g, '_')\n}\n\nfunction dropUndefined(value: Record<string, unknown>): Record<string, unknown> {\n  return Object.fromEntries(Object.entries(value).filter(([, field]) => field !== undefined))\n}\n\nasync function assertDoesNotExist(path: string): Promise<void> {\n  try {\n    await access(path)\n  } catch (err) {\n    if (err && typeof err === 'object' && 'code' in err && err.code === 'ENOENT') return\n    throw err\n  }\n  throw new Error(`Refusing to overwrite existing Haven credential file: ${path}`)\n}\n\nasync function restrictPermissions(\n  path: string,\n  mode: 0o600 | 0o700,\n  warn: ((message: string) => void) | undefined,\n): Promise<void> {\n  try {\n    await chmod(path, mode)\n  } catch (err) {\n    warn?.(\n      `Warning: could not restrict permissions on ${path} to ${mode.toString(8)}. ` +\n        `Move this credential to a private location or run chmod ${mode.toString(8)} ${path}. ` +\n        `${err instanceof Error ? err.message : String(err)}`,\n    )\n  }\n}\n\n// ── The recovery record (#2173) ─────────────────────────────────────────────\n\n/**\n * Where the terminal `ConnectOutcome` is parked so a caller that lost the\n * stream can still read the verdict.\n *\n * The field failure this exists for (2026-08-28, connector 0.1.31-alpha.0):\n * setup SUCCEEDED, but the agent driving it stopped watching during the cold\n * signer install, so the connector's final `--json` object — the only place\n * the restart instruction and the read-only verification sequence live — was\n * emitted into a stream nobody was reading. The agent reverse-engineered\n * completion from `codex mcp list` instead.\n */\nexport const CONNECT_OUTCOME_FILENAME = 'last-connect-outcome.json'\n\n/**\n * Persist the terminal outcome next to the credentials it describes.\n *\n * Non-secret by construction: the content is exactly the object already\n * emitted on stdout, whose secret-freedom is pinned by its own tests. This\n * function never reads or embeds credential-file contents — it serializes what\n * it is handed and nothing else. Written 0o600 anyway, because it lives inside\n * a 0o700 credential directory and there is no reason to widen it.\n *\n * Overwrites, unlike every other write in this file: \"the last outcome\" is a\n * single slot, not a credential, so `assertDoesNotExist` would be wrong here —\n * a stale verdict left in place is exactly the failure the file exists to\n * prevent.\n *\n * Throws on failure. Best-effort is the CALLER's contract (`runConnect` wraps\n * both call sites), so that a test can inject a writer that fails and still\n * assert the run completes.\n */\nexport async function writeConnectOutcomeRecord(\n  directory: string,\n  outcome: unknown,\n  warn?: (message: string) => void,\n): Promise<string> {\n  const path = join(directory, CONNECT_OUTCOME_FILENAME)\n  await writeFile(path, `${JSON.stringify(outcome, null, 2)}\\n`, { mode: 0o600 })\n  await restrictPermissions(path, 0o600, warn)\n  return path\n}\n\n/**\n * #3120: the doctor's read side of the same record.\n *\n * Returns the verbatim `runtime` string a completed or failed setup parked in\n * this directory's `last-connect-outcome.json` — or null when there is no\n * record, it is unreadable, it does not parse, or it carries no string\n * `runtime` field. Best-effort mirrors the write: `recordConnectOutcome`\n * swallows every write failure, so a missing record is a real path, not a\n * defensive one. Never throws; every degradation is silent because the CALLER\n * owns the user-visible \"runtime unknown\" verdict (and names the directory it\n * inspected).\n */\nexport async function readConnectOutcomeRuntime(directory: string): Promise<string | null> {\n  try {\n    const parsed = JSON.parse(await readFile(join(directory, CONNECT_OUTCOME_FILENAME), 'utf8')) as unknown\n    if (typeof parsed !== 'object' || parsed === null) return null\n    const runtime = (parsed as { runtime?: unknown }).runtime\n    return typeof runtime === 'string' && runtime.length > 0 ? runtime : null\n  } catch {\n    return null\n  }\n}\n\n// ── #3122: the local MCP-server-name binding record ─────────────────────────\n//\n// The backend persists the binding (`agents.mcp_server_name`, migration 067)\n// and is the authority for the same-backend case. What it cannot answer is\n// the two cases that bit on 2026-09-18: the same name repointed to a DIFFERENT\n// backend, and a machine that is offline. So each credential directory keeps\n// a non-secret record of what its setup bound — server name → agent id,\n// backend base URL, bound-at — beside `last-connect-outcome.json`. Per\n// DIRECTORY, not machine-wide: two concurrent setups never write the same\n// file, and \"who else claims this name\" is answered by scanning the root,\n// which setup and doctor already do. It is a reporting aid: it never asserts\n// itself as the backend's current truth, and the doctor says so when two\n// records disagree. Carries no API key by construction (pinned by test).\n\nexport const MCP_SERVER_BINDING_FILENAME = 'mcp-server-binding.json'\n\nexport interface McpServerBinding {\n  version: 1\n  /** The hosted MCP server name this directory's setup wired (`haven` or `haven-<slug>`). */\n  server_name: string\n  /** The paired signer server name (`haven-signer` or `haven-signer-<slug>`). */\n  signer_name: string\n  agent_id: string\n  /** The `--api` backend base URL the agent was registered with — the axis the backend cannot see a change on. */\n  api_url: string\n  hosted_mcp_url?: string\n  bound_at: string\n}\n\n/** Overwrites: a binding is a single slot per directory, like the outcome record. 0o600 inside a 0o700 directory. */\nexport async function writeMcpServerBinding(directory: string, binding: McpServerBinding): Promise<string> {\n  const path = join(directory, MCP_SERVER_BINDING_FILENAME)\n  await writeFile(path, `${JSON.stringify(binding, null, 2)}\\n`, { mode: 0o600 })\n  return path\n}\n\n/** Never throws: no record, unreadable or malformed all read as `null`. */\nexport async function readMcpServerBinding(directory: string): Promise<McpServerBinding | null> {\n  try {\n    const parsed = JSON.parse(await readFile(join(directory, MCP_SERVER_BINDING_FILENAME), 'utf8')) as unknown\n    if (typeof parsed !== 'object' || parsed === null) return null\n    const record = parsed as Partial<McpServerBinding>\n    if (record.version !== 1 || typeof record.server_name !== 'string' || typeof record.agent_id !== 'string' || typeof record.api_url !== 'string' || typeof record.bound_at !== 'string') return null\n    return record as McpServerBinding\n  } catch {\n    return null\n  }\n}\n\n/** `--unwire` (and a `--replace` retirement) release the name: a legitimately free name must not warn forever. */\nexport async function clearMcpServerBinding(directory: string): Promise<boolean> {\n  try {\n    await rm(join(directory, MCP_SERVER_BINDING_FILENAME))\n    return true\n  } catch {\n    return false\n  }\n}\n\n/** Every directory under the credential root that carries a binding record, except `excludeDirectory`. Never throws. */\nexport async function listMcpServerBindings(\n  baseDir: string | undefined,\n  excludeDirectory?: string,\n): Promise<Array<{ directory: string; binding: McpServerBinding }>> {\n  const root = defaultCredentialRoot(baseDir)\n  let entries: string[] = []\n  try {\n    entries = await readdir(root)\n  } catch {\n    return []\n  }\n  const out: Array<{ directory: string; binding: McpServerBinding }> = []\n  for (const entry of entries) {\n    const directory = join(root, entry)\n    if (excludeDirectory && directory === excludeDirectory) continue\n    const binding = await readMcpServerBinding(directory)\n    if (binding) out.push({ directory, binding })\n  }\n  return out\n}\n","import { mkdir, readFile, writeFile, chmod, unlink } from 'node:fs/promises'\nimport { connectorRerunCommand } from '@haven_ai/sdk'\nimport { homedir, platform } from 'node:os'\nimport { dirname, join, resolve } from 'node:path'\nimport { isMap, parseDocument, stringify } from 'yaml'\nimport { signerPackageSpec } from './runtime-manifest.js'\nimport { serverNamesFor, type ServerNames } from './server-names.js'\nimport { type RuntimeId } from './runtime-registry.js'\n\nexport type RuntimeMcpMode = 'local_stdio' | 'hosted_plus_signer' | 'manual'\n\nconst HERMES_API_KEY_ENV = 'MCP_HAVEN_API_KEY'\n\n/** How to launch the local edge signer as an MCP stdio server. */\nexport interface SignerLaunchSpec {\n  command: string\n  args: string[]\n}\n\nexport interface RuntimeConfigInput {\n  runtime: RuntimeId\n  hostedMcpUrl: string\n  apiKey: string\n  identityPath: string\n  signerPath: string\n  credentialDirectory: string\n  localMcpCommand?: string\n  /**\n   * Prepared signer launch command (absolute wrapper from prepareSignerRuntime).\n   * When absent, falls back to a runtime `npx -y @haven_ai/signer@…` invocation,\n   * which is fragile under the agent runtime's MCP-spawn environment — prefer\n   * always passing a prepared command.\n   */\n  signerCommand?: SignerLaunchSpec\n  homeDir?: string\n  /**\n   * Topology to write. 'hosted' (default) configures the keyless hosted MCP\n   * server plus the local signer; 'local' restores the local-stdio MCP for\n   * runtimes that support it (explicit opt-in only).\n   */\n  mode?: 'hosted' | 'local'\n  /**\n   * #1695: wiring slug for a NAMED server pair (haven-<slug> /\n   * haven-signer-<slug>). Absent = the bare haven / haven-signer pair,\n   * byte-identical to the pre-#1695 output. A writer only ever touches the\n   * pair it owns, so named and unnamed pairs coexist in one config.\n   */\n  serverName?: string\n}\n\nexport interface RuntimeConfigWriteResult {\n  hostedConfigured: boolean\n  signerConfigured: boolean\n  localMcpConfigured: boolean\n  runtimeMcpMode: RuntimeMcpMode\n  target: string\n  changed: boolean\n  restartRequired: boolean\n  messages: string[]\n  errorCode?: string\n  activationCommand?: string\n}\n\n/** Injectable file operations for failure-safe runtime-config tests. */\nexport interface RuntimeConfigWriteDeps {\n  writeOwnerOnlyText?: (path: string, value: string) => Promise<void>\n}\n\nclass HermesConfigRecoveryError extends Error {\n  constructor() {\n    super('Hermes configuration recovery did not complete')\n    this.name = 'HermesConfigRecoveryError'\n  }\n}\n\nexport class InvalidCodexTomlError extends Error {\n  constructor(message: string) {\n    super(message)\n    this.name = 'InvalidCodexTomlError'\n  }\n}\n\n/**\n * #1719: the chosen client's config file EXISTS but Haven cannot read it.\n *\n * Distinct from a write failure on purpose. A write failure is a permissions\n * or disk problem and \"try again\" is reasonable advice; an unreadable config\n * is a file the user has to fix by hand, and re-running the connector will\n * fail identically forever until they do. Collapsing the two under\n * `runtime_config_write_failed` told the user to retry a thing that cannot\n * succeed.\n */\n/**\n * Mirrors `RERUN` in doctor.ts — a moving dist-tag rather than a pinned\n * version, so the advice resolves to a connector that has `--repair`\n * regardless of what is cached locally. Which tag that is comes from the SDK's\n * build-time `HAVEN_CONNECTOR_CHANNEL` (#2423), so a build published under\n * `dev` repairs with the `dev` connector.\n */\nconst REPAIR_COMMAND_PREFIX = connectorRerunCommand('--doctor --repair --runtime')\n\nexport class UnreadableRuntimeConfigError extends Error {\n  readonly configPath: string\n  constructor(configPath: string, detail: string) {\n    super(`${configPath} is not a config Haven can merge into (${detail})`)\n    this.name = 'UnreadableRuntimeConfigError'\n    this.configPath = configPath\n  }\n}\n\nexport async function writeRuntimeConfig(\n  input: RuntimeConfigInput,\n  deps: RuntimeConfigWriteDeps = {},\n): Promise<RuntimeConfigWriteResult> {\n  switch (input.runtime) {\n    case 'codex-cli':\n    case 'codex-desktop':\n      return writeCodexConfig(input)\n    case 'cursor':\n      return writeJsonRuntimeConfig(input, cursorConfigPath(input.homeDir), 'mcpServers')\n    case 'vscode':\n      return writeJsonRuntimeConfig(input, vscodeConfigPath(input.homeDir), 'servers')\n    case 'vscode-insiders':\n      return writeJsonRuntimeConfig(input, vscodeInsidersConfigPath(input.homeDir), 'servers')\n    case 'claude-desktop':\n      return writeJsonRuntimeConfig(input, claudeDesktopConfigPath(input.homeDir), 'mcpServers')\n    case 'hermes':\n      return writeHermesConfig(input, deps)\n    default:\n      return {\n        hostedConfigured: false,\n        signerConfigured: false,\n        localMcpConfigured: false,\n        runtimeMcpMode: 'manual',\n        target: 'manual runtime setup',\n        changed: false,\n        restartRequired: true,\n        messages: ['Runtime config needs to be added manually for this agent environment.'],\n        errorCode: 'manual_runtime_setup_required',\n      }\n  }\n}\n\nexport function buildHostedServer(hostedMcpUrl: string, apiKey: string, runtime: RuntimeId): Record<string, unknown> {\n  if (runtime === 'vscode' || runtime === 'vscode-insiders') {\n    return {\n      type: 'http',\n      url: hostedMcpUrl,\n      headers: { Authorization: `Bearer ${apiKey}` },\n    }\n  }\n  return {\n    url: hostedMcpUrl,\n    headers: { Authorization: `Bearer ${apiKey}` },\n  }\n}\n\n/**\n * Resolve how to launch the signer: the prepared absolute-path wrapper when\n * available, otherwise a runtime npx invocation (fallback only).\n */\nexport function resolveSignerLaunchSpec(input: RuntimeConfigInput): SignerLaunchSpec {\n  return (\n    input.signerCommand ?? {\n      command: 'npx',\n      args: ['-y', signerPackageSpec(), '--credentials', input.signerPath],\n    }\n  )\n}\n\nexport function buildSignerServer(spec: SignerLaunchSpec, runtime: RuntimeId): Record<string, unknown> {\n  const server = {\n    command: spec.command,\n    args: spec.args,\n  }\n  if (runtime === 'vscode' || runtime === 'vscode-insiders') return { type: 'stdio', ...server }\n  return server\n}\n\nexport function buildLocalMcpServer(command: string, runtime: RuntimeId): Record<string, unknown> {\n  const server = {\n    command,\n    args: [],\n  }\n  if (runtime === 'vscode' || runtime === 'vscode-insiders') return { type: 'stdio', ...server }\n  return server\n}\n\nexport function mergeJsonMcpConfig(\n  existingJson: string | null,\n  serverRoot: 'mcpServers' | 'servers',\n  hostedServer: Record<string, unknown>,\n  signerServer: Record<string, unknown>,\n  names: ServerNames = serverNamesFor(),\n  configPath?: string,\n): string {\n  const config = existingJson?.trim() ? parseJsonObject(existingJson, configPath) : {}\n  const existingRoot = config[serverRoot]\n  const servers = existingRoot && typeof existingRoot === 'object' && !Array.isArray(existingRoot)\n    ? existingRoot as Record<string, unknown>\n    : {}\n  config[serverRoot] = {\n    ...servers,\n    [names.hosted]: hostedServer,\n    [names.signer]: signerServer,\n  }\n  return `${JSON.stringify(config, null, 2)}\\n`\n}\n\n/** Merge Haven's managed MCP entries into Hermes's YAML configuration. */\nexport function mergeHermesYaml(\n  existingYaml: string | null,\n  hostedServer: Record<string, unknown>,\n  signerServer: Record<string, unknown>,\n  names: ServerNames = serverNamesFor(),\n  configPath?: string,\n): string {\n  if (!existingYaml?.trim()) {\n    return renderHermesYaml({ [names.hosted]: hostedServer, [names.signer]: signerServer })\n  }\n\n  const doc = parseDocument(existingYaml, { keepSourceTokens: true })\n  if (doc.errors.length > 0 || !isMap(doc.contents)) {\n    // #1719: the same class as an unparseable JSON config — the file has to be\n    // fixed by hand, so it must not be reported as a retryable write failure.\n    // The YAML parser's own message is deliberately NOT included: it quotes the\n    // offending source, which is a file that may hold another server's bearer\n    // token (the #1719 sibling of the redaction rule this writer already keeps).\n    throw new UnreadableRuntimeConfigError(configPath ?? 'the Hermes config', 'it is not a YAML object')\n  }\n\n  const mcpPair = doc.contents.items.find((item) => item.key?.toString() === 'mcp_servers')\n  const existingServers = mcpPair && isMap(mcpPair.value) ? mcpPair.value.toJSON() : {}\n  const servers = isRecord(existingServers) ? existingServers : {}\n  const mergedServers = {\n    ...servers,\n    [names.hosted]: hostedServer,\n    [names.signer]: signerServer,\n  }\n\n  if (!mcpPair) {\n    return appendHermesMcpServers(existingYaml, mergedServers)\n  }\n  if (!mcpPair.value?.range) return replaceEmptyHermesMcpServers(existingYaml, mcpPair.key?.range, mergedServers)\n  return replaceHermesMcpServers(existingYaml, mcpPair.key?.range, mcpPair.value.range, mergedServers)\n}\n\n/**\n * Upsert the hosted MCP identity in Hermes's dotenv file without evaluating\n * arbitrary dotenv syntax or rewriting unrelated lines.\n */\nexport function mergeHermesEnv(\n  existingEnv: string | null,\n  apiKey: string,\n  envKey: string = HERMES_API_KEY_ENV,\n): string {\n  if (/[\\r\\n]/.test(apiKey)) throw new Error('Hermes API key must be a single line')\n\n  const assignment = `${envKey}=${apiKey}`\n  if (!existingEnv) return `${assignment}\\n`\n\n  const lineEnding = existingEnv.includes('\\r\\n') ? '\\r\\n' : '\\n'\n  const hasTrailingNewline = /\\r?\\n$/.test(existingEnv)\n  const lines = existingEnv.split(/\\r?\\n/)\n  if (hasTrailingNewline) lines.pop()\n\n  let found = false\n  const merged = lines.flatMap((line) => {\n    if (isHermesEnvAssignment(line, envKey)) {\n      if (found) return []\n      found = true\n      return [assignment]\n    }\n    if (isAmbiguousHermesEnvLine(line, envKey)) {\n      throw new Error('Hermes environment contains an ambiguous managed key')\n    }\n    return [line]\n  })\n\n  if (!found) {\n    return `${existingEnv}${hasTrailingNewline ? '' : lineEnding}${assignment}${lineEnding}`\n  }\n  return `${merged.join(lineEnding)}${hasTrailingNewline ? lineEnding : ''}`\n}\n\nfunction isHermesEnvAssignment(line: string, envKey: string): boolean {\n  return new RegExp(`^\\\\s*(?:export[ \\\\t]+)?${envKey}[ \\\\t]*=`).test(line)\n}\n\nfunction isAmbiguousHermesEnvLine(line: string, envKey: string): boolean {\n  // The env keys are our own generated identifiers (no regex metacharacters),\n  // so embedding them in a pattern is safe by construction.\n  return new RegExp(`^\\\\s*(?:export[ \\\\t]+)?${envKey}\\\\b`).test(line)\n}\n\n/**\n * Remove one agent's managed pair from Hermes's YAML configuration,\n * byte-preserving every other line (#2169). The mirror of `mergeHermesYaml`.\n *\n * Returns the input unchanged when the pair is not present. Throws\n * `UnreadableRuntimeConfigError` when the file cannot be safely parsed, so a\n * caller can report it as a hand-fixable problem instead of writing over it.\n */\nexport function removeHermesYaml(\n  existingYaml: string | null,\n  names: ServerNames,\n  configPath?: string,\n): string {\n  if (!existingYaml?.trim()) return existingYaml ?? ''\n  const doc = parseDocument(existingYaml, { keepSourceTokens: true })\n  if (doc.errors.length > 0 || !isMap(doc.contents)) {\n    throw new UnreadableRuntimeConfigError(configPath ?? 'the Hermes config', 'it is not a YAML object')\n  }\n  const mcpPair = doc.contents.items.find((item) => item.key?.toString() === 'mcp_servers')\n  if (!mcpPair || !isMap(mcpPair.value)) return existingYaml\n\n  const toRemove = mcpPair.value.items.filter((item) => {\n    const name = item.key?.toString()\n    return name === names.hosted || name === names.signer\n  })\n  if (toRemove.length === 0) return existingYaml\n  if (toRemove.length !== mcpPair.value.items.length && toRemove.some((item) => !item.key?.range || !item.value?.range)) {\n    // A sibling entry we would have to splice around lacks source ranges —\n    // refuse rather than risk corrupting someone else's pair.\n    throw new UnreadableRuntimeConfigError(configPath ?? 'the Hermes config', 'an MCP server entry cannot be safely removed')\n  }\n\n  let out = existingYaml\n  // Splice from the bottom up so earlier offsets stay valid.\n  const ranges: Array<[number, number]> = toRemove.map((item) => {\n    const keyStart = item.key!.range![0]\n    const valueEnd = item.value!.range![1]\n    const lineStart = existingYaml.lastIndexOf('\\n', keyStart - 1) + 1\n    let end = valueEnd\n    if (existingYaml.slice(end).startsWith('\\r\\n')) end += 2\n    else if (existingYaml[end] === '\\n') end += 1\n    return [lineStart, end] as [number, number]\n  })\n  ranges.sort((a, b) => b[0] - a[0])\n  for (const [start, end] of ranges) out = out.slice(0, start) + out.slice(end)\n\n  // If mcp_servers now holds nothing, drop the key itself so the config does\n  // not carry an empty managed map.\n  if (toRemove.length === mcpPair.value.items.length) {\n    const reparsed = parseDocument(out, { keepSourceTokens: true })\n    if (!reparsed.errors.length && isMap(reparsed.contents)) {\n      const pair = reparsed.contents.items.find((item) => item.key?.toString() === 'mcp_servers')\n      if (pair && pair.key?.range && pair.value?.range) {\n        const keyStart = pair.key.range[0]\n        const valueEnd = pair.value.range[1]\n        const lineStart = out.lastIndexOf('\\n', keyStart - 1) + 1\n        let end = valueEnd\n        if (out.slice(end).startsWith('\\r\\n')) end += 2\n        else if (out[end] === '\\n') end += 1\n        out = out.slice(0, lineStart) + out.slice(end)\n      }\n    }\n  }\n  return out\n}\n\n/**\n * Remove one pair's API-key assignment from Hermes's dotenv file,\n * byte-preserving every other line (#2169). The mirror of `mergeHermesEnv`.\n *\n * Returns the input unchanged when the key is absent. Refuses when the managed\n * key is ambiguous, matching `mergeHermesEnv`'s discipline — never rewrite a\n * line it cannot positively identify as ours.\n */\nexport function removeHermesEnv(existingEnv: string | null, envKey: string): string {\n  if (!existingEnv) return ''\n  const lineEnding = existingEnv.includes('\\r\\n') ? '\\r\\n' : '\\n'\n  const hasTrailingNewline = /\\r?\\n$/.test(existingEnv)\n  const lines = existingEnv.split(/\\r?\\n/)\n  if (hasTrailingNewline) lines.pop()\n\n  let removed = 0\n  const kept = lines.filter((line) => {\n    if (isHermesEnvAssignment(line, envKey)) {\n      removed += 1\n      return false\n    }\n    if (isAmbiguousHermesEnvLine(line, envKey)) {\n      throw new Error('Hermes environment contains an ambiguous managed key')\n    }\n    return true\n  })\n  if (removed === 0) return existingEnv\n  const joined = kept.join(lineEnding)\n  return hasTrailingNewline ? `${joined}${lineEnding}` : joined\n}\n\n/**\n * Remove one agent's hosted + signer entries from a JSON MCP config (Cursor,\n * VS Code, VS Code Insiders, Claude Desktop). The mirror of\n * `mergeJsonMcpConfig`; deletes only the owned names and re-serializes with\n * the writer's own 2-space style.\n */\nexport function removeJsonMcpConfig(\n  existingJson: string | null,\n  serverRoot: 'mcpServers' | 'servers',\n  names: ServerNames,\n  configPath?: string,\n): string {\n  if (!existingJson?.trim()) return existingJson ?? ''\n  const config = parseJsonObject(existingJson, configPath) as Record<string, unknown>\n  const root = config[serverRoot]\n  if (!root || typeof root !== 'object' || Array.isArray(root)) return existingJson\n  const servers = root as Record<string, unknown>\n  let removed = false\n  for (const name of [names.hosted, names.signer]) {\n    if (name in servers) {\n      delete servers[name]\n      removed = true\n    }\n  }\n  if (!removed) return existingJson\n  if (Object.keys(servers).length === 0) delete config[serverRoot]\n  return `${JSON.stringify(config, null, 2)}\\n`\n}\n\n/**\n * Remove one agent's Codex TOML tables. The mirror of `mergeCodexToml` /\n * `mergeCodexTomlHosted`, which already remove-then-append — this is the\n * remove half alone.\n */\nexport function removeCodexToml(existingToml: string, names: ServerNames): string {\n  let next = removeTomlTableTree(\n    removeTomlTableTree(existingToml, `mcp_servers.${names.codexHosted}`),\n    `mcp_servers.${names.codexSigner}`,\n  )\n  return next\n}\n\n\nfunction appendHermesMcpServers(source: string, servers: Record<string, unknown>): string {\n  const documentEnd = /(?:^|\\n)[ \\t]*\\.\\.\\.[ \\t]*(?:#[^\\n]*)?\\r?\\n?$/.exec(source)\n  if (documentEnd) {\n    const markerStart = documentEnd.index + (documentEnd[0].startsWith('\\n') ? 1 : 0)\n    const beforeMarker = source.slice(0, markerStart)\n    return `${beforeMarker}${beforeMarker.endsWith('\\n') ? '' : '\\n'}${renderHermesMcpServers(servers, '')}\\n${source.slice(markerStart)}`\n  }\n  const separator = source.endsWith('\\n') ? '' : '\\n'\n  return `${source}${separator}${renderHermesMcpServers(servers, '')}\\n`\n}\n\nfunction replaceHermesMcpServers(\n  source: string,\n  keyRange: readonly number[] | undefined,\n  valueRange: readonly number[],\n  servers: Record<string, unknown>,\n): string {\n  const valueStart = valueRange[0]\n  const valueEnd = valueRange[1]\n  const valueLineStart = source.lastIndexOf('\\n', valueStart - 1) + 1\n  const keyStartsOnValueLine = keyRange?.[0] !== undefined && keyRange[0] >= valueLineStart\n  const nestedIndent = `${source.slice(valueLineStart, keyRange?.[0] ?? valueLineStart)}  `\n\n  if (keyStartsOnValueLine) {\n    const keyStart = keyRange![0]\n    const keyEnd = keyRange![1]\n    const replacement = `${source.slice(keyStart, keyEnd)}:\\n${renderHermesMcpServerEntries(servers, nestedIndent)}`\n    const needsTrailingNewline = valueEnd < source.length && !source.slice(valueEnd).startsWith('\\n')\n    return `${source.slice(0, keyStart)}${replacement}${needsTrailingNewline ? '\\n' : ''}${source.slice(valueEnd)}`\n  }\n\n  const indent = source.slice(valueLineStart, valueStart)\n  const rendered = stringify(servers, { lineWidth: 120 }).trimEnd()\n  const replacement = rendered.split('\\n').map((line, index) => index === 0 ? line : `${indent}${line}`).join('\\n')\n  const needsTrailingNewline = valueEnd < source.length && !source.slice(valueEnd).startsWith('\\n')\n  return `${source.slice(0, valueStart)}${replacement}${needsTrailingNewline ? '\\n' : ''}${source.slice(valueEnd)}`\n}\n\nfunction replaceEmptyHermesMcpServers(\n  source: string,\n  keyRange: readonly number[] | undefined,\n  servers: Record<string, unknown>,\n): string {\n  if (!keyRange) throw new Error('Hermes config mcp_servers key is invalid')\n  const keyStart = keyRange[0]\n  const keyEnd = keyRange[1]\n  const lineStart = source.lastIndexOf('\\n', keyStart - 1) + 1\n  const lineEnd = source.indexOf('\\n', keyEnd)\n  const nestedIndent = `${source.slice(lineStart, keyStart)}  `\n  const replacement = `${source.slice(keyStart, keyEnd)}:\\n${renderHermesMcpServerEntries(servers, nestedIndent)}`\n  return `${source.slice(0, keyStart)}${replacement}${lineEnd === -1 ? '\\n' : source.slice(lineEnd)}`\n}\n\nfunction renderHermesYaml(servers: Record<string, unknown>): string {\n  return `${renderHermesMcpServers(servers, '')}\\n`\n}\n\nfunction renderHermesMcpServers(servers: Record<string, unknown>, indent: string): string {\n  return `mcp_servers:\\n${renderHermesMcpServerEntries(servers, `${indent}  `)}`\n}\n\nfunction renderHermesMcpServerEntries(servers: Record<string, unknown>, indent: string): string {\n  return stringify(servers, { lineWidth: 120 })\n    .trimEnd()\n    .split('\\n')\n    .map((line) => `${indent}${line}`)\n    .join('\\n')\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return Boolean(value) && typeof value === 'object' && !Array.isArray(value)\n}\n\nexport function mergeCodexToml(\n  existingToml: string,\n  localMcpCommand: string,\n  names: ServerNames = serverNamesFor(),\n): string {\n  let next = removeTomlTableTree(\n    removeTomlTableTree(existingToml, `mcp_servers.${names.codexHosted}`),\n    `mcp_servers.${names.codexSigner}`,\n  )\n  next = next.trimEnd()\n  const block = [\n    `[mcp_servers.${names.codexHosted}]`,\n    `command = ${tomlString(localMcpCommand)}`,\n    'args = []',\n    'startup_timeout_sec = 120',\n  ].join('\\n')\n  validateCodexToml(block, 'Generated Codex Haven config')\n  const merged = `${next ? `${next}\\n\\n` : ''}${block}\\n`\n  return merged\n}\n\nexport function mergeCodexTomlHosted(\n  existingToml: string,\n  hostedMcpUrl: string,\n  apiKey: string,\n  signerSpec: SignerLaunchSpec,\n  names: ServerNames = serverNamesFor(),\n): string {\n  let next = removeTomlTableTree(\n    removeTomlTableTree(existingToml, `mcp_servers.${names.codexHosted}`),\n    `mcp_servers.${names.codexSigner}`,\n  )\n  next = next.trimEnd()\n  const block = [\n    `[mcp_servers.${names.codexHosted}]`,\n    `url = ${tomlString(hostedMcpUrl)}`,\n    `http_headers = { \"Authorization\" = ${tomlString(`Bearer ${apiKey}`)} }`,\n    '',\n    `[mcp_servers.${names.codexSigner}]`,\n    `command = ${tomlString(signerSpec.command)}`,\n    `args = [${signerSpec.args.map((arg) => tomlString(arg)).join(', ')}]`,\n    'startup_timeout_sec = 120',\n  ].join('\\n')\n  validateCodexToml(block, 'Generated Codex Haven config')\n  const merged = `${next ? `${next}\\n\\n` : ''}${block}\\n`\n  return merged\n}\n\nasync function writeJsonRuntimeConfig(\n  input: RuntimeConfigInput,\n  target: string,\n  serverRoot: 'mcpServers' | 'servers',\n): Promise<RuntimeConfigWriteResult> {\n  try {\n    const existing = await readOptional(target)\n    const merged = mergeJsonMcpConfig(\n      existing,\n      serverRoot,\n      buildHostedServer(input.hostedMcpUrl, input.apiKey, input.runtime),\n      buildSignerServer(resolveSignerLaunchSpec(input), input.runtime),\n      serverNamesFor(input.serverName),\n      target,\n    )\n    await writeOwnerOnlyText(target, merged)\n    return {\n      hostedConfigured: true,\n      signerConfigured: true,\n      localMcpConfigured: false,\n      runtimeMcpMode: 'hosted_plus_signer',\n      target: configTargetLabel(input.runtime),\n      changed: existing !== merged,\n      restartRequired: input.runtime === 'claude-desktop',\n      messages: [`Updated Haven MCP entries in ${configTargetLabel(input.runtime)}.`],\n    }\n  } catch (err) {\n    // #1719: the parse runs BEFORE the write, so an unreadable config leaves\n    // the file untouched — no half-merged config, nothing to roll back. The\n    // separate code exists so the message can say \"fix this file\" instead of\n    // \"run setup again\", which would never succeed — this fires AFTER\n    // registerSetup consumed the one-shot setup token, so the pasted command\n    // now 409s at /resolve. `--repair` is the recovery that actually works:\n    // it rewrites this exact config from the credentials already on disk,\n    // needs no token, and mints no second agent (the #1688 orphaning a fresh\n    // connection would cause).\n    const unreadable = err instanceof UnreadableRuntimeConfigError\n    return {\n      hostedConfigured: false,\n      signerConfigured: false,\n      localMcpConfigured: false,\n      runtimeMcpMode: 'hosted_plus_signer',\n      target: configTargetLabel(input.runtime),\n      changed: false,\n      restartRequired: true,\n      messages: unreadable\n        ? [\n            `Could not update ${configTargetLabel(input.runtime)}: ${err.message}.`,\n            `Nothing was written to ${err.configPath}. Fix the JSON there (or move the file aside), then run \\`${REPAIR_COMMAND_PREFIX} ${input.runtime}\\` to write the Haven entries from the credentials already stored on this machine. Do not re-run the connector command: its setup token is already used.`,\n          ]\n        : [`Could not update ${configTargetLabel(input.runtime)}: ${err instanceof Error ? err.message : String(err)}`],\n      errorCode: unreadable ? 'runtime_config_unreadable' : 'runtime_config_write_failed',\n    }\n  }\n}\n\nasync function writeHermesConfig(input: RuntimeConfigInput, deps: RuntimeConfigWriteDeps): Promise<RuntimeConfigWriteResult> {\n  const target = hermesConfigPath(input.homeDir)\n  const envTarget = hermesEnvPath(input.homeDir)\n  try {\n    const [existing, existingEnv] = await Promise.all([readOptional(target), readOptional(envTarget)])\n    const names = serverNamesFor(input.serverName)\n    const hostedServer = {\n      ...buildHostedServer(input.hostedMcpUrl, `\\${${names.hermesEnvKey}}`, input.runtime),\n      enabled: true,\n    }\n    const signerServer = {\n      ...buildSignerServer(resolveSignerLaunchSpec(input), input.runtime),\n      enabled: true,\n    }\n    const merged = mergeHermesYaml(\n      existing,\n      hostedServer,\n      signerServer,\n      names,\n      target,\n    )\n    const mergedEnv = mergeHermesEnv(existingEnv, input.apiKey, names.hermesEnvKey)\n    const writeText = deps.writeOwnerOnlyText ?? writeOwnerOnlyText\n    await writeText(envTarget, mergedEnv)\n    try {\n      await writeText(target, merged)\n    } catch (err) {\n      const recovered = await restoreHermesFiles(target, existing, envTarget, existingEnv, writeText)\n      if (!recovered) throw new HermesConfigRecoveryError()\n      throw err\n    }\n    return {\n      hostedConfigured: true,\n      signerConfigured: true,\n      localMcpConfigured: false,\n      runtimeMcpMode: 'hosted_plus_signer',\n      target: 'Hermes Agent config',\n      changed: existing !== merged || existingEnv !== mergedEnv,\n      restartRequired: true,\n      messages: [\n        `Updated Haven MCP entries in ${target}; stored the hosted MCP identity in ${envTarget}.`,\n        // #3737: name the pair actually written — a bare run prints exactly the\n        // historical sentence; a named run names its own pair.\n        `Restart Hermes (start a new session; gateway users: /restart), then verify with \\`hermes mcp list\\`, \\`hermes mcp test ${names.hosted}\\`, and \\`hermes mcp test ${names.signer}\\`.`,\n        'If several long-lived Hermes processes are running (a gateway plus TUI workers), restart EVERY one: each loads its MCP wiring at startup, so a process started before this setup keeps using its old snapshot.',\n        'If no mcp_* tools appear after restart, ensure the MCP SDK is installed in Hermes: pip install mcp',\n      ],\n    }\n  } catch (err) {\n    const recoveryIncomplete = err instanceof HermesConfigRecoveryError\n    const unreadable = err instanceof UnreadableRuntimeConfigError\n    return {\n      hostedConfigured: false,\n      signerConfigured: false,\n      localMcpConfigured: false,\n      runtimeMcpMode: 'hosted_plus_signer',\n      target: 'Hermes Agent config',\n      changed: false,\n      restartRequired: true,\n      messages: unreadable\n        ? [\n            `Could not update Hermes Agent config: ${err.message}.`,\n            `Nothing was written to ${err.configPath}. Fix the YAML there (or move the file aside), then run \\`${REPAIR_COMMAND_PREFIX} hermes\\` to write the Haven entries from the credentials already stored on this machine. Do not re-run the connector command: its setup token is already used.`,\n          ]\n        : [recoveryIncomplete\n          ? 'Could not update Hermes Agent config. Recovery did not complete; inspect the Hermes configuration before retrying.'\n          : 'Could not update Hermes Agent config. Existing configuration was left unchanged.'],\n      errorCode: unreadable ? 'runtime_config_unreadable' : 'runtime_config_write_failed',\n    }\n  }\n}\n\nasync function restoreHermesFiles(\n  configPath: string,\n  existingConfig: string | null,\n  envPath: string,\n  existingEnv: string | null,\n  writeText: (path: string, value: string) => Promise<void>,\n): Promise<boolean> {\n  const [envResult, configResult] = await Promise.allSettled([\n    restoreOptionalText(envPath, existingEnv, writeText),\n    restoreOptionalText(configPath, existingConfig, writeText),\n  ])\n  return envResult.status === 'fulfilled' && configResult.status === 'fulfilled'\n}\n\nasync function restoreOptionalText(\n  path: string,\n  existing: string | null,\n  writeText: (path: string, value: string) => Promise<void>,\n): Promise<void> {\n  if (existing !== null) {\n    await writeText(path, existing)\n    return\n  }\n  try {\n    await unlink(path)\n  } catch (err) {\n    if (err && typeof err === 'object' && 'code' in err && err.code === 'ENOENT') return\n    throw err\n  }\n}\n\nasync function writeCodexConfig(input: RuntimeConfigInput): Promise<RuntimeConfigWriteResult> {\n  const target = codexConfigPath(input.homeDir)\n  const local = input.mode === 'local'\n  try {\n    const existing = await readOptional(target)\n    if (local) {\n      if (!input.localMcpCommand) {\n        throw new Error('local MCP wrapper command is required')\n      }\n      const merged = mergeCodexToml(existing ?? '', input.localMcpCommand, serverNamesFor(input.serverName))\n      await writeOwnerOnlyText(target, merged)\n      return {\n        hostedConfigured: false,\n        signerConfigured: true,\n        localMcpConfigured: true,\n        runtimeMcpMode: 'local_stdio',\n        target: configTargetLabel(input.runtime),\n        changed: existing !== merged,\n        restartRequired: true,\n        messages: [\n          `Updated local Haven MCP entry in ${configTargetLabel(input.runtime)}.`,\n        ],\n      }\n    }\n    const merged = mergeCodexTomlHosted(\n      existing ?? '',\n      input.hostedMcpUrl,\n      input.apiKey,\n      resolveSignerLaunchSpec(input),\n      serverNamesFor(input.serverName),\n    )\n    await writeOwnerOnlyText(target, merged)\n    return {\n      hostedConfigured: true,\n      signerConfigured: true,\n      localMcpConfigured: false,\n      runtimeMcpMode: 'hosted_plus_signer',\n      target: configTargetLabel(input.runtime),\n      changed: existing !== merged,\n      restartRequired: true,\n      messages: [\n        `Updated Haven MCP entries in ${configTargetLabel(input.runtime)}.`,\n      ],\n    }\n  } catch (err) {\n    const invalidToml = err instanceof InvalidCodexTomlError\n    return {\n      hostedConfigured: false,\n      signerConfigured: false,\n      localMcpConfigured: false,\n      runtimeMcpMode: local ? 'local_stdio' : 'hosted_plus_signer',\n      target: configTargetLabel(input.runtime),\n      changed: false,\n      restartRequired: true,\n      messages: [`Could not update ${configTargetLabel(input.runtime)}: ${err instanceof Error ? err.message : String(err)}`],\n      errorCode: invalidToml ? 'codex_config_invalid' : 'runtime_config_write_failed',\n    }\n  }\n}\n\nasync function readOptional(path: string): Promise<string | null> {\n  try {\n    return await readFile(path, 'utf8')\n  } catch (err) {\n    if (err && typeof err === 'object' && 'code' in err && err.code === 'ENOENT') return null\n    throw err\n  }\n}\n\nasync function writeOwnerOnlyText(path: string, value: string): Promise<void> {\n  await mkdir(dirname(path), { recursive: true, mode: 0o700 })\n  await writeFile(path, value, { mode: 0o600 })\n  await chmod(path, 0o600).catch(() => undefined)\n}\n\nfunction parseJsonObject(value: string, configPath?: string): Record<string, unknown> {\n  let parsed: unknown\n  try {\n    parsed = JSON.parse(value) as unknown\n  } catch {\n    // The parser's own message is deliberately dropped: V8's SyntaxError text\n    // quotes the offending source, and this file may hold ANOTHER MCP server's\n    // bearer token. The path plus \"not valid JSON\" is everything the user\n    // needs, and nothing they must not see in a log.\n    throw new UnreadableRuntimeConfigError(configPath ?? 'the runtime config', 'it is not valid JSON')\n  }\n  if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n    throw new UnreadableRuntimeConfigError(configPath ?? 'the runtime config', 'the top level is not a JSON object')\n  }\n  return parsed as Record<string, unknown>\n}\n\nfunction removeTomlTableTree(toml: string, table: string): string {\n  const lines = toml.split(/\\r?\\n/)\n  const kept: string[] = []\n  let skipping = false\n  for (const line of lines) {\n    const trimmed = line.trim()\n    const tableName = tomlTableName(trimmed)\n    if (tableName) {\n      skipping = tableName === table || tableName.startsWith(`${table}.`)\n      if (skipping) continue\n    }\n    if (!skipping) kept.push(line)\n  }\n  return kept.join('\\n')\n}\n\nfunction tomlTableName(line: string): string | null {\n  if (line.startsWith('[[') && line.endsWith(']]')) return line.slice(2, -2).trim()\n  if (line.startsWith('[') && line.endsWith(']')) return line.slice(1, -1).trim()\n  return null\n}\n\nexport function validateCodexToml(toml: string, label = 'Codex config'): void {\n  const lines = toml.split(/\\r?\\n/)\n  let pendingValue: { value: string; line: number } | null = null\n  for (let index = 0; index < lines.length; index += 1) {\n    const raw = lines[index]\n    const line = stripTomlComment(raw).trim()\n    if (!line) continue\n\n    if (pendingValue) {\n      pendingValue.value = `${pendingValue.value}\\n${line}`\n      if (hasBalancedTomlContainers(pendingValue.value)) {\n        if (!isTomlValue(pendingValue.value)) {\n          throw new InvalidCodexTomlError(`${label} has invalid TOML near line ${pendingValue.line}.`)\n        }\n        pendingValue = null\n      }\n      continue\n    }\n\n    if (isTomlTable(line)) continue\n\n    const equalsIndex = line.indexOf('=')\n    if (equalsIndex <= 0) {\n      throw new InvalidCodexTomlError(`${label} has invalid TOML near line ${index + 1}.`)\n    }\n\n    const key = line.slice(0, equalsIndex).trim()\n    const value = line.slice(equalsIndex + 1).trim()\n    if (!isTomlKey(key)) {\n      throw new InvalidCodexTomlError(`${label} has invalid TOML near line ${index + 1}.`)\n    }\n    if (startsTomlContainer(value) && !hasBalancedTomlContainers(value)) {\n      pendingValue = { value, line: index + 1 }\n      continue\n    }\n    if (!isTomlValue(value)) {\n      throw new InvalidCodexTomlError(`${label} has invalid TOML near line ${index + 1}.`)\n    }\n  }\n  if (pendingValue) {\n    throw new InvalidCodexTomlError(`${label} has invalid TOML near line ${pendingValue.line}.`)\n  }\n}\n\nfunction isTomlTable(line: string): boolean {\n  const table = tomlTableName(line)\n  return Boolean(table && splitTomlDottedKey(table).every(isTomlKeyPart))\n}\n\nfunction isTomlKey(value: string): boolean {\n  return splitTomlDottedKey(value).every(isTomlKeyPart)\n}\n\nfunction splitTomlDottedKey(value: string): string[] {\n  const parts: string[] = []\n  let current = ''\n  let quote: '\"' | \"'\" | null = null\n  let escaped = false\n  for (let i = 0; i < value.length; i += 1) {\n    const char = value[i]\n    if (quote) {\n      current += char\n      if (quote === '\"' && char === '\\\\' && !escaped) {\n        escaped = true\n        continue\n      }\n      if (char === quote && !escaped) quote = null\n      escaped = false\n      continue\n    }\n    if (char === '\"' || char === \"'\") {\n      quote = char\n      current += char\n      continue\n    }\n    if (char === '.') {\n      parts.push(current.trim())\n      current = ''\n      continue\n    }\n    current += char\n  }\n  parts.push(current.trim())\n  return quote ? [] : parts\n}\n\nfunction isTomlKeyPart(value: string): boolean {\n  return isTomlBareKey(value) || isTomlQuotedString(value)\n}\n\nfunction isTomlBareKey(value: string): boolean {\n  return /^[A-Za-z0-9_-]+$/.test(value)\n}\n\nfunction isTomlValue(value: string): boolean {\n  if (!value) return false\n  if (isTomlQuotedString(value)) return true\n  if (/^(true|false)$/i.test(value)) return true\n  if (/^[+-]?(?:inf|nan)$/i.test(value)) return true\n  if (/^[+-]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]+)?(?:[eE][+-]?[0-9_]+)?$/.test(value)) return true\n  if (/^\\d{4}-\\d{2}-\\d{2}(?:[Tt ][0-9:.+-Zz]+)?$/.test(value)) return true\n  if ((value.startsWith('[') && value.endsWith(']')) || (value.startsWith('{') && value.endsWith('}'))) {\n    return hasBalancedTomlContainers(value)\n  }\n  return false\n}\n\nfunction startsTomlContainer(value: string): boolean {\n  return value.startsWith('[') || value.startsWith('{')\n}\n\nfunction isTomlQuotedString(value: string): boolean {\n  if (value.startsWith('\"\"\"') || value.startsWith(\"'''\")) {\n    const marker = value.slice(0, 3)\n    return value.length >= 6 && value.endsWith(marker)\n  }\n  if ((!value.startsWith('\"') || !value.endsWith('\"')) && (!value.startsWith(\"'\") || !value.endsWith(\"'\"))) {\n    return false\n  }\n  return hasBalancedTomlContainers(value)\n}\n\nfunction stripTomlComment(value: string): string {\n  let quote: '\"' | \"'\" | null = null\n  let escaped = false\n  for (let i = 0; i < value.length; i += 1) {\n    const char = value[i]\n    if (quote) {\n      if (quote === '\"' && char === '\\\\' && !escaped) {\n        escaped = true\n        continue\n      }\n      if (char === quote && !escaped) quote = null\n      escaped = false\n      continue\n    }\n    if (char === '\"' || char === \"'\") {\n      quote = char\n      continue\n    }\n    if (char === '#') return value.slice(0, i)\n  }\n  return value\n}\n\nfunction hasBalancedTomlContainers(value: string): boolean {\n  const stack: string[] = []\n  let quote: '\"' | \"'\" | null = null\n  let escaped = false\n  for (let i = 0; i < value.length; i += 1) {\n    const char = value[i]\n    if (quote) {\n      if (quote === '\"' && char === '\\\\' && !escaped) {\n        escaped = true\n        continue\n      }\n      if (char === quote && !escaped) quote = null\n      escaped = false\n      continue\n    }\n    if (char === '\"' || char === \"'\") {\n      quote = char\n      continue\n    }\n    if (char === '[' || char === '{') {\n      stack.push(char)\n      continue\n    }\n    if (char === ']') {\n      if (stack.pop() !== '[') return false\n      continue\n    }\n    if (char === '}') {\n      if (stack.pop() !== '{') return false\n    }\n  }\n  return stack.length === 0 && quote === null\n}\n\nfunction tomlString(value: string): string {\n  return `\"${value.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"')}\"`\n}\n\n/**\n * #1589: the doctor needs to READ the config the writers write. One resolver,\n * next to the path functions themselves so a new runtime cannot be added\n * without the doctor seeing it (returns null for runtimes without a\n * file-based config this module owns, e.g. claude-code via the CLI).\n */\nexport function runtimeConfigPathFor(runtime: string, homeDir = homedir()): string | null {\n  switch (runtime) {\n    case 'cursor':\n      return cursorConfigPath(homeDir)\n    case 'codex-cli':\n    case 'codex-desktop':\n      return codexConfigPath(homeDir)\n    case 'vscode':\n      return vscodeConfigPath(homeDir)\n    case 'vscode-insiders':\n      return vscodeInsidersConfigPath(homeDir)\n    case 'claude-desktop':\n      return claudeDesktopConfigPath(homeDir)\n    case 'hermes':\n      return hermesConfigPath(homeDir)\n    default:\n      return null\n  }\n}\n\nfunction cursorConfigPath(homeDir = homedir()): string {\n  return resolve(homeDir, '.cursor', 'mcp.json')\n}\n\nfunction codexConfigPath(homeDir = homedir()): string {\n  return resolve(homeDir, '.codex', 'config.toml')\n}\n\nfunction vscodeConfigPath(homeDir = homedir()): string {\n  if (platform() === 'darwin') return resolve(homeDir, 'Library', 'Application Support', 'Code', 'User', 'mcp.json')\n  if (platform() === 'win32') {\n    return resolve(process.env.APPDATA ?? join(homeDir, 'AppData', 'Roaming'), 'Code', 'User', 'mcp.json')\n  }\n  return resolve(homeDir, '.config', 'Code', 'User', 'mcp.json')\n}\n\nfunction vscodeInsidersConfigPath(homeDir = homedir()): string {\n  if (platform() === 'darwin') return resolve(homeDir, 'Library', 'Application Support', 'Code - Insiders', 'User', 'mcp.json')\n  if (platform() === 'win32') {\n    return resolve(process.env.APPDATA ?? join(homeDir, 'AppData', 'Roaming'), 'Code - Insiders', 'User', 'mcp.json')\n  }\n  return resolve(homeDir, '.config', 'Code - Insiders', 'User', 'mcp.json')\n}\n\nfunction claudeDesktopConfigPath(homeDir = homedir()): string {\n  if (platform() === 'darwin') {\n    return resolve(homeDir, 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json')\n  }\n  if (platform() === 'win32') {\n    return resolve(process.env.APPDATA ?? join(homeDir, 'AppData', 'Roaming'), 'Claude', 'claude_desktop_config.json')\n  }\n  return resolve(homeDir, '.config', 'Claude', 'claude_desktop_config.json')\n}\n\nexport function hermesConfigPath(homeDir?: string): string {\n  return join(hermesHomePath(homeDir), 'config.yaml')\n}\n\nexport function hermesEnvPath(homeDir?: string): string {\n  return join(hermesHomePath(homeDir), '.env')\n}\n\nfunction hermesHomePath(homeDir?: string): string {\n  return process.env.HERMES_HOME ?? join(homeDir ?? homedir(), '.hermes')\n}\n\nfunction configTargetLabel(runtime: RuntimeId): string {\n  switch (runtime) {\n    case 'codex-cli':\n      return 'Codex CLI config'\n    case 'codex-desktop':\n      return 'Codex Desktop config'\n    case 'cursor':\n      return 'Cursor MCP config'\n    case 'vscode':\n      return 'VS Code MCP config'\n    case 'vscode-insiders':\n      return 'VS Code Insiders MCP config'\n    case 'claude-desktop':\n      return 'Claude Desktop config'\n    default:\n      return 'runtime MCP config'\n  }\n}\n","import { readFile } from 'node:fs/promises'\nimport { resolve } from 'node:path'\nimport {\n  computeConsentHash,\n  consentInputFromClient,\n  ensureConsent,\n  loadCredentials,\n  registeredToolNames,\n  type ConsentDecision,\n} from '@haven_ai/mcp'\n\nexport interface LocalMcpConsentStatus {\n  acknowledged: boolean\n  hash?: string\n  reason?: ConsentDecision['reason'] | 'ack_file_missing' | 'ack_file_mismatch'\n  error?: string\n}\n\nexport async function acknowledgeLocalMcpConsent(\n  identityPath: string,\n  signerPath: string,\n  log?: (message: string) => void,\n): Promise<LocalMcpConsentStatus> {\n  try {\n    const input = await buildLocalMcpConsentInput(identityPath, signerPath)\n    const decision = await ensureConsent(input, {\n      credentialsPath: identityPath,\n      writeAck: true,\n      out: log ? { write: (chunk) => writeLogChunk(log, chunk) } : undefined,\n    })\n    return {\n      acknowledged: decision.ok,\n      hash: decision.hash,\n      reason: decision.reason,\n    }\n  } catch (err) {\n    return {\n      acknowledged: false,\n      error: err instanceof Error ? err.message : String(err),\n    }\n  }\n}\n\nexport async function getLocalMcpConsentStatus(\n  identityPath: string,\n  signerPath: string,\n): Promise<LocalMcpConsentStatus> {\n  try {\n    const input = await buildLocalMcpConsentInput(identityPath, signerPath)\n    const hash = computeConsentHash(input)\n    const stored = await readLocalMcpAckFile(localMcpAckPath(identityPath))\n    if (stored === hash) {\n      return { acknowledged: true, hash, reason: 'ack_file_match' }\n    }\n    return {\n      acknowledged: false,\n      hash,\n      reason: stored ? 'ack_file_mismatch' : 'ack_file_missing',\n    }\n  } catch (err) {\n    return {\n      acknowledged: false,\n      error: err instanceof Error ? err.message : String(err),\n    }\n  }\n}\n\nexport function localMcpAckPath(identityPath: string): string {\n  return resolve(`${identityPath}.ack.json`)\n}\n\nasync function buildLocalMcpConsentInput(identityPath: string, signerPath: string) {\n  const credentials = await loadCredentials({ identityPath, signerPath })\n  const unavailableDuringSetup = {\n    getAllowances: async () => {\n      throw new Error('Haven approval is not complete yet.')\n    },\n  }\n  return consentInputFromClient(\n    unavailableDuringSetup as never,\n    {\n      apiKey: credentials.apiKey,\n      apiUrl: credentials.apiUrl,\n      agentId: credentials.agentId,\n      accountAddress: credentials.accountAddress,\n      delegateAddress: credentials.delegateAddress,\n      chainId: credentials.chainId,\n      allowanceSummary: credentials.allowanceSummary,\n    },\n    registeredToolNames(),\n  )\n}\n\nasync function readLocalMcpAckFile(path: string): Promise<string | null> {\n  try {\n    const parsed = JSON.parse(await readFile(path, 'utf8')) as { ack?: unknown }\n    return typeof parsed.ack === 'string' ? parsed.ack : null\n  } catch {\n    return null\n  }\n}\n\nfunction writeLogChunk(log: (message: string) => void, chunk: string): void {\n  const message = String(chunk).trimEnd()\n  if (message) log(message)\n}\n","import { spawn } from 'node:child_process'\nimport { readFile } from 'node:fs/promises'\n\nexport type HostedProbeStatus = 'ok' | 'unauthorized' | 'network_error' | 'bad_response'\n\nexport interface HostedProbeResult {\n  status: HostedProbeStatus\n  toolCount?: number\n}\n\n/**\n * #1697: who does this API key actually authenticate as?\n *\n * The #1681 incident was only provable by hand: cross-checking the delegate\n * address a live session reported against the `signer.json` on disk, a check\n * nothing in the product performed. This is the knowable half — the doctor\n * still cannot see inside a running host, but it CAN prove that the stored\n * API key and the stored signing key belong to the same agent. The key read\n * here is the same one the hosted MCP entry carries, which is what makes the\n * comparison meaningful rather than incidental.\n *\n * Read-only: a GET of the agent's own identity, nothing else.\n */\nexport interface HostedIdentityProbeResult {\n  status: HostedProbeStatus\n  agentId?: string\n  delegateAddress?: string\n}\n\nexport async function probeHostedAgentIdentity(\n  apiKey: string,\n  apiUrl: string,\n  fetchImpl: typeof fetch = fetch,\n): Promise<HostedIdentityProbeResult> {\n  let response: Response\n  try {\n    response = await fetchWithTimeout(fetchImpl, `${apiUrl.replace(/\\/+$/, '')}/machine-payments/agent`, {\n      method: 'GET',\n      headers: { Authorization: `Bearer ${apiKey}`, Accept: 'application/json' },\n    })\n  } catch {\n    return { status: 'network_error' }\n  }\n  if (response.status === 401 || response.status === 403) return { status: 'unauthorized' }\n  if (!response.ok) return { status: 'bad_response' }\n  try {\n    const payload = JSON.parse(await response.text()) as { id?: string; delegate_address?: string }\n    if (typeof payload?.delegate_address !== 'string') return { status: 'bad_response' }\n    return { status: 'ok', agentId: payload.id, delegateAddress: payload.delegate_address }\n  } catch {\n    return { status: 'bad_response' }\n  }\n}\n\nexport type LocalMcpProbeStatus = 'ok' | 'timeout' | 'process_error' | 'bad_response' | 'missing_tools'\n\nexport interface LocalMcpProbeResult {\n  status: LocalMcpProbeStatus\n  /** #1589: the initialize response's serverInfo/capabilities, when reached —\n   *  the doctor reports the signer's advertised compat versions from here\n   *  instead of a second probe call. */\n  serverInfo?: { name?: string; version?: string }\n  capabilities?: Record<string, unknown>\n  toolNames?: string[]\n}\n\nexport async function probeHostedMcpTools(\n  apiKey: string,\n  hostedMcpUrl: string,\n  fetchImpl: typeof fetch = fetch,\n): Promise<HostedProbeResult> {\n  let response: Response\n  try {\n    response = await fetchWithTimeout(fetchImpl, hostedMcpUrl, {\n      method: 'POST',\n      headers: {\n        Authorization: `Bearer ${apiKey}`,\n        'Content-Type': 'application/json',\n        Accept: 'application/json, text/event-stream',\n      },\n      body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' }),\n    })\n  } catch {\n    return { status: 'network_error' }\n  }\n\n  if (response.status === 401 || response.status === 403) return { status: 'unauthorized' }\n  if (!response.ok) return { status: 'bad_response' }\n\n  try {\n    const payload = parseJsonRpcPayload(await response.text())\n    if (!payload || payload.error) return { status: 'bad_response' }\n    const tools = (payload.result as { tools?: unknown[] } | undefined)?.tools\n    return { status: 'ok', toolCount: Array.isArray(tools) ? tools.length : undefined }\n  } catch {\n    return { status: 'bad_response' }\n  }\n}\n\nexport async function probeLocalSignerCredential(signerPath: string): Promise<boolean> {\n  try {\n    const parsed = JSON.parse(await readFile(signerPath, 'utf8')) as unknown\n    return Boolean(\n      parsed &&\n        typeof parsed === 'object' &&\n        'delegate_key' in parsed &&\n        typeof (parsed as { delegate_key?: unknown }).delegate_key === 'string',\n    )\n  } catch {\n    return false\n  }\n}\n\nexport async function probeLocalMcpTools(\n  command: string,\n  args: string[],\n  requiredTools: readonly string[],\n  timeoutMs = 10_000,\n): Promise<LocalMcpProbeResult> {\n  return new Promise((resolve) => {\n    const child = spawn(command, args, { stdio: ['pipe', 'pipe', 'ignore'] })\n    let stdout = ''\n    let settled = false\n    let sawInitialize = false\n    let serverInfo: { name?: string; version?: string } | undefined\n    let capabilities: Record<string, unknown> | undefined\n\n    const finish = (result: LocalMcpProbeResult): void => {\n      if (settled) return\n      settled = true\n      clearTimeout(timeout)\n      child.kill()\n      resolve(result)\n    }\n\n    const timeout = setTimeout(() => finish({ status: 'timeout' }), timeoutMs)\n\n    child.on('error', () => finish({ status: 'process_error' }))\n    child.on('exit', (code) => {\n      if (!settled && code !== 0) finish({ status: 'process_error' })\n    })\n    child.stdout.on('data', (chunk: Buffer) => {\n      stdout += chunk.toString('utf8')\n      const lines = stdout.split(/\\r?\\n/)\n      stdout = lines.pop() ?? ''\n      for (const line of lines) {\n        const trimmed = line.trim()\n        if (!trimmed) continue\n        let payload: JsonRpcEnvelope & { id?: number }\n        try {\n          payload = JSON.parse(trimmed) as JsonRpcEnvelope & { id?: number }\n        } catch {\n          continue\n        }\n        if (payload.error) {\n          finish({ status: 'bad_response' })\n          return\n        }\n        if (payload.id === 1 && !sawInitialize) {\n          sawInitialize = true\n          const init = payload.result as\n            | { serverInfo?: { name?: string; version?: string }; capabilities?: Record<string, unknown> }\n            | undefined\n          serverInfo = init?.serverInfo\n          capabilities = init?.capabilities\n          writeJsonRpc(child, { jsonrpc: '2.0', method: 'notifications/initialized', params: {} })\n          writeJsonRpc(child, { jsonrpc: '2.0', id: 2, method: 'tools/list', params: {} })\n          continue\n        }\n        if (payload.id === 2) {\n          const tools = (payload.result as { tools?: unknown[] } | undefined)?.tools\n          const toolNames = Array.isArray(tools)\n            ? tools\n                .map((tool) => tool && typeof tool === 'object' && 'name' in tool ? (tool as { name?: unknown }).name : undefined)\n                .filter((name): name is string => typeof name === 'string')\n            : []\n          const missing = requiredTools.filter((name) => !toolNames.includes(name))\n          finish({ status: missing.length === 0 ? 'ok' : 'missing_tools', toolNames, serverInfo, capabilities })\n          return\n        }\n      }\n    })\n\n    writeJsonRpc(child, {\n      jsonrpc: '2.0',\n      id: 1,\n      method: 'initialize',\n      params: {\n        protocolVersion: '2025-06-18',\n        capabilities: {},\n        clientInfo: { name: 'haven-connect-probe', version: '0.0.0' },\n      },\n    })\n  })\n}\n\ninterface JsonRpcEnvelope {\n  result?: unknown\n  error?: unknown\n}\n\nfunction writeJsonRpc(child: ReturnType<typeof spawn>, payload: Record<string, unknown>): void {\n  child.stdin?.write(`${JSON.stringify(payload)}\\n`)\n}\n\nfunction parseJsonRpcPayload(raw: string): JsonRpcEnvelope | null {\n  const trimmed = raw.trim()\n  if (!trimmed) return null\n  if (trimmed.startsWith('{')) {\n    try {\n      return JSON.parse(trimmed) as JsonRpcEnvelope\n    } catch {\n      return null\n    }\n  }\n  const dataLines = trimmed\n    .split(/\\r?\\n/)\n    .filter((line) => line.startsWith('data:'))\n    .map((line) => line.slice(5).trim())\n  for (let i = dataLines.length - 1; i >= 0; i -= 1) {\n    try {\n      return JSON.parse(dataLines[i]) as JsonRpcEnvelope\n    } catch {\n      /* try previous SSE frame */\n    }\n  }\n  return null\n}\n\nasync function fetchWithTimeout(fetchImpl: typeof fetch, url: string, init: RequestInit): Promise<Response> {\n  const controller = new AbortController()\n  const timeout = setTimeout(() => controller.abort(), 3000)\n  try {\n    return await fetchImpl(url, { ...init, signal: controller.signal })\n  } finally {\n    clearTimeout(timeout)\n  }\n}\n","import { execFile } from 'node:child_process'\nimport { access, chmod, mkdir, readFile, writeFile } from 'node:fs/promises'\nimport { homedir } from 'node:os'\nimport { dirname, join, resolve } from 'node:path'\nimport { promisify } from 'node:util'\nimport { isSupportedNodeVersion, unsupportedNodeVersionMessage } from '@haven_ai/sdk'\nimport { SIGNER_INSTALL_HEARTBEAT_MS, SIGNER_INSTALL_TIMEOUT_MS } from './signer-runtime.js'\nimport {\n  MCP_RUNTIME_MANIFEST,\n  mcpPackageSpec,\n  sdkPackageSpec,\n} from './runtime-manifest.js'\nimport {\n  describeRuntimeSpecOverride,\n  overrideApplies,\n  resolveRuntimeSpecOverride,\n  runtimeSpecOverrideDirectoryKey,\n  runtimeSpecOverrideNotice,\n  type RuntimeSpecOverride,\n  type RuntimeSpecOverrideRecord,\n} from './runtime-spec-override.js'\n\nconst execFileAsync = promisify(execFile)\n\nexport interface PrepareLocalMcpRuntimeInput {\n  credentialDirectory: string\n  identityPath: string\n  signerPath: string\n  homeDir?: string\n  nodeVersion?: string\n  /** #1696: wiring slug, recorded in the sidecar for per-agent inventory (#1697). */\n  serverName?: string\n}\n\nexport interface PreparedLocalMcpRuntime {\n  command: string\n  args: string[]\n  wrapperPath: string\n  runtimeDirectory: string\n  npmCacheDirectory: string\n  cliPath: string\n  messages: string[]\n  /** #2424: present only when the install ran under a runtime-spec override. */\n  runtimeSpecOverride?: RuntimeSpecOverrideRecord\n}\n\nexport interface LocalMcpRuntimeDeps {\n  runCommand?: (command: string, args: string[]) => Promise<void>\n  /** Install progress heartbeat, mirrored from the signer runtime (#1586/#1593). */\n  onProgress?: (message: string) => void\n  /** #2424: where `HAVEN_MCP_SPEC` / `HAVEN_SDK_SPEC` are read from; defaults to `process.env`. */\n  env?: NodeJS.ProcessEnv\n}\n\n/**\n * Raised when the running Node is below the floor every Haven package declares.\n *\n * The `code` is load-bearing: `runtime-install.ts` maps it to the\n * `local_stdio_mcp_unsupported_node_version` probe result, and Haven's install\n * telemetry has been recording that string since the local path shipped. Kept\n * verbatim even though the guard is no longer local-MCP-only (#1161), because\n * renaming it would silently split one condition across two codes in the\n * historical data.\n */\nexport class UnsupportedNodeVersionError extends Error {\n  readonly code = 'local_mcp_unsupported_node_version'\n  readonly nodeVersion: string\n  readonly minimumNodeVersion: string\n\n  constructor(nodeVersion: string, minimumNodeVersion: string, subject = 'Haven setup') {\n    super(unsupportedNodeVersionMessage({ subject, nodeVersion, minimumNodeVersion }))\n    this.name = 'UnsupportedNodeVersionError'\n    this.nodeVersion = nodeVersion\n    this.minimumNodeVersion = minimumNodeVersion\n  }\n}\n\nexport async function prepareLocalMcpRuntime(\n  input: PrepareLocalMcpRuntimeInput,\n  deps: LocalMcpRuntimeDeps = {},\n): Promise<PreparedLocalMcpRuntime> {\n  assertSupportedNodeVersion(input.nodeVersion)\n\n  const homeDir = input.homeDir ?? homedir()\n  // #2424: mirrors prepareSignerRuntime — resolved before any side effect, a\n  // hash-keyed directory under an override, never reused, printed loudly.\n  const override = resolveLocalMcpRuntimeOverride(deps.env ?? process.env)\n  const mcpSpec = override?.mcp ?? mcpPackageSpec()\n  const sdkSpec = override?.sdk ?? sdkPackageSpec()\n  const resolvedSpecs = [mcpSpec, sdkSpec]\n  const overrideRecord: RuntimeSpecOverrideRecord | undefined = override\n    ? { specs: override, resolved_specs: resolvedSpecs, directory_key: runtimeSpecOverrideDirectoryKey(resolvedSpecs) }\n    : undefined\n  const runtimeDirectory = resolve(\n    homeDir,\n    '.haven',\n    'mcp-runtime',\n    overrideRecord ? overrideRecord.directory_key : MCP_RUNTIME_MANIFEST.mcpVersion,\n  )\n  const npmCacheDirectory = resolve(homeDir, '.haven', 'npm-cache')\n  const cliPath = join(runtimeDirectory, 'node_modules', '@haven_ai', 'mcp', 'dist', 'cli.js')\n  const messages: string[] = []\n\n  if (override) {\n    messages.push(...runtimeSpecOverrideNotice(\n      'MCP runtime',\n      override,\n      { mcp: mcpPackageSpec(), sdk: sdkPackageSpec() },\n      runtimeDirectory,\n    ))\n  }\n\n  await mkdir(runtimeDirectory, { recursive: true, mode: 0o700 })\n  await chmod(runtimeDirectory, 0o700).catch(() => undefined)\n  await mkdir(npmCacheDirectory, { recursive: true, mode: 0o700 })\n  await chmod(npmCacheDirectory, 0o700).catch(() => undefined)\n\n  if (override) {\n    await installRuntimePackages(runtimeDirectory, npmCacheDirectory, resolvedSpecs, deps)\n    messages.push(`Installed local Haven MCP runtime from override (${resolvedSpecs.join(' ')}).`)\n  } else if (await installedRuntimeMatches(runtimeDirectory, cliPath)) {\n    messages.push(`Using existing local Haven MCP runtime ${mcpPackageSpec()}.`)\n  } else {\n    await installRuntimePackages(runtimeDirectory, npmCacheDirectory, resolvedSpecs, deps)\n    messages.push(`Installed local Haven MCP runtime ${mcpPackageSpec()}.`)\n  }\n\n  await assertFileExists(cliPath, 'local Haven MCP CLI')\n  const installedVersions = override ? await readInstalledVersions(runtimeDirectory) : undefined\n\n  const wrapperPath = join(input.credentialDirectory, 'bin', 'haven-mcp')\n  await writeWrapper({\n    wrapperPath,\n    cliPath,\n    identityPath: input.identityPath,\n    signerPath: input.signerPath,\n    overrideComment: override ? describeRuntimeSpecOverride(override) : undefined,\n  })\n\n  await writeRuntimeSidecar({\n    path: join(input.credentialDirectory, 'mcp-runtime.json'),\n    wrapperPath,\n    runtimeDirectory,\n    npmCacheDirectory,\n    cliPath,\n    serverName: input.serverName,\n    override: overrideRecord,\n    installedVersions,\n  })\n\n  messages.push(`Prepared stable local Haven MCP wrapper: ${wrapperPath}`)\n\n  return {\n    command: wrapperPath,\n    args: [],\n    wrapperPath,\n    runtimeDirectory,\n    npmCacheDirectory,\n    cliPath,\n    messages,\n    ...(overrideRecord ? { runtimeSpecOverride: overrideRecord } : {}),\n  }\n}\n\n/**\n * Refuse to proceed on an unsupported Node.\n *\n * Called from BOTH connect paths since #1161: `runConnect` runs it before any\n * side effect on the default (hosted MCP + local signer) topology, and\n * `prepareLocalMcpRuntime` keeps its own call for the `--local` path. It used to\n * exist only on the latter — the path almost nobody takes — so the documented\n * floor was enforced where it mattered least.\n */\nexport function assertSupportedNodeVersion(\n  nodeVersion = process.versions.node,\n  minimumNodeVersion = MCP_RUNTIME_MANIFEST.minimumNodeVersion,\n  subject = 'Haven setup',\n): void {\n  if (!isSupportedNodeVersion(nodeVersion, minimumNodeVersion)) {\n    throw new UnsupportedNodeVersionError(nodeVersion, minimumNodeVersion, subject)\n  }\n}\n\n/** The `--local` runtime's slice of the override: `mcp` and `sdk`; a lone `HAVEN_SIGNER_SPEC` is not its business. */\nfunction resolveLocalMcpRuntimeOverride(env: NodeJS.ProcessEnv): RuntimeSpecOverride | undefined {\n  const override = resolveRuntimeSpecOverride(env)\n  if (!overrideApplies(override, ['mcp', 'sdk'])) return undefined\n  const { mcp, sdk } = override\n  return { ...(mcp !== undefined ? { mcp } : {}), ...(sdk !== undefined ? { sdk } : {}) }\n}\n\nasync function installRuntimePackages(\n  runtimeDirectory: string,\n  npmCacheDirectory: string,\n  packageSpecs: readonly string[],\n  deps: LocalMcpRuntimeDeps,\n): Promise<void> {\n  const { runCommand, onProgress } = deps\n  // Mirrors prepareSignerRuntime's installRuntimePackages: fast path reuses the\n  // default npm cache (warmed by npx) with --prefer-offline so the mcp + sdk\n  // tarballs are not re-downloaded; fall back to the isolated Haven-owned cache\n  // if the default cache is broken or root-owned (see docs/operations/\n  // mcp-runtime-compatibility.md).\n  const baseArgs = [\n    'install',\n    '--prefix',\n    runtimeDirectory,\n    '--no-audit',\n    '--no-fund',\n    '--omit=dev',\n    '--prefer-offline',\n    ...packageSpecs,\n  ]\n  const run = async (args: string[]): Promise<void> => {\n    // Heartbeat while npm works, and the same honest budget as the signer\n    // install: a cold-cache install can legitimately exceed the old 120s\n    // timeout, and a silent console reads as a hang (#1586/#1593).\n    const startedAt = Date.now()\n    const heartbeat = setInterval(() => {\n      const seconds = Math.round((Date.now() - startedAt) / 1000)\n      onProgress?.(`Still installing the local Haven MCP runtime… (${seconds}s — a cold cache can take several minutes)`)\n    }, SIGNER_INSTALL_HEARTBEAT_MS)\n    heartbeat.unref?.()\n    try {\n      if (runCommand) await runCommand('npm', args)\n      else await execFileAsync('npm', args, { timeout: SIGNER_INSTALL_TIMEOUT_MS, maxBuffer: 1024 * 1024 })\n    } finally {\n      clearInterval(heartbeat)\n    }\n  }\n\n  try {\n    await run(baseArgs)\n  } catch {\n    try {\n      await run([...baseArgs, '--cache', npmCacheDirectory])\n    } catch (err) {\n      throw new Error(`Could not install local Haven MCP runtime ${packageSpecs.join(' ')}: ${err instanceof Error ? err.message : String(err)}`)\n    }\n  }\n}\n\nasync function installedRuntimeMatches(runtimeDirectory: string, cliPath: string): Promise<boolean> {\n  try {\n    await assertFileExists(cliPath, 'local Haven MCP CLI')\n    const installed = await readInstalledVersions(runtimeDirectory)\n    return installed.mcpVersion === MCP_RUNTIME_MANIFEST.mcpVersion &&\n      installed.sdkVersion === MCP_RUNTIME_MANIFEST.sdkVersion\n  } catch {\n    return false\n  }\n}\n\nasync function readInstalledVersions(runtimeDirectory: string): Promise<{ mcpVersion: string; sdkVersion: string }> {\n  const [mcpPackage, sdkPackage] = await Promise.all([\n    readPackageJson(join(runtimeDirectory, 'node_modules', '@haven_ai', 'mcp', 'package.json')),\n    readPackageJson(join(runtimeDirectory, 'node_modules', '@haven_ai', 'sdk', 'package.json')),\n  ])\n  return { mcpVersion: mcpPackage.version ?? '', sdkVersion: sdkPackage.version ?? '' }\n}\n\nasync function readPackageJson(path: string): Promise<{ version?: string }> {\n  return JSON.parse(await readFile(path, 'utf8')) as { version?: string }\n}\n\nasync function writeWrapper(input: {\n  wrapperPath: string\n  cliPath: string\n  identityPath: string\n  signerPath: string\n  /** #2424: present only under an override. */\n  overrideComment?: string\n}): Promise<void> {\n  await mkdir(dirname(input.wrapperPath), { recursive: true, mode: 0o700 })\n  await chmod(dirname(input.wrapperPath), 0o700).catch(() => undefined)\n  const source = [\n    '#!/usr/bin/env node',\n    ...(input.overrideComment\n      ? [`// HAVEN RUNTIME SPEC OVERRIDE (#2424): ${input.overrideComment} — this wrapper launches a NON-pinned MCP build.`]\n      : []),\n    \"import { spawn } from 'node:child_process'\",\n    '',\n    `const cliPath = ${JSON.stringify(input.cliPath)}`,\n    `const identityPath = ${JSON.stringify(input.identityPath)}`,\n    `const signerPath = ${JSON.stringify(input.signerPath)}`,\n    '',\n    \"const child = spawn(process.execPath, [cliPath, '--identity', identityPath, '--signer', signerPath, ...process.argv.slice(2)], {\",\n    \"  stdio: 'inherit',\",\n    '})',\n    '',\n    \"child.on('exit', (code, signal) => {\",\n    '  if (signal) process.kill(process.pid, signal)',\n    '  else process.exit(code ?? 1)',\n    '})',\n    '',\n  ].join('\\n')\n  await writeFile(input.wrapperPath, source, { mode: 0o700 })\n  await chmod(input.wrapperPath, 0o700).catch(() => undefined)\n}\n\nasync function writeRuntimeSidecar(input: {\n  path: string\n  wrapperPath: string\n  runtimeDirectory: string\n  npmCacheDirectory: string\n  cliPath: string\n  serverName?: string\n  override?: RuntimeSpecOverrideRecord\n  installedVersions?: { mcpVersion: string; sdkVersion: string }\n}): Promise<void> {\n  const value = {\n    ...(input.serverName ? { server_name: input.serverName } : {}),\n    mcp_package: MCP_RUNTIME_MANIFEST.mcpPackage,\n    mcp_version: input.installedVersions?.mcpVersion ?? MCP_RUNTIME_MANIFEST.mcpVersion,\n    sdk_package: MCP_RUNTIME_MANIFEST.sdkPackage,\n    sdk_version: input.installedVersions?.sdkVersion ?? MCP_RUNTIME_MANIFEST.sdkVersion,\n    minimum_node_version: MCP_RUNTIME_MANIFEST.minimumNodeVersion,\n    wrapper_path: input.wrapperPath,\n    runtime_directory: input.runtimeDirectory,\n    npm_cache_directory: input.npmCacheDirectory,\n    cli_path: input.cliPath,\n    ...(input.override ? { runtime_spec_override: input.override } : {}),\n  }\n  await writeFile(input.path, `${JSON.stringify(value, null, 2)}\\n`, { mode: 0o600 })\n  await chmod(input.path, 0o600).catch(() => undefined)\n}\n\nasync function assertFileExists(path: string, label: string): Promise<void> {\n  try {\n    await access(path)\n  } catch {\n    throw new Error(`Missing ${label}: ${path}`)\n  }\n}\n","import { mkdir, readFile, writeFile } from 'node:fs/promises'\nimport { homedir } from 'node:os'\nimport { join, resolve } from 'node:path'\nimport { HAVEN_SKILL_MD, HAVEN_SKILL_BODY_MD, SKILL_FOLDER_NAME } from '@haven_ai/sdk'\nimport type { RuntimeId } from './runtime-registry.js'\n\n/**\n * Guidance-surface parity across runtimes (#1332).\n *\n * The generic payment skill is static and secret-free. Where a runtime has a\n * DOCUMENTED instruction mechanism, setup installs the canonical content\n * there; the substance is identical everywhere — only the wrapper differs:\n *\n * - claude-code — `~/.claude/skills/haven-pay/SKILL.md` (Claude's skills\n *   folder; unchanged behavior, moved here from runtime-install.ts).\n * - hermes — `$HERMES_HOME/skills/haven-pay/SKILL.md` (default\n *   `~/.hermes/skills/…`). Hermes auto-discovers SKILL.md skills from that\n *   directory in the same front-matter format Claude uses, so the file is\n *   byte-identical to the Claude install.\n * - codex-cli / codex-desktop — a marker-delimited managed section in the\n *   global `~/.codex/AGENTS.md` (Codex's documented global-guidance file,\n *   shared by CLI and Desktop). The section carries the skill BODY (front\n *   matter is skills-registry metadata and meaningless in AGENTS.md). Writes\n *   are idempotent — an existing managed section is replaced in place — and\n *   everything outside the markers is preserved byte-for-byte. The file is\n *   created when absent. `AGENTS.override.md` is never touched.\n * - every other runtime — no documented instruction file; the baseline is the\n *   MCP server-level initialize instructions, so nothing is written.\n */\n\nexport const CODEX_AGENTS_BEGIN_MARKER =\n  '<!-- BEGIN haven-pay (managed by @haven_ai/connect; edits inside this section are overwritten on re-setup) -->'\nexport const CODEX_AGENTS_END_MARKER = '<!-- END haven-pay -->'\n\nexport interface SkillInstallResult {\n  installed: boolean\n  target?: string\n  messages: string[]\n}\n\nexport interface SkillInstallDeps {\n  homeDir?: string\n  env?: NodeJS.ProcessEnv\n}\n\nexport async function installSkillForRuntime(\n  runtime: RuntimeId,\n  deps: SkillInstallDeps = {},\n): Promise<SkillInstallResult | undefined> {\n  switch (runtime) {\n    case 'claude-code':\n      return installSkillFile(\n        resolve(deps.homeDir ?? homedir(), '.claude', 'skills', SKILL_FOLDER_NAME),\n        '~/.claude/skills/haven-pay',\n      )\n    case 'hermes':\n      return installSkillFile(\n        join(hermesHome(deps), 'skills', SKILL_FOLDER_NAME),\n        'the Hermes skills folder',\n      )\n    case 'codex-cli':\n    case 'codex-desktop':\n      return installCodexAgentsSection(deps)\n    default:\n      // No documented instruction file for this runtime — the MCP server's\n      // initialize instructions carry the baseline guidance.\n      return undefined\n  }\n}\n\nasync function installSkillFile(skillDir: string, label: string): Promise<SkillInstallResult> {\n  try {\n    await mkdir(skillDir, { recursive: true })\n    const target = join(skillDir, 'SKILL.md')\n    await writeFile(target, HAVEN_SKILL_MD, 'utf8')\n    return {\n      installed: true,\n      target,\n      messages: [`Installed the generic Haven payment skill (${label}). It contains no secrets.`],\n    }\n  } catch (err) {\n    return {\n      installed: false,\n      messages: [\n        `Could not install the Haven payment skill: ${err instanceof Error ? err.message : String(err)}. Download it from the Haven dashboard instead.`,\n      ],\n    }\n  }\n}\n\nasync function installCodexAgentsSection(deps: SkillInstallDeps): Promise<SkillInstallResult> {\n  try {\n    const codexDir = resolve(deps.homeDir ?? homedir(), '.codex')\n    const target = join(codexDir, 'AGENTS.md')\n    await mkdir(codexDir, { recursive: true })\n    const existing = await readFile(target, 'utf8').catch(() => null)\n    const next = upsertManagedSection(existing, codexManagedSection())\n    if (next !== existing) {\n      await writeFile(target, next, 'utf8')\n    }\n    return {\n      installed: true,\n      target,\n      messages: [\n        'Installed the generic Haven payment guidance as a managed section in ~/.codex/AGENTS.md (Codex reads it as global instructions). It contains no secrets; your own content in that file is untouched.',\n      ],\n    }\n  } catch (err) {\n    return {\n      installed: false,\n      messages: [\n        `Could not install the Haven payment guidance into ~/.codex/AGENTS.md: ${err instanceof Error ? err.message : String(err)}. Download the skill from the Haven dashboard instead.`,\n      ],\n    }\n  }\n}\n\nfunction codexManagedSection(): string {\n  return `${CODEX_AGENTS_BEGIN_MARKER}\\n\\n${HAVEN_SKILL_BODY_MD.trimEnd()}\\n\\n${CODEX_AGENTS_END_MARKER}\\n`\n}\n\n/**\n * Replace the existing managed section in place, or append one. Everything\n * outside the markers is preserved byte-for-byte — this file belongs to the\n * user; Haven owns only the span between its own markers.\n */\nexport function upsertManagedSection(existing: string | null, section: string): string {\n  if (existing === null || existing.trim() === '') return section\n  // Line-anchored: a marker quoted mid-line (prose, a code fence example)\n  // must not be mistaken for a live section boundary.\n  const begins = markerLineIndexes(existing, CODEX_AGENTS_BEGIN_MARKER)\n  const ends = markerLineIndexes(existing, CODEX_AGENTS_END_MARKER)\n  if (begins.length === 1 && ends.length === 1 && ends[0] > begins[0]) {\n    const afterEnd = ends[0] + CODEX_AGENTS_END_MARKER.length\n    // Swallow the line break the section itself terminates with (LF or CRLF),\n    // so re-runs replace in place instead of accreting blank lines.\n    const tail = existing.startsWith('\\r\\n', afterEnd)\n      ? existing.slice(afterEnd + 2)\n      : existing.startsWith('\\n', afterEnd)\n        ? existing.slice(afterEnd + 1)\n        : existing.slice(afterEnd)\n    return existing.slice(0, begins[0]) + section + tail\n  }\n  if (begins.length > 0 || ends.length > 0) {\n    // Anything but exactly one well-ordered pair — an orphaned marker, or a\n    // duplicated section — is damage. Appending or guessing a span here could\n    // swallow user content between markers on this or a LATER run; fail\n    // closed and leave the file alone.\n    throw new Error(\n      'found a damaged Haven marker section (orphaned or duplicated markers); remove the leftover marker lines and re-run setup',\n    )\n  }\n  // No markers: append at the end, separated by a blank line.\n  return `${existing.replace(/\\n*$/, '\\n\\n')}${section}`\n}\n\n/** Indexes of `marker` occurrences that sit at the start of a line. */\nfunction markerLineIndexes(text: string, marker: string): number[] {\n  const indexes: number[] = []\n  for (let from = 0; ; ) {\n    const at = text.indexOf(marker, from)\n    if (at === -1) return indexes\n    if (at === 0 || text[at - 1] === '\\n') indexes.push(at)\n    from = at + marker.length\n  }\n}\n\n// Must resolve the SAME home as config-writers' hermesHomePath (which reads\n// the real process.env) — the skill and the config.yaml/.env writes belong in\n// one Hermes home. `deps.env` exists for test isolation only; production\n// callers never pass it, so both resolvers read the same process.env.\nfunction hermesHome(deps: SkillInstallDeps): string {\n  const env = deps.env ?? process.env\n  return env.HERMES_HOME ?? join(deps.homeDir ?? homedir(), '.hermes')\n}\n","import { ConnectError } from './connect-error.js'\n\nexport type RuntimeId =\n  | 'claude-code'\n  | 'codex-desktop'\n  | 'codex-cli'\n  | 'cursor'\n  | 'vscode'\n  | 'vscode-insiders'\n  | 'claude-desktop'\n  | 'hermes'\n  | 'other'\n\nexport type RestartMode = 'restart-session' | 'restart-app' | 'hot-reload' | 'manual'\n\nexport interface RuntimeProfile {\n  id: RuntimeId\n  label: string\n  restartMode: RestartMode\n  canWriteRuntimeConfig: boolean\n  /** Precise, runtime-owned instruction for loading a freshly written MCP entry. */\n  activationInstruction: string\n}\n\nconst RUNTIME_PROFILES: Record<RuntimeId, RuntimeProfile> = {\n  'claude-code': {\n    id: 'claude-code',\n    label: 'Claude Code',\n    restartMode: 'restart-session',\n    canWriteRuntimeConfig: true,\n    activationInstruction: 'Start a new Claude Code session so it loads the Haven MCP entries.',\n  },\n  'codex-cli': {\n    id: 'codex-cli',\n    label: 'Codex CLI',\n    restartMode: 'restart-session',\n    canWriteRuntimeConfig: true,\n    activationInstruction: 'Start a fresh Codex CLI session (for example, run `codex resume --last`).',\n  },\n  'codex-desktop': {\n    id: 'codex-desktop',\n    label: 'Codex Desktop',\n    restartMode: 'restart-session',\n    canWriteRuntimeConfig: true,\n    activationInstruction: 'Quit and reopen Codex Desktop so it loads the Haven MCP entries.',\n  },\n  cursor: {\n    id: 'cursor',\n    label: 'Cursor',\n    restartMode: 'hot-reload',\n    canWriteRuntimeConfig: true,\n    activationInstruction: 'Wait for Cursor to hot-reload the Haven MCP entries; no app restart is required.',\n  },\n  vscode: {\n    id: 'vscode',\n    label: 'VS Code',\n    restartMode: 'hot-reload',\n    canWriteRuntimeConfig: true,\n    activationInstruction: 'Wait for VS Code to hot-reload the Haven MCP entries; no app restart is required.',\n  },\n  'vscode-insiders': {\n    id: 'vscode-insiders',\n    label: 'VS Code Insiders',\n    restartMode: 'hot-reload',\n    canWriteRuntimeConfig: true,\n    activationInstruction: 'Wait for VS Code Insiders to hot-reload the Haven MCP entries; no app restart is required.',\n  },\n  'claude-desktop': {\n    id: 'claude-desktop',\n    label: 'Claude Desktop',\n    restartMode: 'restart-app',\n    canWriteRuntimeConfig: true,\n    activationInstruction: 'Quit and reopen Claude Desktop so it loads the Haven MCP entries.',\n  },\n  hermes: {\n    id: 'hermes',\n    label: 'Hermes Agent',\n    restartMode: 'restart-session',\n    canWriteRuntimeConfig: true,\n    activationInstruction: 'Start a new Hermes session; in Hermes Gateway, run `/restart` instead.',\n  },\n  other: {\n    id: 'other',\n    label: 'Other agent runtime',\n    restartMode: 'manual',\n    canWriteRuntimeConfig: false,\n    activationInstruction: 'Finish the manual MCP setup shown above, then start a fresh session in that runtime.',\n  },\n}\n\nconst RUNTIME_ALIASES: Record<string, RuntimeId> = {\n  claude: 'claude-code',\n  'claude-code': 'claude-code',\n  claudecode: 'claude-code',\n  'claude_code': 'claude-code',\n  // #1682: Cowork runs Claude Code's config, so it resolves to the same\n  // profile. The dashboard's command carries no --runtime for it (it is a\n  // detected, command-path runtime), but an explicit `--runtime cowork` typed\n  // by hand must not fall through to the no-runtime refusal.\n  cowork: 'claude-code',\n  codex: 'codex-cli',\n  'codex-cli': 'codex-cli',\n  codexcli: 'codex-cli',\n  'codex_cli': 'codex-cli',\n  'codex-desktop': 'codex-desktop',\n  'codex_desktop': 'codex-desktop',\n  codexdesktop: 'codex-desktop',\n  'codex-app': 'codex-desktop',\n  'codex_app': 'codex-desktop',\n  codexapp: 'codex-desktop',\n  cursor: 'cursor',\n  vscode: 'vscode',\n  'vs-code': 'vscode',\n  'vs_code': 'vscode',\n  code: 'vscode',\n  'vscode-insiders': 'vscode-insiders',\n  'vscode_insiders': 'vscode-insiders',\n  vscodeinsiders: 'vscode-insiders',\n  'vs-code-insiders': 'vscode-insiders',\n  'code-insiders': 'vscode-insiders',\n  insiders: 'vscode-insiders',\n  'claude-desktop': 'claude-desktop',\n  'claude_desktop': 'claude-desktop',\n  claudesktop: 'claude-desktop',\n  desktop: 'claude-desktop',\n  hermes: 'hermes',\n  'hermes-agent': 'hermes',\n  hermes_agent: 'hermes',\n  hermesagent: 'hermes',\n  // #1682: OpenClaw is a SNIPPET target — the user pastes an mcpServers entry\n  // into ~/.openclaw/openclaw.json and restarts the gateway. That is exactly\n  // the 'other' profile's behaviour (credentials written to disk, no config\n  // auto-written, manual finish), so it resolves there rather than earning a\n  // profile whose only distinguishing feature would be its label.\n  openclaw: 'other',\n  'open-claw': 'other',\n  'open_claw': 'other',\n  other: 'other',\n  manual: 'other',\n}\n\nexport function runtimeProfile(runtime: string | undefined, env: NodeJS.ProcessEnv = process.env): RuntimeProfile {\n  return RUNTIME_PROFILES[normalizeRuntime(runtime, env)]\n}\n\nexport function normalizeRuntime(runtime: string | undefined, env: NodeJS.ProcessEnv = process.env): RuntimeId {\n  const explicit = normalizeRuntimeName(runtime)\n  if (explicit) return explicit\n  return detectRuntime(env) ?? 'other'\n}\n\n/**\n * The flag values a refusal should offer, as data (#2091): they ride on the\n * refusal's `ConnectError.details.allowedRuntimes` so the `--json` contract\n * can list them machine-readably, not only in prose an automation run never\n * sees. Mirrors RuntimeId.\n */\nexport const RUNTIME_FLAG_VALUE_LIST = [\n  'claude-code',\n  'codex-cli',\n  'codex-desktop',\n  'cursor',\n  'vscode',\n  'vscode-insiders',\n  'claude-desktop',\n  'hermes',\n  'other',\n] as const satisfies readonly RuntimeId[]\n\n/** The same values as refusal-message prose. */\nexport const RUNTIME_FLAG_VALUES = RUNTIME_FLAG_VALUE_LIST.join(', ')\n\nexport interface RuntimeSelection {\n  runtime: RuntimeId | null\n  source: 'force' | 'detected' | 'explicit' | 'prompted' | 'none'\n  /** Set when a confident environment detection overrode a contradicting explicit hint (#1672). */\n  overrodeHint?: RuntimeId\n  /** Set when a supplied hint was not a runtime name at all and detection carried the run (#1719). */\n  discardedHint?: string\n}\n\nexport interface RuntimeResolutionOptions {\n  env?: NodeJS.ProcessEnv\n  /**\n   * Rung 3b (#1719): the harness an AGENT executing this command reported for\n   * ITSELF, when detection found nothing to go on.\n   *\n   * It deliberately enters at the same precedence as `--runtime`, which is\n   * what makes it safe: a hint can only ever fill a vacuum, and loses to a\n   * confident detection exactly as #1672 made it. In practice the agent\n   * supplies it BY re-running with `--runtime <name>`; this field exists so a\n   * programmatic caller can pass a self-report without pretending to be a\n   * command-line flag, and so the ladder names the rung it has.\n   */\n  selfReported?: string\n  /**\n   * Rung 4 (#1719): ask a human at an interactive terminal which of the\n   * clients installed on this machine to configure. Injected as a thunk so\n   * the ladder stays a policy function — the scan, the readline prompt, and\n   * the \"nothing writable is installed\" refusal all live in\n   * `installed-clients.ts`. Omitted (`--json`, no TTY, library callers) means\n   * the rung is skipped entirely, not answered with a guess.\n   */\n  promptForRuntime?: () => Promise<RuntimeId>\n}\n\n/**\n * Runtime resolution, detection-first (#1672) and self-resolving (#1719).\n *\n * The connector command carries no `--runtime`; the connector works out the\n * runtime it is executing inside. Precedence:\n *\n * 1. `--runtime-force <name>` — always wins (unknown name refuses).\n * 2. Environment detection over a CONTRADICTING hint. Detection only fires\n *    inside a real agent shell, where writing a different client's config is\n *    almost surely wrong — the claude-desktop-hint-in-Claude-Code dead end\n *    this exists to close.\n * 3. An explicit `--runtime`, or an agent's self-report, with no contradicting\n *    detection (the legit plain-terminal \"configure Claude Desktop by hand\"\n *    case — unchanged).\n * 4. Detection alone.\n * 5. An interactive pick among the clients actually installed here, when a\n *    human is at a TTY. The scan populates the choices; it never selects.\n * 6. Nothing known → `runtime: null`; the caller refuses BEFORE side effects\n *    rather than guessing a config location.\n *\n * A hint that is not a runtime name at all is not a hint — it is a mistake, and\n * the one thing it must never do is fall through to a config location nobody\n * asked for. With no detection to fall back on it refuses (`runtime_unrecognized`).\n * With a detection it loses to it, loudly, exactly like a contradicting hint:\n * the detected client is the right write either way, and refusing there would\n * turn every rollout window in which the dashboard learns an id before the\n * published connector does into a hard failure.\n */\nexport async function resolveRuntimeSelection(\n  explicit: string | undefined,\n  force: string | undefined,\n  options: RuntimeResolutionOptions = {},\n): Promise<RuntimeSelection> {\n  const env = options.env ?? process.env\n  if (force !== undefined) {\n    const forced = normalizeRuntimeName(force)\n    if (!forced) {\n      throw new ConnectError(\n        'runtime_force_unrecognized',\n        `Unknown --runtime-force value \"${force}\". Valid values: ${RUNTIME_FLAG_VALUES}.`,\n        'rerun_connect_with_a_valid_runtime_name',\n        { allowedRuntimes: RUNTIME_FLAG_VALUE_LIST },\n      )\n    }\n    return { runtime: forced, source: 'force' }\n  }\n  const detected = detectRuntime(env)\n  const supplied = explicit?.trim() || options.selfReported?.trim() || undefined\n  const hint = normalizeRuntimeName(supplied)\n  if (supplied && !hint) {\n    if (!detected) {\n      throw new ConnectError(\n        'runtime_unrecognized',\n        `\"${supplied}\" is not an agent runtime Haven knows. Valid values: ${RUNTIME_FLAG_VALUES} ` +\n          '(the aliases cowork, codex and openclaw are accepted too). ' +\n          'Re-run with one of those, or --runtime other to store credentials and finish the MCP setup by hand. ' +\n          'Nothing was written and the Haven setup token is still unused.',\n        'rerun_connect_with_a_valid_runtime_name',\n        { allowedRuntimes: RUNTIME_FLAG_VALUE_LIST },\n      )\n    }\n    return { runtime: detected, source: 'detected', discardedHint: supplied }\n  }\n  if (detected && hint && detected !== hint) {\n    return { runtime: detected, source: 'detected', overrodeHint: hint }\n  }\n  if (hint) return { runtime: hint, source: 'explicit' }\n  if (detected) return { runtime: detected, source: 'detected' }\n  if (options.promptForRuntime) {\n    return { runtime: await options.promptForRuntime(), source: 'prompted' }\n  }\n  return { runtime: null, source: 'none' }\n}\n\nexport function restartRequiredForRuntime(runtime: string | undefined, env: NodeJS.ProcessEnv = process.env): boolean {\n  const mode = runtimeProfile(runtime, env).restartMode\n  return mode === 'restart-session' || mode === 'restart-app'\n}\n\n/**\n * Desktop GUI runtimes really do require a restart for the user to see the new\n * MCP server — the MCP server lifecycle is tied to app launch, not to the\n * current conversation. The agent who reported the \"restart not needed\"\n * surprise was using Claude Code (a CLI session that picks up new MCP servers\n * in-session via the deferred-tool mechanism). Don't softpedal the restart\n * instruction on Claude Desktop / Codex Desktop just because Claude Code is\n * looser about it.\n */\nexport function runtimeRequiresHardRestart(runtime: RuntimeId): boolean {\n  return runtime === 'claude-desktop' || runtime === 'codex-desktop'\n}\n\n/**\n * The one safe post-activation check for every supported topology. It only\n * reads the connected agent and its live budget; it never signs, funds, or\n * creates a payment.\n */\nexport function runtimeVerificationInstruction(runtime: RuntimeId): string {\n  const label = RUNTIME_PROFILES[runtime].label\n  return `In ${label}, run the read-only \\`haven_get_agent\\` and \\`haven_get_allowances\\` tools to confirm the Haven wallet and live budget. Do not sign, fund, or create a payment to verify setup.`\n}\n\n/**\n * #3120: exported for the doctor's runtime resolution — when `--runtime` is\n * absent, the connector resolves the runtime the setup actually recorded, and\n * the recorded value must go through the same alias table an explicit flag\n * would (`Cowork` → `claude-code`, `desktop` → `claude-desktop`, …). Returns\n * null for empty/unknown names; it NEVER env-detects (that is\n * `normalizeRuntime`'s job, which wraps this).\n */\nexport function normalizeRuntimeName(runtime: string | undefined): RuntimeId | null {\n  const key = runtime?.trim().toLowerCase()\n  if (!key) return null\n  return RUNTIME_ALIASES[key.replace(/\\s+/g, '-')] ?? null\n}\n\nfunction detectRuntime(env: NodeJS.ProcessEnv): RuntimeId | null {\n  if (env.CLAUDECODE || env.CLAUDE_CODE || env.CLAUDECODE_CWD) return 'claude-code'\n  if (env.CODEX_SANDBOX || env.CODEX_HOME || env.CODEX_CWD) return 'codex-cli'\n  if (env.VSCODE_CWD || env.VSCODE_IPC_HOOK_CLI || env.TERM_PROGRAM === 'vscode') return 'vscode'\n  if (env.HERMES_HOME || env.HERMES_AGENT) return 'hermes'\n  return null\n}\n","import { readFile } from 'node:fs/promises'\nimport { resolve } from 'node:path'\nimport {\n  computeSignerConsentHash,\n  createEdgeSigner,\n  ensureSignerConsent,\n  loadSignerCredentials,\n  toolSchemas,\n  type SignerConsentDecision,\n  type SignerConsentInput,\n  type SignerToolName,\n} from '@haven_ai/signer'\n\nexport interface LocalSignerConsentStatus {\n  acknowledged: boolean\n  hash?: string\n  reason?: SignerConsentDecision['reason'] | 'ack_file_missing' | 'ack_file_mismatch'\n  error?: string\n}\n\nexport async function acknowledgeLocalSignerConsent(\n  signerPath: string,\n  log?: (message: string) => void,\n): Promise<LocalSignerConsentStatus> {\n  try {\n    const input = await buildSignerConsentInput(signerPath)\n    const decision = await ensureSignerConsent(input, {\n      credentialsPath: signerPath,\n      writeAck: true,\n      out: log ? { write: (chunk) => writeLogChunk(log, chunk) } : undefined,\n    })\n    return {\n      acknowledged: decision.ok,\n      hash: decision.hash,\n      reason: decision.reason,\n    }\n  } catch (err) {\n    return {\n      acknowledged: false,\n      error: err instanceof Error ? err.message : String(err),\n    }\n  }\n}\n\nexport async function getLocalSignerConsentStatus(signerPath: string): Promise<LocalSignerConsentStatus> {\n  try {\n    const input = await buildSignerConsentInput(signerPath)\n    const hash = computeSignerConsentHash(input)\n    const stored = await readSignerAckFile(signerAckPath(signerPath))\n    if (stored === hash) {\n      return { acknowledged: true, hash, reason: 'ack_file_match' }\n    }\n    return {\n      acknowledged: false,\n      hash,\n      reason: stored ? 'ack_file_mismatch' : 'ack_file_missing',\n    }\n  } catch (err) {\n    return {\n      acknowledged: false,\n      error: err instanceof Error ? err.message : String(err),\n    }\n  }\n}\n\nexport function signerAckPath(signerPath: string): string {\n  return resolve(`${signerPath}.signer-ack.json`)\n}\n\nasync function buildSignerConsentInput(signerPath: string): Promise<SignerConsentInput> {\n  const credentials = await loadSignerCredentials(signerPath)\n  const signer = createEdgeSigner(credentials.delegateKey, {\n    x402BindingSigner: credentials.x402BindingSigner,\n  })\n  return {\n    delegateAddress: signer.delegateAddress,\n    accountAddress: credentials.accountAddress,\n    agentId: credentials.agentId,\n    chainId: credentials.chainId,\n    network: credentials.network,\n    toolNames: Object.keys(toolSchemas) as SignerToolName[],\n  }\n}\n\nasync function readSignerAckFile(path: string): Promise<string | null> {\n  try {\n    const parsed = JSON.parse(await readFile(path, 'utf8')) as { ack?: unknown }\n    return typeof parsed.ack === 'string' ? parsed.ack : null\n  } catch {\n    return null\n  }\n}\n\nfunction writeLogChunk(log: (message: string) => void, chunk: string): void {\n  const message = String(chunk).trimEnd()\n  if (message) log(message)\n}\n","import { execFile } from 'node:child_process'\nimport { connectorRerunCommand } from '@haven_ai/sdk'\nimport { promisify } from 'node:util'\nimport { writeRuntimeConfig, type RuntimeMcpMode, type RuntimeConfigWriteResult } from './config-writers.js'\nimport { serverNamesFor } from './server-names.js'\nimport {\n  acknowledgeLocalMcpConsent,\n  getLocalMcpConsentStatus,\n  type LocalMcpConsentStatus,\n} from './local-mcp-consent.js'\nimport {\n  probeHostedMcpTools,\n  probeLocalMcpTools,\n  probeLocalSignerCredential,\n  type LocalMcpProbeResult,\n  type LocalMcpProbeStatus,\n} from './probes.js'\nimport {\n  prepareLocalMcpRuntime,\n  type PreparedLocalMcpRuntime,\n  type PrepareLocalMcpRuntimeInput,\n} from './local-mcp-runtime.js'\nimport {\n  prepareSignerRuntime,\n  type PreparedSignerRuntime,\n  type PrepareSignerRuntimeInput,\n} from './signer-runtime.js'\nimport { MCP_RUNTIME_MANIFEST, mcpPackageSpec, signerPackageSpec } from './runtime-manifest.js'\nimport { installSkillForRuntime } from './skill-install.js'\nimport { normalizeRuntime, restartRequiredForRuntime, runtimeProfile, type RuntimeId } from './runtime-registry.js'\nimport {\n  acknowledgeLocalSignerConsent,\n  getLocalSignerConsentStatus,\n  type LocalSignerConsentStatus,\n} from './signer-consent.js'\n\nconst execFileAsync = promisify(execFile)\n\nexport interface RuntimeInstallInput {\n  runtime?: string\n  hostedMcpUrl: string\n  apiKey: string\n  signerPath: string\n  identityPath: string\n  credentialDirectory: string\n  environmentLabel?: string\n  ackSigner?: boolean\n  ackLocalTools?: boolean\n  /**\n   * Explicit opt-in to the local-stdio MCP topology (zero hosted dependency).\n   * Default is hosted MCP + local signer for every runtime; local MCP is only\n   * used when this is true and the runtime supports it.\n   */\n  localMcp?: boolean\n  /**\n   * #1695: wiring slug for a NAMED MCP pair (haven-<slug> /\n   * haven-signer-<slug>). Absent = the bare pair, unchanged from today.\n   */\n  serverName?: string\n}\n\nexport interface RuntimeInstallResult {\n  runtime: RuntimeId\n  runtimeMcpMode: RuntimeMcpMode\n  hostedMcpConfigured: boolean\n  localSignerConfigured: boolean\n  localMcpConfigured: boolean\n  probeResult: string\n  restartRequired: boolean\n  nextUserAction: string\n  errorCode?: string\n  configTarget?: string\n  runtimeVersion?: string\n  signerAcknowledged?: boolean\n  localMcpAcknowledged?: boolean\n  activationCommand?: string\n  skillInstalled?: boolean\n  /**\n   * Hosted topology only: true when the signer was pre-installed and registered\n   * via its absolute wrapper, false when prep failed and it fell back to the\n   * fragile runtime-`npx` launch. Undefined for local/manual topologies that\n   * do not run the signer as a separate MCP. Lets callers/tests detect the\n   * silent npx fallback instead of treating every write as fully healthy.\n   */\n  signerRuntimePrepared?: boolean\n  messages: string[]\n}\n\n/**\n * The config-write snapshot handed to `onRuntimeConfigured` (#1543). The\n * booleans mirror the semantics of the FINAL report's unlock keys minus the\n * probe verdicts: \"configured\" here means the config write succeeded, the\n * required consent is acknowledged, and the signer credential exists on disk\n * (a local fs check) — not that a handshake has verified it. A later probe\n * failure refines the final report and sets its errorCode; the dashboard's\n * unlock condition accepts either state.\n */\nexport interface EarlyRuntimeConfigReport {\n  runtime: RuntimeId\n  runtimeMcpMode: RuntimeMcpMode\n  hostedMcpConfigured: boolean\n  localSignerConfigured: boolean\n  localMcpConfigured: boolean\n  signerAcknowledged?: boolean\n  localMcpAcknowledged?: boolean\n  restartRequired: boolean\n  nextUserAction: string\n  errorCode?: string\n}\n\nexport interface RuntimeInstallDeps {\n  env?: NodeJS.ProcessEnv\n  homeDir?: string\n  fetch?: typeof fetch\n  /**\n   * Optional live progress callback. installRuntime's slowest steps (signer\n   * pre-install, runtime config write, MCP handshake probes) otherwise emit\n   * nothing until the caller flushes the collected `messages` after this\n   * returns — leaving the console silent through the longest part of setup.\n   * When provided, a few lightweight heartbeat lines are emitted as they run.\n   */\n  onProgress?: (message: string) => void\n  /**\n   * #1543: invoked once, the moment the runtime MCP config write has settled —\n   * BEFORE the network probes and the skill install. The dashboard withholds\n   * its budget-approval controls until an install-status report shows the\n   * runtime configured, and the final report only lands after the entire\n   * install; gating approval on that tail made the user wait on work approval\n   * does not depend on. The snapshot carries the config-write facts (no probe\n   * verdicts, no skill state); the caller's complete report remains\n   * authoritative and overwrites these keys. Best-effort by contract: a\n   * throwing callback is swallowed and never fails the install.\n   */\n  onRuntimeConfigured?: (report: EarlyRuntimeConfigReport) => Promise<void> | void\n  runCommand?: (command: string, args: string[]) => Promise<void>\n  prepareLocalMcpRuntime?: (input: PrepareLocalMcpRuntimeInput) => Promise<PreparedLocalMcpRuntime>\n  prepareSignerRuntime?: (input: PrepareSignerRuntimeInput) => Promise<PreparedSignerRuntime>\n  probeSignerTools?: (\n    command: string,\n    args: string[],\n    requiredTools: readonly string[],\n  ) => Promise<LocalMcpProbeResult>\n  probeLocalMcpTools?: (\n    command: string,\n    args: string[],\n    requiredTools: readonly string[],\n  ) => Promise<LocalMcpProbeResult>\n}\n\nexport async function installRuntime(\n  input: RuntimeInstallInput,\n  deps: RuntimeInstallDeps = {},\n): Promise<RuntimeInstallResult> {\n  const runtime = normalizeRuntime(input.runtime, deps.env)\n  const profile = runtimeProfile(runtime, deps.env)\n  const progress = deps.onProgress ?? (() => undefined)\n  const localRuntime = input.localMcp === true && supportsLocalMcp(runtime)\n  const consentMessages: string[] = []\n  const localMcpConsent = localRuntime\n    ? await resolveLocalMcpConsent(input, consentMessages)\n    : undefined\n  const signerConsent = localRuntime\n    ? undefined\n    : await resolveSignerConsent(input, consentMessages)\n\n  if (runtime === 'other') {\n    const signerCredentialReady = await probeLocalSignerCredential(input.signerPath)\n    const signerReady = signerCredentialReady && signerConsent?.acknowledged\n    return {\n      runtime,\n      runtimeMcpMode: 'manual',\n      hostedMcpConfigured: false,\n      localSignerConfigured: false,\n      localMcpConfigured: false,\n      probeResult: signerReady\n        ? 'manual_runtime_setup_required_local_signer_ready'\n        : 'manual_runtime_setup_required_local_signer_unavailable',\n      restartRequired: true,\n      nextUserAction: 'return_to_haven_for_wallet_approval_then_configure_runtime',\n      errorCode: 'manual_runtime_setup_required',\n      configTarget: 'manual runtime setup',\n      signerAcknowledged: signerConsent?.acknowledged,\n      localMcpAcknowledged: false,\n      messages: [\n        ...consentMessages,\n        'Custom runtime: Haven did not auto-configure it. Your credentials are on disk (chmod 600) — read them at runtime; never paste a key into the agent prompt, memory, or logs.',\n        `  identity (hosted MCP Bearer): ${input.identityPath}`,\n        `  signer (local signing key):   ${input.signerPath}`,\n        'After wallet approval, wire the runtime to Haven by reference:',\n        `  Hosted MCP + local signer: point your MCP client at ${input.hostedMcpUrl} with the api_key from identity.json, then run  npx -y ${signerPackageSpec()} --credentials ${input.signerPath}`,\n        `  Fully local MCP (no hosted dependency):  npx -y ${mcpPackageSpec()} --identity ${input.identityPath} --signer ${input.signerPath}`,\n      ],\n    }\n  }\n\n  let localRuntimeInstall: PreparedLocalMcpRuntime | undefined\n  let localRuntimeError: unknown\n  if (localRuntime) {\n    try {\n      localRuntimeInstall = await prepareRuntimeForLocalMcp(input, deps)\n    } catch (err) {\n      localRuntimeError = err\n    }\n  }\n\n  if (localRuntimeError) {\n    const errorCode = localRuntimePrepareErrorCode(localRuntimeError)\n    return {\n      runtime,\n      runtimeMcpMode: 'local_stdio',\n      hostedMcpConfigured: false,\n      localSignerConfigured: false,\n      localMcpConfigured: false,\n      probeResult: errorCode === 'local_mcp_unsupported_node_version'\n        ? 'local_stdio_mcp_unsupported_node_version'\n        : 'local_stdio_mcp_runtime_install_failed',\n      restartRequired: true,\n      nextUserAction: nextAction(runtime, profile.restartMode, errorCode),\n      errorCode,\n      configTarget: profile.label,\n      signerAcknowledged: signerConsent?.acknowledged,\n      localMcpAcknowledged: localMcpConsent?.acknowledged,\n      activationCommand: undefined,\n      messages: [\n        ...consentMessages,\n        `Could not prepare local Haven MCP runtime: ${localRuntimeError instanceof Error ? localRuntimeError.message : String(localRuntimeError)}`,\n      ],\n    }\n  }\n\n  // Hosted topology launches the local signer as its own MCP stdio server.\n  // Pre-install it and register an absolute wrapper instead of a runtime\n  // `npx -y` invocation, which is fragile in the agent runtime's MCP-spawn\n  // environment.\n  //\n  // #1586: prep failure is FATAL for this setup run — loud and fail-closed,\n  // never a silent npx fallback. The 2026-08-18 Codex Desktop test showed\n  // why: with Codex's startup_timeout_sec = 120, an npx first-launch is a\n  // multi-minute npm install killed at 2 minutes, leaving corrupted _npx\n  // dirs and a config that LOOKS wired but structurally cannot connect —\n  // strictly worse than a clear error. Fail-closed here means NO config is\n  // written at all (not even the hosted `haven` entry): a half-wired setup\n  // where quotes work but signing never can is the same looks-fine trap in\n  // a different place. The recovery is a re-run once the cause (network,\n  // npm cache) is addressed.\n  let signerCommand: { command: string; args: string[] } | undefined\n  if (!localRuntime) {\n    progress('Getting the signer ready…')\n    try {\n      const signerRuntime = await prepareSignerForRuntime(input, deps)\n      signerCommand = { command: signerRuntime.command, args: signerRuntime.args }\n      consentMessages.push(...signerRuntime.messages)\n    } catch (err) {\n      return {\n        runtime,\n        runtimeMcpMode: 'hosted_plus_signer',\n        hostedMcpConfigured: false,\n        localSignerConfigured: false,\n        localMcpConfigured: false,\n        probeResult: 'signer_runtime_install_failed',\n        restartRequired: false,\n        nextUserAction:\n          'The local Haven signer runtime could not be installed, so no configuration was written. ' +\n          `Check your network (a cold install downloads the signer package set) and re-run: ${connectorRerunCommand()}`,\n        errorCode: 'signer_runtime_install_failed',\n        configTarget: profile.label,\n        signerAcknowledged: signerConsent?.acknowledged,\n        localMcpAcknowledged: localMcpConsent?.acknowledged,\n        activationCommand: undefined,\n        signerRuntimePrepared: false,\n        messages: [\n          ...consentMessages,\n          `Could not pre-install the local Haven signer: ${err instanceof Error ? err.message : String(err)}`,\n          'No runtime configuration was written (fail-closed): a config pointing at an uninstalled signer looks wired but cannot start.',\n          `Re-run \\`${connectorRerunCommand()}\\` to retry the setup.`,\n        ],\n      }\n    }\n  }\n  const signerRuntimePrepared = localRuntime ? undefined : signerCommand !== undefined\n\n  progress('Setting up your Haven tools…')\n  const configResult = localRuntime\n    ? runtime === 'claude-code'\n      ? await configureClaudeCode(deps, localRuntimeInstall?.command ?? '', input.serverName)\n      : await writeRuntimeConfig({\n          runtime,\n          hostedMcpUrl: input.hostedMcpUrl,\n          apiKey: input.apiKey,\n          identityPath: input.identityPath,\n          signerPath: input.signerPath,\n          serverName: input.serverName,\n          credentialDirectory: input.credentialDirectory,\n          localMcpCommand: localRuntimeInstall?.command,\n          signerCommand,\n          homeDir: deps.homeDir,\n          mode: 'local',\n        })\n    : await writeHostedRuntimeConfig(deps, { ...input, runtime }, signerCommand)\n\n  // #1543: the config write has settled — everything the dashboard's approval\n  // unlock reads is now known, so report it before the probes and skill\n  // install run. The signer-credential check is a local fs stat, cheap enough\n  // to make the early booleans carry the final report's semantics (minus the\n  // network probe verdicts, which only refine — never gate — the unlock).\n  if (deps.onRuntimeConfigured) {\n    const signerCredentialOnDisk = await probeLocalSignerCredential(input.signerPath)\n    const earlyLocalMcpOk = configResult.runtimeMcpMode === 'local_stdio' &&\n      configResult.localMcpConfigured &&\n      signerCredentialOnDisk &&\n      Boolean(localMcpConsent?.acknowledged)\n    const earlySignerOk = configResult.runtimeMcpMode === 'local_stdio'\n      ? earlyLocalMcpOk\n      : configResult.signerConfigured && signerCredentialOnDisk && Boolean(signerConsent?.acknowledged)\n    try {\n      await deps.onRuntimeConfigured({\n        runtime,\n        runtimeMcpMode: configResult.runtimeMcpMode,\n        hostedMcpConfigured: configResult.hostedConfigured,\n        localSignerConfigured: earlySignerOk,\n        localMcpConfigured: earlyLocalMcpOk,\n        signerAcknowledged: signerConsent?.acknowledged,\n        localMcpAcknowledged: localMcpConsent?.acknowledged,\n        restartRequired: configResult.restartRequired || restartRequiredForRuntime(runtime, deps.env),\n        nextUserAction: nextAction(runtime, profile.restartMode, configResult.errorCode),\n        errorCode: configResult.errorCode,\n      })\n    } catch {\n      // Best-effort by contract: early reporting must never fail the install —\n      // the caller's complete report follows either way.\n    }\n  }\n\n  progress('Almost there — just confirming everything connects…')\n  const localProbePromise = configResult.runtimeMcpMode === 'local_stdio' && localRuntimeInstall\n    ? runLocalMcpProbe(localRuntimeInstall, deps)\n    : Promise.resolve(undefined)\n  // #1587: in the hosted topology the signer is its own MCP stdio server and\n  // gets the same courtesy as the hosted server — a REAL handshake\n  // (initialize → tools/list → required-tools check) against the registered\n  // command, not a credential-file stat. The 2026-08-18 Codex test is why:\n  // setup exited 0 on a signer that could not start, and the failure\n  // surfaced mid-payment. Cheap and fast now that #1586 guarantees the\n  // command is a prepared wrapper, never a cold npx launch.\n  const signerProbePromise = configResult.runtimeMcpMode !== 'local_stdio' && signerCommand\n    ? (deps.probeSignerTools ?? probeLocalMcpTools)(\n        signerCommand.command,\n        signerCommand.args,\n        MCP_RUNTIME_MANIFEST.requiredSignerTools,\n      )\n    : Promise.resolve(undefined)\n  const [hostedProbe, signerCredentialReady, localMcpProbe, signerProbe] = await Promise.all([\n    configResult.hostedConfigured\n      ? probeHostedMcpTools(input.apiKey, input.hostedMcpUrl, deps.fetch)\n      : Promise.resolve({ status: 'bad_response' as const }),\n    probeLocalSignerCredential(input.signerPath),\n    localProbePromise,\n    signerProbePromise,\n  ])\n\n  const hostedOk = configResult.hostedConfigured && hostedProbe.status === 'ok'\n  const localMcpOk = configResult.runtimeMcpMode === 'local_stdio' &&\n    configResult.localMcpConfigured &&\n    signerCredentialReady &&\n    Boolean(localMcpConsent?.acknowledged) &&\n    localMcpProbe?.status === 'ok'\n  const signerOk = configResult.runtimeMcpMode === 'local_stdio'\n    ? localMcpOk\n    : configResult.signerConfigured &&\n      signerCredentialReady &&\n      Boolean(signerConsent?.acknowledged) &&\n      // #1587: no handshake, no green. A signer command that was registered\n      // but not probed (manual topology) keeps the old semantics.\n      (signerProbe === undefined || signerProbe.status === 'ok')\n  const restartRequired = configResult.restartRequired || restartRequiredForRuntime(runtime, deps.env)\n  const errorCode = configResult.errorCode ??\n    (configResult.runtimeMcpMode === 'local_stdio'\n      ? localMcpErrorCode(signerCredentialReady, localMcpConsent, localMcpProbe?.status)\n      : hostedMcpErrorCode(configResult.hostedConfigured, hostedProbe.status) ??\n        signerConsentErrorCode(signerCredentialReady, signerConsent) ??\n        signerProbeErrorCode(signerProbe))\n  const hostedProbeMessages = configResult.hostedConfigured && hostedProbe.status !== 'ok'\n    ? [`Hosted Haven MCP probe failed: ${hostedProbe.status}.`]\n    : configResult.hostedConfigured\n      ? ['Verified that the hosted Haven MCP tools endpoint responds to a read-only handshake.']\n      : []\n  const signerProbeMessages = signerProbe\n    ? signerProbe.status === 'ok'\n      ? ['Verified local Haven signer with a stdio handshake.']\n      : [\n          `Local Haven signer handshake failed: ${signerProbe.status}.`,\n          `Re-run \\`${connectorRerunCommand()}\\` to repair the signer setup.`,\n        ]\n    : []\n  const localProbeMessages = localMcpProbe && localMcpProbe.status !== 'ok'\n    ? [`Local Haven MCP handshake failed: ${localMcpProbe.status}.`]\n    : localMcpProbe?.status === 'ok'\n      ? ['Verified local Haven MCP tools with a stdio handshake.']\n      : []\n\n  // The generic payment skill is static and secret-free, so it is installed\n  // like the other acknowledged local writes on every runtime with a\n  // documented instruction mechanism (#1332): Claude's and Hermes's skills\n  // folders, Codex's global AGENTS.md managed section. Runtimes without one\n  // rely on the MCP server-level initialize instructions.\n  const skillInstall = !configResult.errorCode\n    ? await installSkillForRuntime(runtime, { homeDir: deps.homeDir, env: deps.env })\n    : undefined\n\n  return {\n    runtime,\n    runtimeMcpMode: configResult.runtimeMcpMode,\n    hostedMcpConfigured: hostedOk,\n    localSignerConfigured: signerOk,\n    localMcpConfigured: localMcpOk,\n    probeResult: buildProbeResult(configResult.runtimeMcpMode, configResult.hostedConfigured, hostedProbe.status, signerOk, localMcpOk, localMcpProbe?.status),\n    restartRequired,\n    nextUserAction: nextAction(runtime, profile.restartMode, errorCode),\n    errorCode,\n    configTarget: configResult.target,\n    signerAcknowledged: signerConsent?.acknowledged,\n    localMcpAcknowledged: localMcpConsent?.acknowledged,\n    activationCommand: configResult.activationCommand,\n    skillInstalled: skillInstall?.installed,\n    signerRuntimePrepared,\n    messages: [...consentMessages, ...(localRuntimeInstall?.messages ?? []), ...configResult.messages, ...hostedProbeMessages, ...signerProbeMessages, ...localProbeMessages, ...(skillInstall?.messages ?? [])],\n  }\n}\n\nexport function runtimeInstallCapabilities(runtime: string | undefined, env: NodeJS.ProcessEnv = process.env): {\n  canWriteRuntimeConfig: boolean\n  restartRequired: boolean\n} {\n  const profile = runtimeProfile(runtime, env)\n  return {\n    canWriteRuntimeConfig: profile.canWriteRuntimeConfig,\n    restartRequired: restartRequiredForRuntime(runtime, env),\n  }\n}\n\nasync function configureClaudeCode(\n  deps: RuntimeInstallDeps,\n  localMcpCommand: string,\n  serverName?: string,\n): Promise<{\n  hostedConfigured: boolean\n  signerConfigured: boolean\n  localMcpConfigured: boolean\n  runtimeMcpMode: RuntimeMcpMode\n  target: string\n  changed: boolean\n  restartRequired: boolean\n  messages: string[]\n  errorCode?: string\n  activationCommand?: string\n}> {\n  const runCommand = deps.runCommand ?? defaultRunCommand\n  const serverJson = JSON.stringify({\n    type: 'stdio',\n    command: localMcpCommand,\n    args: [],\n    env: {},\n  })\n  try {\n    if (!localMcpCommand) throw new Error('local MCP wrapper command is required')\n    // Remove stale entries first so re-runs and hosted→local switches are\n    // idempotent — `claude mcp add-json` fails when the name already exists.\n    // #1569: without this, a second setup left the runtime wired to the\n    // PREVIOUS agent's wrapper (the add collided, the old entry survived) —\n    // the hosted sibling below always did it in this order. Deliberate\n    // tradeoff: if the add fails AFTER a successful remove, the runtime ends\n    // with NO haven entry instead of a stale wrong-agent one — fail-closed,\n    // and the claude_code_config_failed recovery (rerun setup) works cleanly\n    // from that state because this sequence is idempotent from any start.\n    const names = serverNamesFor(serverName)\n    await runCommand('claude', ['mcp', 'remove', names.hosted]).catch(() => undefined)\n    await runCommand('claude', ['mcp', 'remove', names.signer]).catch(() => undefined)\n    await runCommand('claude', ['mcp', 'add-json', names.hosted, serverJson, '--scope', 'user'])\n      .catch(async () => {\n        await runCommand('claude', ['mcp', 'add', names.hosted, '--scope', 'user', '--', localMcpCommand])\n      })\n    const verified = await runCommand('claude', ['mcp', 'get', names.hosted])\n      .then(() => true)\n      .catch(() => false)\n    return {\n      hostedConfigured: false,\n      signerConfigured: true,\n      localMcpConfigured: true,\n      runtimeMcpMode: 'local_stdio',\n      target: 'Claude Code MCP config',\n      changed: true,\n      restartRequired: true,\n      messages: [\n        'Updated local Haven MCP entry with Claude Code.',\n        ...(verified ? ['Verified Claude Code MCP entry.'] : []),\n      ],\n    }\n  } catch (err) {\n    return {\n      hostedConfigured: false,\n      signerConfigured: false,\n      localMcpConfigured: false,\n      runtimeMcpMode: 'local_stdio',\n      target: 'Claude Code MCP config',\n      changed: false,\n      restartRequired: true,\n      messages: [\n        `Could not update Claude Code MCP config: ${err instanceof Error ? err.message : String(err)}`,\n        'Install Claude Code or rerun the Haven connector command inside a Claude Code terminal.',\n      ],\n      errorCode: 'claude_code_config_failed',\n    }\n  }\n}\n\n/**\n * Write the HOSTED topology's runtime config, whichever runtime it is.\n *\n * Exported and extracted (#1700) because Claude Code is not written by\n * `writeRuntimeConfig` at all — its `switch` has no `claude-code` case, so that\n * runtime falls through to the `default:` branch and returns\n * `hostedConfigured: false` with a \"add it manually\" message. Claude Code's\n * config is written by shelling out to `claude mcp add-json` instead.\n *\n * That is easy to not know, and the cost of not knowing it is silent: a caller\n * that reaches for `writeRuntimeConfig` directly gets a plausible-looking\n * result object for the single most common runtime, having changed nothing.\n * Re-key hit exactly that — it reported success while leaving every wired\n * Claude Code host presenting an API key the backend had just retired. This\n * function is the one place that fork is decided, so a future caller inherits\n * the right answer instead of rediscovering the wrong one.\n */\nexport async function writeHostedRuntimeConfig(\n  deps: RuntimeInstallDeps,\n  input: RuntimeInstallInput,\n  signerCommand?: { command: string; args: string[] },\n): Promise<RuntimeConfigWriteResult> {\n  if (input.runtime === 'claude-code') {\n    return configureClaudeCodeHosted(deps, input, signerCommand)\n  }\n  return writeRuntimeConfig({\n    runtime: input.runtime as RuntimeId,\n    hostedMcpUrl: input.hostedMcpUrl,\n    apiKey: input.apiKey,\n    identityPath: input.identityPath,\n    signerPath: input.signerPath,\n    serverName: input.serverName,\n    credentialDirectory: input.credentialDirectory,\n    signerCommand,\n    homeDir: deps.homeDir,\n    mode: 'hosted',\n  })\n}\n\nasync function configureClaudeCodeHosted(\n  deps: RuntimeInstallDeps,\n  input: RuntimeInstallInput,\n  signerCommand?: { command: string; args: string[] },\n): Promise<{\n  hostedConfigured: boolean\n  signerConfigured: boolean\n  localMcpConfigured: boolean\n  runtimeMcpMode: RuntimeMcpMode\n  target: string\n  changed: boolean\n  restartRequired: boolean\n  messages: string[]\n  errorCode?: string\n  activationCommand?: string\n}> {\n  const runCommand = deps.runCommand ?? defaultRunCommand\n  const hostedJson = JSON.stringify({\n    type: 'http',\n    url: input.hostedMcpUrl,\n    headers: { Authorization: `Bearer ${input.apiKey}` },\n  })\n  const signerJson = JSON.stringify({\n    type: 'stdio',\n    command: signerCommand?.command ?? 'npx',\n    args: signerCommand?.args ?? ['-y', signerPackageSpec(), '--credentials', input.signerPath],\n    env: {},\n  })\n  try {\n    // Remove stale entries first so re-runs and local→hosted switches are\n    // idempotent — `claude mcp add-json` fails when the name already exists.\n    // #1695: only the entries THIS pair owns, by name — a named setup can\n    // never clobber the bare pair or a sibling named pair.\n    const names = serverNamesFor(input.serverName)\n    await runCommand('claude', ['mcp', 'remove', names.hosted]).catch(() => undefined)\n    await runCommand('claude', ['mcp', 'remove', names.signer]).catch(() => undefined)\n    await runCommand('claude', ['mcp', 'add-json', names.hosted, hostedJson, '--scope', 'user'])\n    await runCommand('claude', ['mcp', 'add-json', names.signer, signerJson, '--scope', 'user'])\n    const verified = await runCommand('claude', ['mcp', 'get', names.hosted])\n      .then(() => true)\n      .catch(() => false)\n    return {\n      hostedConfigured: true,\n      signerConfigured: true,\n      localMcpConfigured: false,\n      runtimeMcpMode: 'hosted_plus_signer',\n      target: 'Claude Code MCP config',\n      changed: true,\n      restartRequired: true,\n      messages: [\n        'Updated hosted Haven MCP and local signer entries with Claude Code.',\n        ...(verified ? ['Verified Claude Code MCP entry.'] : []),\n      ],\n    }\n  } catch (err) {\n    return {\n      hostedConfigured: false,\n      signerConfigured: false,\n      localMcpConfigured: false,\n      runtimeMcpMode: 'hosted_plus_signer',\n      target: 'Claude Code MCP config',\n      changed: false,\n      restartRequired: true,\n      messages: [\n        `Could not update Claude Code MCP config: ${err instanceof Error ? err.message : String(err)}`,\n        'Install Claude Code or rerun the Haven connector command inside a Claude Code terminal.',\n      ],\n      errorCode: 'claude_code_config_failed',\n    }\n  }\n}\n\nasync function defaultRunCommand(command: string, args: string[]): Promise<void> {\n  await execFileAsync(command, args, { timeout: 10_000 })\n}\n\nfunction buildProbeResult(\n  mode: RuntimeMcpMode,\n  hostedConfigured: boolean,\n  hostedStatus: string,\n  signerReady: boolean,\n  localMcpReady: boolean,\n  localMcpProbeStatus?: LocalMcpProbeStatus,\n): string {\n  if (mode === 'local_stdio') {\n    if (localMcpReady) return 'local_stdio_mcp_ready'\n    return localMcpProbeStatus ? `local_stdio_mcp_${localMcpProbeStatus}` : 'local_stdio_mcp_unavailable'\n  }\n  const hostedPart = hostedConfigured ? `hosted_${hostedStatus}` : 'hosted_not_configured'\n  const signerPart = signerReady ? 'local_signer_ready' : 'local_signer_unavailable'\n  return `${hostedPart}_${signerPart}`.slice(0, 120)\n}\n\nasync function resolveLocalMcpConsent(\n  input: RuntimeInstallInput,\n  messages: string[],\n): Promise<LocalMcpConsentStatus> {\n  if (input.ackLocalTools || input.ackSigner) {\n    const status = await acknowledgeLocalMcpConsent(input.identityPath, input.signerPath, (message) => messages.push(message))\n    if (status.acknowledged) {\n      messages.push('Prepared the local Haven tools acknowledgement.')\n    } else {\n      messages.push('Local Haven tools acknowledgement still needs attention.')\n    }\n    return status\n  }\n  return getLocalMcpConsentStatus(input.identityPath, input.signerPath)\n}\n\nasync function resolveSignerConsent(\n  input: RuntimeInstallInput,\n  messages: string[],\n): Promise<LocalSignerConsentStatus> {\n  if (input.ackSigner || input.ackLocalTools) {\n    const status = await acknowledgeLocalSignerConsent(input.signerPath, (message) => messages.push(message))\n    if (status.acknowledged) {\n      messages.push('Prepared the local Haven signer acknowledgement.')\n    } else {\n      messages.push('Local Haven signer acknowledgement still needs attention.')\n    }\n    return status\n  }\n  return getLocalSignerConsentStatus(input.signerPath)\n}\n\nfunction signerConsentErrorCode(\n  signerCredentialReady: boolean,\n  signerConsent: LocalSignerConsentStatus | undefined,\n): string | undefined {\n  if (!signerCredentialReady) return 'local_signer_credential_unavailable'\n  if (!signerConsent?.acknowledged) return 'local_signer_ack_required'\n  return undefined\n}\n\nfunction signerProbeErrorCode(probe: LocalMcpProbeResult | undefined): string | undefined {\n  if (!probe || probe.status === 'ok') return undefined\n  return `local_signer_probe_${probe.status}`\n}\n\nfunction hostedMcpErrorCode(\n  hostedConfigured: boolean,\n  hostedProbeStatus: string,\n): string | undefined {\n  if (!hostedConfigured || hostedProbeStatus === 'ok') return undefined\n  return `hosted_mcp_probe_${hostedProbeStatus}`\n}\n\nfunction localMcpErrorCode(\n  signerCredentialReady: boolean,\n  localMcpConsent: LocalMcpConsentStatus | undefined,\n  localMcpProbeStatus: LocalMcpProbeStatus | undefined,\n): string | undefined {\n  if (!signerCredentialReady) return 'local_signer_credential_unavailable'\n  if (!localMcpConsent?.acknowledged) return 'local_mcp_ack_required'\n  if (localMcpProbeStatus && localMcpProbeStatus !== 'ok') return `local_mcp_probe_${localMcpProbeStatus}`\n  return undefined\n}\n\nfunction nextAction(\n  runtime: RuntimeId,\n  restartMode: 'restart-session' | 'restart-app' | 'hot-reload' | 'manual',\n  errorCode?: string,\n): string {\n  if (errorCode) return 'return_to_haven_for_wallet_approval_then_finish_runtime_setup'\n  if (restartMode === 'hot-reload') return 'return_to_haven_for_wallet_approval'\n  if (runtime === 'codex-cli' || runtime === 'codex-desktop') return 'return_to_haven_for_wallet_approval_then_restart_codex'\n  if (runtime === 'claude-code') return 'return_to_haven_for_wallet_approval_then_restart_claude_code'\n  if (restartMode === 'restart-app') return 'return_to_haven_for_wallet_approval_then_restart_app'\n  if (restartMode === 'restart-session') return 'return_to_haven_for_wallet_approval_then_restart_agent_session'\n  return 'return_to_haven_for_wallet_approval_then_configure_runtime'\n}\n\n/**\n * Runtimes where the local-stdio MCP topology can be installed when the user\n * explicitly opts in. Never used by default — the default topology is hosted\n * MCP + local signer for every runtime.\n */\nexport function supportsLocalMcp(runtime: RuntimeId): boolean {\n  return runtime === 'codex-cli' || runtime === 'codex-desktop' || runtime === 'claude-code'\n}\n\nasync function prepareRuntimeForLocalMcp(\n  input: RuntimeInstallInput,\n  deps: RuntimeInstallDeps,\n): Promise<PreparedLocalMcpRuntime> {\n  // onProgress threaded through on purpose (#1593, the #1586 review lesson):\n  // without it the install heartbeat is dead code in production.\n  const prepare = deps.prepareLocalMcpRuntime ?? ((runtimeInput: PrepareLocalMcpRuntimeInput) =>\n    prepareLocalMcpRuntime(runtimeInput, { runCommand: deps.runCommand, onProgress: deps.onProgress, env: deps.env }))\n  return prepare({\n    credentialDirectory: input.credentialDirectory,\n    identityPath: input.identityPath,\n    signerPath: input.signerPath,\n    homeDir: deps.homeDir,\n    serverName: input.serverName,\n  })\n}\n\nasync function prepareSignerForRuntime(\n  input: RuntimeInstallInput,\n  deps: RuntimeInstallDeps,\n): Promise<PreparedSignerRuntime> {\n  const prepare = deps.prepareSignerRuntime ?? ((runtimeInput: PrepareSignerRuntimeInput) =>\n    // onProgress threaded through on purpose (#1586 review): without it the\n    // install heartbeat was dead code in production and the console still\n    // went silent for the whole cold install — the exact symptom the issue\n    // set out to remove, at a longer timeout.\n    prepareSignerRuntime(runtimeInput, { runCommand: deps.runCommand, onProgress: deps.onProgress, env: deps.env }))\n  return prepare({\n    credentialDirectory: input.credentialDirectory,\n    signerPath: input.signerPath,\n    homeDir: deps.homeDir,\n    serverName: input.serverName,\n  })\n}\n\nasync function runLocalMcpProbe(\n  runtimeInstall: PreparedLocalMcpRuntime,\n  deps: RuntimeInstallDeps,\n): Promise<LocalMcpProbeResult> {\n  const probe = deps.probeLocalMcpTools ?? probeLocalMcpTools\n  try {\n    return await probe(runtimeInstall.command, runtimeInstall.args, MCP_RUNTIME_MANIFEST.requiredTools)\n  } catch {\n    return { status: 'process_error' }\n  }\n}\n\nfunction localRuntimePrepareErrorCode(err: unknown): string {\n  if (err && typeof err === 'object' && 'code' in err && err.code === 'local_mcp_unsupported_node_version') {\n    return 'local_mcp_unsupported_node_version'\n  }\n  return 'local_mcp_runtime_install_failed'\n}\n","import { homedir } from 'node:os'\nimport { join, resolve } from 'node:path'\nimport { access, readFile as fsReadFile } from 'node:fs/promises'\nimport { createInterface } from 'node:readline'\nimport { ConnectError } from './connect-error.js'\nimport { runtimeConfigPathFor } from './config-writers.js'\nimport { runtimeProfile, type RuntimeId } from './runtime-registry.js'\n\n/**\n * Installed-client scan + interactive pick (#1719).\n *\n * The rung that answers \"which runtime am I configuring?\" for a HUMAN in a\n * plain terminal, where there is no agent shell to detect. Two properties hold\n * it up, and both are load-bearing:\n *\n * 1. **Only clients the connector can actually write.** A row that cannot be\n *    configured is not a choice, it is a dead end wearing a choice's clothes.\n * 2. **The scan populates the choices; it never selects.** Finding exactly one\n *    installed app tells you what EXISTS, not where the user wants their agent\n *    to run — and the cost of being wrong is an API key and a delegate key\n *    written into an app the user does not use. `scanInstalledClients` returns\n *    candidates and nothing else; only an answer typed at the prompt resolves\n *    a runtime.\n */\nexport interface InstalledClientCandidate {\n  runtime: RuntimeId\n  label: string\n  /** What made this a candidate — shown at the prompt so the pick is informed. */\n  detail: string\n  /**\n   * The config file Haven would write for this client, when it owns one.\n   * `null` for Claude Code, which is configured through its own CLI. Set\n   * regardless of which evidence found the client — `evidence` is what says\n   * whether that file exists today.\n   */\n  configPath: string | null\n  /**\n   * The file the config-file evidence was found in, when this candidate\n   * carries that tier. Usually the same file `configPath` names — except for\n   * Claude Code, whose evidence lives in `~/.claude.json` while `configPath`\n   * stays `null` (the connector would configure it through its own CLI, not\n   * by writing a file it owns).\n   */\n  evidencePath?: string | null\n  evidence: 'config-file' | 'client-directory'\n}\n\ninterface ScanTarget {\n  runtime: RuntimeId\n  label: string\n  /** The config file the connector would write, when it owns a file path. */\n  configPath: string | null\n  /**\n   * A file whose existence grants config-file evidence even when the\n   * connector does not own it for writing (`configPath` null). Set only for\n   * Claude Code: a user-scope `~/.claude.json` that carries an `mcpServers`\n   * key means Claude Code has already been pointed at some MCP server.\n   */\n  evidencePath?: string\n  /**\n   * Extra condition on the evidence file's CONTENT (absent: existence alone\n   * is evidence). Claude Code needs it — a `~/.claude.json` without an\n   * `mcpServers` key is only a directory-tier marker, as before.\n   */\n  evidenceMatches?: (contents: string) => boolean\n  /** Paths that mean \"this client is installed\" even with no MCP config yet. */\n  markers: string[]\n}\n\nexport interface ScanInstalledClientsOptions {\n  homeDir?: string\n  /** Workspace root, for the project-local `.vscode/` marker. */\n  cwd?: string\n  env?: NodeJS.ProcessEnv\n  /** Injectable so the scan is testable without a populated home directory. */\n  exists?: (path: string) => Promise<boolean>\n  /** Injectable so the `mcpServers` evidence check is testable without a real file. */\n  readFile?: (path: string) => Promise<string>\n}\n\n/**\n * Ranked highest-confidence first WITHIN each evidence tier. An existing MCP\n * config file outranks a bare client directory across the board — a client the\n * user has already pointed at some MCP server is likelier to be the one they\n * are pointing at Haven now.\n */\nconst SCAN_ORDER: readonly RuntimeId[] = [\n  'claude-code',\n  'codex-cli',\n  'cursor',\n  'vscode',\n  'vscode-insiders',\n  'claude-desktop',\n  'hermes',\n]\n\nexport function installedClientTargets(\n  homeDir: string = homedir(),\n  cwd: string = process.cwd(),\n  env: NodeJS.ProcessEnv = process.env,\n): ScanTarget[] {\n  const targets: ScanTarget[] = [\n    {\n      runtime: 'claude-code',\n      label: 'Claude Code',\n      // Claude Code is configured through its own CLI (`claude mcp add-json`),\n      // not by writing a file this module owns — so `configPath` stays null\n      // and the write still goes through the CLI. But a user-scope\n      // `~/.claude.json` carrying an `mcpServers` key IS config-file\n      // evidence: the user has already pointed Claude Code at some MCP\n      // server. It is not the file the connector would write, hence the\n      // separate evidence path (#3732): without it, a Codex config won by\n      // construction on any machine where the user runs Claude Code.\n      configPath: null,\n      evidencePath: join(homeDir, '.claude.json'),\n      evidenceMatches: (contents) => {\n        try {\n          const parsed: unknown = JSON.parse(contents)\n          return typeof parsed === 'object' && parsed !== null && 'mcpServers' in parsed\n        } catch {\n          return false\n        }\n      },\n      markers: [join(homeDir, '.claude'), join(homeDir, '.claude.json')],\n    },\n    {\n      runtime: 'codex-cli',\n      // Both Codex surfaces write the same ~/.codex/config.toml, so they are\n      // ONE candidate. Splitting them would ask the user to answer a question\n      // whose answers are the same write.\n      label: 'Codex (CLI or Desktop)',\n      configPath: runtimeConfigPathFor('codex-cli', homeDir),\n      markers: [join(homeDir, '.codex')],\n    },\n    {\n      runtime: 'cursor',\n      label: 'Cursor',\n      configPath: runtimeConfigPathFor('cursor', homeDir),\n      markers: [join(homeDir, '.cursor')],\n    },\n    {\n      runtime: 'vscode',\n      label: 'VS Code',\n      configPath: runtimeConfigPathFor('vscode', homeDir),\n      markers: [resolve(cwd, '.vscode')],\n    },\n    {\n      runtime: 'vscode-insiders',\n      label: 'VS Code Insiders',\n      configPath: runtimeConfigPathFor('vscode-insiders', homeDir),\n      markers: [],\n    },\n    {\n      runtime: 'claude-desktop',\n      // The chat app, a separate runtime from Claude Code. Named so a user in\n      // the desktop app's Code tab cannot read this row as \"where I am\" —\n      // it sorted above Claude Code whenever both had config (#3732).\n      label: 'Claude Desktop (chat app)',\n      configPath: runtimeConfigPathFor('claude-desktop', homeDir),\n      markers: [],\n    },\n    {\n      runtime: 'hermes',\n      label: 'Hermes Agent',\n      configPath: runtimeConfigPathFor('hermes', homeDir),\n      markers: [env.HERMES_HOME ?? join(homeDir, '.hermes')],\n    },\n  ]\n  // Belt and braces against a future profile losing its writer: an unwritable\n  // runtime must never reach the prompt (property 1 above).\n  return targets.filter((target) => runtimeProfile(target.runtime, {}).canWriteRuntimeConfig)\n}\n\nexport async function scanInstalledClients(\n  options: ScanInstalledClientsOptions = {},\n): Promise<InstalledClientCandidate[]> {\n  const exists = options.exists ?? pathExists\n  const readFile = options.readFile ?? ((path: string) => fsReadFile(path, 'utf8'))\n  const targets = installedClientTargets(options.homeDir, options.cwd, options.env ?? process.env)\n  const found: InstalledClientCandidate[] = []\n  for (const target of targets) {\n    if (target.configPath && (await exists(target.configPath))) {\n      found.push({\n        runtime: target.runtime,\n        label: target.label,\n        detail: `MCP config found at ${target.configPath}`,\n        configPath: target.configPath,\n        evidencePath: target.configPath,\n        evidence: 'config-file',\n      })\n      continue\n    }\n    if (target.evidencePath && (await hasConfigEvidence(target, exists, readFile))) {\n      found.push({\n        runtime: target.runtime,\n        label: target.label,\n        detail: `MCP config found at ${target.evidencePath}`,\n        configPath: target.configPath,\n        evidencePath: target.evidencePath,\n        evidence: 'config-file',\n      })\n      continue\n    }\n    for (const marker of target.markers) {\n      if (!(await exists(marker))) continue\n      found.push({\n        runtime: target.runtime,\n        label: target.label,\n        detail: `installed (${marker})`,\n        configPath: target.configPath,\n        evidencePath: null,\n        evidence: 'client-directory',\n      })\n      break\n    }\n  }\n  return found.sort((a, b) => {\n    if (a.evidence !== b.evidence) return a.evidence === 'config-file' ? -1 : 1\n    return SCAN_ORDER.indexOf(a.runtime) - SCAN_ORDER.indexOf(b.runtime)\n  })\n}\n\n/**\n * Whether the target's separate evidence path earns config-file evidence:\n * the file must exist, and when the target pins a content rule\n * (`evidenceMatches`), the file must satisfy it. A file that cannot be READ\n * grants nothing — unreadable is not evidence (#3732).\n */\nasync function hasConfigEvidence(\n  target: ScanTarget,\n  exists: (path: string) => Promise<boolean>,\n  readFile: (path: string) => Promise<string>,\n): Promise<boolean> {\n  const path = target.evidencePath as string\n  if (!(await exists(path))) return false\n  if (!target.evidenceMatches) return true\n  try {\n    return target.evidenceMatches(await readFile(path))\n  } catch {\n    return false\n  }\n}\n\n/**\n * The scan's findings as DATA, for the `--json` refusal (#2174).\n *\n * The interactive prompt is deliberately omitted under `--json`, which threw\n * this signal away exactly where it was most useful: an agent retrying a\n * `runtime_undetermined` refusal picked from a nine-value menu on\n * self-knowledge alone, while the connector already knew which client configs\n * exist on the machine.\n *\n * Property 2 above is preserved verbatim and is the reason this returns a\n * HINT rather than a runtime: the caller still has to refuse. Finding exactly\n * one installed app tells you what exists, not where the user wants their\n * agent to run, and the cost of being wrong is an API key and a delegate key\n * written into an app they do not use.\n */\nexport interface InstalledClientHint {\n  /** Runtime ids the scan found, likeliest first. */\n  installedClients: readonly RuntimeId[]\n  /**\n   * The top hit, and only when it is unambiguously top — see\n   * `installedClientHint`. A value an agent may echo back as `--runtime`;\n   * never a selection the connector makes for it.\n   */\n  suggestedRuntime?: RuntimeId\n}\n\n/**\n * A suggestion is offered only when one candidate is CLEARLY first: a lone\n * candidate, or a single live MCP config file among bare client directories —\n * the one tier difference the scan treats as evidence. Candidates within a\n * tier are separated only by `SCAN_ORDER`, a fixed preference rather than a\n * fact about this machine, so suggesting the winner of that tiebreak would\n * dress an arbitrary choice as a finding.\n *\n * The suggestion is derived from the WHOLE array rather than from the first\n * two entries, so it does not depend on the caller having sorted anything.\n * This is exported, and an unsorted list reaching a positional rule would\n * yield a quietly wrong suggestion — never a selection, since only the caller\n * can act on it, but wrong is still wrong. `installedClients` preserves the\n * order it was given, which for `scanInstalledClients` is likeliest-first.\n */\nexport function installedClientHint(\n  candidates: readonly InstalledClientCandidate[],\n): InstalledClientHint {\n  const installedClients = candidates.map((candidate) => candidate.runtime)\n  if (candidates.length === 1) {\n    return { installedClients, suggestedRuntime: candidates[0].runtime }\n  }\n  const configured = candidates.filter((candidate) => candidate.evidence === 'config-file')\n  return configured.length === 1\n    ? { installedClients, suggestedRuntime: configured[0].runtime }\n    : { installedClients }\n}\n\nexport interface PromptIo {\n  write: (text: string) => void\n  /** Resolves the typed line, or `null` on EOF / Ctrl-C. */\n  question: (query: string) => Promise<string | null>\n}\n\n/** Bounded so a piped-but-TTY-looking stdin cannot spin forever. */\nconst MAX_PROMPT_ATTEMPTS = 3\n\nexport async function promptForInstalledClient(\n  candidates: readonly InstalledClientCandidate[],\n  io: PromptIo = defaultPromptIo(),\n): Promise<RuntimeId> {\n  if (candidates.length === 0) throw noInstalledClientsError()\n  const hint = installedClientHint(candidates)\n  io.write('Haven could not detect which agent runtime this is.\\n')\n  io.write('These agent clients are installed on this machine:\\n')\n  candidates.forEach((candidate, index) => {\n    // The suggested runtime may be MARKED (a hint, from `installedClientHint`)\n    // but is never pre-selected: an untyped Enter must not write an API key\n    // and a delegate key into whichever client sorts first (#3732).\n    const suggested = hint.suggestedRuntime === candidate.runtime ? ' (suggested)' : ''\n    io.write(`  ${index + 1}) ${candidate.label}${suggested} — ${candidate.detail}\\n`)\n  })\n  io.write('Haven writes an API key and a signing key into the client you pick, so pick the one your agent actually runs in.\\n')\n\n  for (let attempt = 0; attempt < MAX_PROMPT_ATTEMPTS; attempt += 1) {\n    const answer = await io.question(`Which one? [1-${candidates.length}]: `)\n    if (answer === null) throw promptAbortedError('the prompt was cancelled')\n    const trimmed = answer.trim()\n    // Empty input is NOT a default (#3732, owner decision 2026-10-07): the\n    // scan populates the choices; it never selects — and neither does an\n    // untyped Enter, which would write live keys into whichever client sorts\n    // first. Avoiding it costs one keystroke; being wrong costs a key in a\n    // client the user does not use. Re-ask, spending an attempt, exactly\n    // like the wiring-collision prompt (\"Empty input is NOT a default\",\n    // wiring-collision.ts).\n    if (trimmed === '') {\n      io.write(`Type the number of the client to configure (1-${candidates.length}).\\n`)\n      continue\n    }\n    const picked = Number.parseInt(trimmed, 10)\n    if (Number.isInteger(picked) && picked >= 1 && picked <= candidates.length) {\n      return candidates[picked - 1].runtime\n    }\n    io.write(`\"${trimmed}\" is not one of 1-${candidates.length}.\\n`)\n  }\n  throw promptAbortedError(`no valid choice after ${MAX_PROMPT_ATTEMPTS} attempts`)\n}\n\n/**\n * The whole rung as one thunk: scan, refuse if nothing writable is installed,\n * otherwise prompt. This is what `resolveRuntimeSelection` calls, which is why\n * the registry needs no knowledge of the filesystem or of readline.\n */\nexport async function resolveRuntimeByInstalledClientPrompt(\n  options: ScanInstalledClientsOptions & { io?: PromptIo } = {},\n): Promise<RuntimeId> {\n  const candidates = await scanInstalledClients(options)\n  if (candidates.length === 0) throw noInstalledClientsError()\n  return promptForInstalledClient(candidates, options.io ?? defaultPromptIo())\n}\n\nfunction noInstalledClientsError(): ConnectError {\n  return new ConnectError(\n    'runtime_no_installed_clients',\n    'Could not determine the agent runtime: nothing was detected in this environment, and no agent client Haven can configure is installed on this machine. ' +\n      'Re-run with --runtime <name> naming the client you want configured, or --runtime other to store credentials and finish the MCP setup by hand.',\n    'rerun_connect_with_explicit_runtime',\n  )\n}\n\nfunction promptAbortedError(reason: string): ConnectError {\n  return new ConnectError(\n    'runtime_prompt_aborted',\n    `Runtime not chosen (${reason}). Nothing was written: no agent was created, no credentials were stored, and the Haven setup token is still unused. ` +\n      'Run the connector command again, or pass --runtime <name> to skip the prompt.',\n    'rerun_connect_and_choose_a_runtime',\n  )\n}\n\nasync function pathExists(path: string): Promise<boolean> {\n  try {\n    await access(path)\n    return true\n  } catch {\n    return false\n  }\n}\n\n/**\n * The readline-backed prompt IO, shared with the #2551 wiring-collision prompt\n * so the two interactive rungs cannot drift on Ctrl-C / EOF handling.\n */\nexport function defaultPromptIo(): PromptIo {\n  return {\n    write: (text) => process.stdout.write(text),\n    question: (query) =>\n      new Promise<string | null>((resolvePromise) => {\n        const rl = createInterface({ input: process.stdin, output: process.stdout })\n        let settled = false\n        const settle = (value: string | null) => {\n          if (settled) return\n          settled = true\n          rl.close()\n          resolvePromise(value)\n        }\n        // Without an explicit SIGINT listener readline's Ctrl-C behaviour\n        // depends on the host; with one, Ctrl-C is an abort we report as such\n        // and exit non-zero from, having written nothing.\n        rl.once('SIGINT', () => settle(null))\n        rl.once('close', () => settle(null))\n        rl.question(query, (answer) => settle(answer))\n      }),\n  }\n}\n","/**\n * Existing-agent wiring collision at setup (#2551).\n *\n * A second setup on one machine used to be resolved AFTER the fact: the\n * #1569 remove-first install overwrote the bare `haven` / `haven-signer`\n * pair, and the #1688 heads-up then told the user, in a run that had already\n * moved on, that their previous agent still held a live key. The connector\n * had the information all along — it just acted on it after the write.\n *\n * This module moves the decision to the moment of conflict, in the component\n * that can see it, and BEFORE anything is minted or written. Three rules:\n *\n * - **Local reads only.** Detection scans the credential root this run would\n *   write into — the same directories `--doctor` classifies — and never calls\n *   Haven. That is what lets it run ahead of `registerSetup`: a declined or\n *   refused run leaves no orphaned `pending_approval` agent behind, because\n *   nothing was registered.\n * - **The doctor's vocabulary, not a second definition.** A collision is a\n *   directory the doctor would call `wired` or `superseded` — one holding a\n *   USABLE key (an `identity.json` with an `api_key`) and no `TOMBSTONE.json`\n *   — that this run's bare pair would displace. `retired`, `orphaned` and\n *   `parked` directories never trigger it; nor does a NAMED directory, whose\n *   own `haven-<slug>` pair coexists with the bare one by construction\n *   (#1695). A `--name` run displaces nothing, so it never collides here;\n *   its one refusal (a taken slug) is `assertServerSlugAvailable`.\n * - **Connect never revokes.** The replace path retires the superseded\n *   directory LOCALLY — tombstone, then the unconditional key-material\n *   teardown (`--unwire` runs it only after its #3123 probe; this path does\n *   not probe) — and names the agent for the owner to revoke on the\n *   Haven agent page. `POST /agents/:id/revoke` is owner-authenticated; an\n *   agent credential revoking a sibling agent is exactly the \"agent editing\n *   its own authority\" the re-key routes refuse (#1694).\n *\n * \"Usable\" is decided locally, exactly as the doctor decides it before its\n * live probe: a key the owner already revoked in the dashboard still reads as\n * usable here. That is the honest limit of a check that makes no network\n * call, and the refusal names the ids so the owner can tell.\n */\nimport { readdir, readFile, stat } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { assertValidServerSlug } from './server-names.js'\nimport { readRuntimeSidecar } from './signer-runtime.js'\nimport { defaultCredentialRoot } from './storage.js'\nimport { TOMBSTONE_FILENAME } from './tombstone.js'\nimport type { PromptIo } from './installed-clients.js'\n\nexport interface SupersededDirectory {\n  directory: string\n  /** Agent id from `identity.json`, or the directory name when it is missing. */\n  agentId: string\n}\n\nexport interface WiringCollision {\n  /** Every bare-pair directory holding a usable key — what this run would displace. */\n  superseded: readonly SupersededDirectory[]\n  /**\n   * A valid, collision-checked slug the user can take to install alongside\n   * instead. Derived from the agent name Haven resolved for this setup, so\n   * the proposal reads as the agent rather than as a counter.\n   */\n  suggestedServerName: string\n}\n\nexport type WiringCollisionResolution =\n  | { action: 'replace' }\n  | { action: 'alongside'; serverName: string }\n  | { action: 'abort' }\n\n/**\n * Directories under the credential root that a BARE-pair setup would\n * displace. `null` when there is nothing to displace — a clean machine, a\n * machine holding only retired/orphaned/parked directories, or one holding\n * only named agents.\n */\nexport async function detectWiringCollision(input: {\n  credentialsDir?: string\n  agentName: string\n}): Promise<WiringCollision | null> {\n  const root = defaultCredentialRoot(input.credentialsDir)\n  let entries: string[] = []\n  try {\n    entries = await readdir(root)\n  } catch {\n    return null\n  }\n  const superseded: SupersededDirectory[] = []\n  const taken = new Set<string>()\n  for (const entry of entries) {\n    const directory = join(root, entry)\n    let identityRaw: string\n    try {\n      identityRaw = await readFile(join(directory, 'identity.json'), 'utf8')\n    } catch {\n      // No identity: retired-with-keys-removed, parked, or not an agent\n      // directory at all. None of these holds a usable key.\n      continue\n    }\n    taken.add(entry)\n    let identity: { agent_id?: string; api_key?: string } | undefined\n    try {\n      identity = JSON.parse(identityRaw) as { agent_id?: string; api_key?: string }\n    } catch {\n      identity = undefined\n    }\n    // The doctor's `orphaned`: an identity that yields no usable key.\n    if (!identity?.api_key) continue\n    // The doctor's `retired` outranks everything else it can see.\n    if (await pathExists(join(directory, TOMBSTONE_FILENAME))) continue\n    // A NAMED agent owns `haven-<slug>`; the bare pair leaves it alone.\n    const sidecar = await readRuntimeSidecar(directory)\n    if (sidecar?.server_name) continue\n    superseded.push({ directory, agentId: identity.agent_id ?? entry })\n  }\n  if (superseded.length === 0) return null\n  return {\n    superseded,\n    suggestedServerName: proposeServerSlug(input.agentName, taken),\n  }\n}\n\n/**\n * A valid slug from a display name, de-collided against the directory names\n * already under the credential root. The slug is what a `--name` install is\n * keyed on (#1696), so it has to pass `assertValidServerSlug` and must not be\n * a directory that already holds credentials.\n *\n * A name that slugifies to nothing usable (empty, or one of the reserved\n * names the validator refuses) falls back to `agent`, and a taken candidate\n * gains a numeric suffix. The proposal is exactly that — a proposal: the user\n * types it back (or their own), and the ordinary `--name` path validates it\n * again before anything is written.\n */\nexport function proposeServerSlug(\n  agentName: string,\n  taken: ReadonlySet<string>,\n  maxBaseLength = 32,\n): string {\n  let base = agentName\n    .toLowerCase()\n    .replace(/[^a-z0-9]+/g, '-')\n    .replace(/^-+|-+$/g, '')\n    .replace(/-{2,}/g, '-')\n    .slice(0, maxBaseLength)\n    .replace(/-+$/g, '')\n  if (!slugIsValid(base)) base = 'agent'\n  if (!taken.has(base)) return base\n  for (let n = 2; n < 1000; n += 1) {\n    const suffix = `-${n}`\n    const candidate = `${base.slice(0, maxBaseLength - suffix.length).replace(/-+$/g, '')}${suffix}`\n    if (slugIsValid(candidate) && !taken.has(candidate)) return candidate\n  }\n  // Unreachable in practice (999 same-named directories); never return a\n  // taken or invalid slug, so refuse loudly rather than propose one.\n  throw new Error(`Could not propose an unused server name for ${JSON.stringify(agentName)}.`)\n}\n\n/**\n * #3737: the slug a DEFAULT setup derives for itself. Same rules as the\n * collision-path proposal — slugified display name, `agent` fallback, numeric\n * de-collision — with the owner-decision-4 environment mark appended: on a\n * non-production backend the slug ends `-dev`, so a machine can hold a dev\n * and a production agent side by side and every config entry says which is\n * which. `maxBaseLength` reserves room for the mark so the result still\n * passes `assertValidServerSlug`.\n *\n * `taken` must name EVERY directory under the credential root — not just the\n * keyed ones (`detectWiringCollision`'s set) — so a slug freed by `--unwire`\n * (a tombstoned or key-removed directory) is never handed out again and the\n * new credentials are never written into a retired directory. See\n * `listTakenDirectoryNames`.\n */\nexport function deriveServerSlug(\n  agentName: string,\n  taken: ReadonlySet<string>,\n  markNonProduction: boolean,\n): string {\n  const mark = '-dev'\n  if (!markNonProduction) return proposeServerSlug(agentName, taken)\n  const base = proposeServerSlug(agentName, taken, 32 - mark.length)\n  // An agent literally named \"Research Dev\" already slugifies to a marked\n  // slug; appending again would only shorten the usable base.\n  if (base.endsWith(mark)) return base\n  const marked = `${base}${mark}`\n  if (!taken.has(marked)) return marked\n  return proposeServerSlug(marked, taken)\n}\n\n/**\n * Every directory name under the credential root — the widest possible\n * `taken` set for slug derivation (#3737). Deliberately wider than\n * `detectWiringCollision`'s: that one only names directories holding an\n * `identity.json`, because displacement needs a live key, but DERIVATION\n * must avoid every name that exists on disk in any state, retired ones\n * included — connect never overwrites a directory, and writing fresh\n * credentials into a tombstoned or key-removed one would revive a retired\n * identity. Best-effort: an unreadable root yields an empty set, the same\n * stance `detectWiringCollision` takes (the storage preflight has already\n * run by the time this is called, so the root is normally writable).\n */\nexport async function listTakenDirectoryNames(credentialsDir?: string): Promise<Set<string>> {\n  const root = defaultCredentialRoot(credentialsDir)\n  let entries: string[] = []\n  try {\n    entries = await readdir(root)\n  } catch {\n    return new Set()\n  }\n  const taken = new Set<string>()\n  for (const entry of entries) {\n    try {\n      if (!(await stat(join(root, entry))).isDirectory()) continue\n    } catch {\n      continue\n    }\n    taken.add(entry)\n  }\n  return taken\n}\n\nfunction slugIsValid(slug: string): boolean {\n  try {\n    assertValidServerSlug(slug)\n    return true\n  } catch {\n    return false\n  }\n}\n\n/** Bounded so a piped-but-TTY-looking stdin cannot spin forever (the #1719 rule). */\nconst MAX_PROMPT_ATTEMPTS = 3\n\n/**\n * The interactive choice at the conflict. Only reached through the #1719 gate\n * (`interactive` AND a TTY stdin) — a `--json`, CI or agent run never sees it\n * and gets the typed refusal instead.\n *\n * Empty input is NOT a default: replacing retires a working agent's local\n * key material, and installing alongside changes the server names every host\n * will see, so neither is the thing to do because someone pressed Enter.\n * Three unrecognised answers abort, having written nothing.\n */\nexport async function promptWiringCollisionResolution(\n  collision: WiringCollision,\n  agentName: string,\n  io: PromptIo,\n): Promise<WiringCollisionResolution> {\n  const ids = collision.superseded.map((entry) => entry.agentId).join(', ')\n  io.write(`This machine is already wired to a Haven agent with a live key: ${ids}.\\n`)\n  io.write(`Setting up \"${agentName}\" on the bare haven / haven-signer pair would replace that wiring.\\n`)\n  io.write('  r) replace — re-point haven / haven-signer at the new agent and retire the previous directory locally\\n')\n  io.write('     (tombstoned, local key files removed; you still use Remove agent\\u2026 on the Haven agent page)\\n')\n  io.write(`  a) alongside — install as a named agent (suggested: ${collision.suggestedServerName}) with its own\\n`)\n  io.write(`     haven-<name> / haven-signer-<name> pair, leaving the current wiring untouched\\n`)\n  io.write('  q) quit — nothing is written and the setup token stays unused\\n')\n  for (let attempt = 0; attempt < MAX_PROMPT_ATTEMPTS; attempt += 1) {\n    const answer = await io.question('Replace, install alongside, or quit? [r/a/q]: ')\n    if (answer === null) return { action: 'abort' }\n    const trimmed = answer.trim().toLowerCase()\n    if (trimmed === 'r' || trimmed === 'replace') return { action: 'replace' }\n    if (trimmed === 'q' || trimmed === 'quit') return { action: 'abort' }\n    if (trimmed === 'a' || trimmed === 'alongside') {\n      const typed = await io.question(`Server name [${collision.suggestedServerName}]: `)\n      if (typed === null) return { action: 'abort' }\n      const serverName = typed.trim() === '' ? collision.suggestedServerName : typed.trim()\n      try {\n        assertValidServerSlug(serverName)\n      } catch (err) {\n        io.write(`${err instanceof Error ? err.message : String(err)}\\n`)\n        continue\n      }\n      return { action: 'alongside', serverName }\n    }\n    io.write(`\"${trimmed}\" is not one of r, a, q.\\n`)\n  }\n  return { action: 'abort' }\n}\n\nasync function pathExists(path: string): Promise<boolean> {\n  try {\n    await stat(path)\n    return true\n  } catch {\n    return false\n  }\n}\n","/**\n * --unwire (#2169): remove ONE agent's runtime wiring and leave every other\n * agent and every unrelated line untouched.\n *\n * The connector has always been able to WRITE a pair into a runtime config\n * (merge* writers) and never able to ERASE one. Retiring an agent therefore\n * left its MCP pair — and on Hermes its dotenv API-key line — in place, and\n * the next setup produced the exact state --doctor's `identity_match` check\n * exists to name: the runtime quotes as one agent and signs as another. That\n * is the live-demo incident #2168/#2169 were split from.\n *\n * This module is the erase half, with the discipline of the writers inverted:\n *\n * - **Tombstone first.** The directory is retired BEFORE any config is\n *   touched, so a long-lived host that still resolves the old wrapper gets\n *   the `HAVEN-TOMBSTONE` diagnosis instead of a masked `ENOENT` park loop\n *   (#1681), and the #2155 mirrored record keeps the retirement observable\n *   even after the directory itself is deleted.\n * - **Named pairs remove by name** — `haven-<slug>` / `haven-signer-<slug>`\n *   are unique, so the name is proof of ownership.\n * - **Unnamed pairs refuse to guess.** Every unnamed agent claims the same\n *   bare `haven` / `haven-signer` names and the same `MCP_HAVEN_API_KEY`, and\n *   only the wrapper path in the config (or the key value in the dotenv)\n *   distinguishes who actually owns them (#1695, `agentIsWired`'s reasoning).\n *   If the config launches THIS directory's wrapper (or the env holds THIS\n *   agent's stored key) the entry is ours and is removed; otherwise the\n *   command REFUSES rather than unwire a different, working agent.\n * - **No custody boundary moves.** This never revokes on the backend —\n *   `connect reports, the user decides` (#1688) survives; revocation stays an\n *   owner action on the Haven agent page. What it DOES do, unlike\n *   `--tombstone`'s touch-nothing retirement, is fully tear down the TARGET\n *   directory's local half: after the tombstone it removes the directory's own\n *   key material (signer.json, any abandoned re-key) and strips the API key\n *   from identity.json, so `--doctor` reports `retired` — not `superseded`\n *   (still spend-capable) — per the doctor's mutation-proof rule that a\n *   tombstone never excuses a live key. The tombstone record and its #2155\n *   mirror survive the teardown.\n *\n * Scope mirrors the writers: Hermes YAML + dotenv, Codex TOML, and the JSON\n * MCP configs (Cursor, VS Code, VS Code Insiders, Claude Desktop).\n */\nimport { probeHostedAgentIdentity, type HostedProbeStatus } from './probes.js'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport { readFile, rm, writeFile } from 'node:fs/promises'\nimport {\n  UnreadableRuntimeConfigError,\n  hermesEnvPath,\n  removeCodexToml,\n  removeHermesEnv,\n  removeHermesYaml,\n  removeJsonMcpConfig,\n  runtimeConfigPathFor,\n} from './config-writers.js'\nimport { serverNamesFor, type ServerNames } from './server-names.js'\nimport { readRuntimeSidecar, type SignerRuntimeSidecar } from './signer-runtime.js'\nimport { TOMBSTONE_FILENAME, writeAgentTombstone } from './tombstone.js'\nimport { REKEY_PENDING_FILENAME, clearMcpServerBinding } from './storage.js'\n\nexport interface UnwireRuntimeOutcome {\n  runtime: string\n  label: string\n  path: string | null\n  status: 'removed' | 'clean' | 'refused' | 'unreadable'\n  detail?: string\n}\n\n/**\n * #3123: what happened to THIS directory's key material. Before #3123 the\n * teardown ran unconditionally — and a revoked agent's API key is exactly\n * the credential the sweep-recovery routes still accept, so `--unwire` was\n * destroying the only local means of recovering a stranded balance without\n * ever asking what the key was still good for. Owner decision (option c):\n * the connector asks the one question it can (the existing identity probe)\n * and REFUSES to destroy on every answer but \"there is nothing to preserve\";\n * an explicit flag proceeds and says what ends.\n */\nexport interface TeardownOutcome {\n  /** `destroyed` — nothing to preserve, key material removed as before; `retained` — refused, key material left in place; `forced` — removed under `--destroy-key-material`. */\n  status: 'destroyed' | 'retained' | 'forced'\n  /** The identity probe's answer, or `not_probed` when there was no stored API key + API URL to probe with. */\n  probe: HostedProbeStatus | 'not_probed'\n  detail: string\n  /** The one next step, present on `retained` (and on `forced`, naming what ended). */\n  remedy?: string\n}\n\nexport interface UnwireOutcome {\n  directory: string\n  agentId: string\n  slug: string | undefined\n  tombstoned: boolean\n  runtimes: UnwireRuntimeOutcome[]\n  teardown: TeardownOutcome\n  /** #3122: whether a local `mcp-server-binding.json` was removed (false when there was none). */\n  bindingReleased: boolean\n  /** #3259: set when the surviving ledger record could not be written; the in-place tombstone stands. */\n  mirrorError?: string\n}\n\nexport interface UnwireInput {\n  directory: string\n  /** #1696 wiring slug; when absent, read from the directory's own sidecar. */\n  slug?: string\n  /** Reason recorded in the tombstone written first (#1681). */\n  reason?: string\n  replacedBy?: string\n  /** Override for the surviving mirror root (#2155), like `--tombstone`'s own. */\n  tombstonesDir?: string\n  homeDir?: string\n  /**\n   * #3123: `--destroy-key-material`. Proceed with the local key teardown\n   * whatever the probe says. The outcome states what was destroyed and that\n   * local recovery of a stranded balance ends with it.\n   */\n  destroyKeyMaterial?: boolean\n  /** Test seam for the ONE network call on this path (the existing identity probe). */\n  probeHostedIdentity?: typeof probeHostedAgentIdentity\n  fetch?: typeof fetch\n}\n\ninterface IdentityFile {\n  agent_id?: string\n  api_key?: string\n  api_url?: string\n  hosted_mcp_url?: string\n}\n\ninterface RuntimeModel {\n  runtime: string\n  label: string\n  kind: 'yaml' | 'toml' | 'json'\n  serverRoot?: 'mcpServers' | 'servers'\n}\n\n/** One entry per supported runtime, mirroring `runtimeConfigPathFor`. */\nconst RUNTIMES: RuntimeModel[] = [\n  { runtime: 'hermes', label: 'Hermes Agent config', kind: 'yaml' },\n  { runtime: 'codex-cli', label: 'Codex config', kind: 'toml' },\n  { runtime: 'cursor', label: 'Cursor MCP config', kind: 'json', serverRoot: 'mcpServers' },\n  { runtime: 'vscode', label: 'VS Code MCP config', kind: 'json', serverRoot: 'servers' },\n  { runtime: 'vscode-insiders', label: 'VS Code Insiders MCP config', kind: 'json', serverRoot: 'servers' },\n  { runtime: 'claude-desktop', label: 'Claude Desktop config', kind: 'json', serverRoot: 'mcpServers' },\n]\n\nfunction identityAt(directory: string): Promise<IdentityFile | null> {\n  return readFile(join(directory, 'identity.json'), 'utf8')\n    .then((raw) => JSON.parse(raw) as IdentityFile)\n    .catch(() => null)\n}\n\nfunction removeForModel(text: string, model: RuntimeModel, names: ServerNames, path: string): string {\n  switch (model.kind) {\n    case 'yaml':\n      return removeHermesYaml(text, names, path)\n    case 'toml':\n      return removeCodexToml(text, names)\n    case 'json':\n      return removeJsonMcpConfig(text, model.serverRoot ?? 'mcpServers', names, path)\n  }\n}\n\nfunction envLineValue(envText: string, envKey: string): string | undefined {\n  const line = envText.split(/\\r?\\n/).find((candidate) => new RegExp(`^\\\\s*(?:export[ \\\\t]+)?${envKey}[ \\\\t]*=`).test(candidate))\n  if (!line) return undefined\n  let value = line.slice(line.indexOf('=') + 1)\n  value = value.trim()\n  if ((value.startsWith('\"') && value.endsWith('\"')) || (value.startsWith(\"'\") && value.endsWith(\"'\"))) {\n    value = value.slice(1, -1)\n  }\n  return value\n}\n\nasync function readOptionalText(path: string): Promise<string | null> {\n  try {\n    return await readFile(path, 'utf8')\n  } catch {\n    return null\n  }\n}\n\n/**\n * Unwire ONE agent: tombstone it first, then remove its pair from every\n * supported runtime config and (Hermes) dotenv file that exists. Refuses —\n * never guesses — when the bare pair is present but provably belongs to a\n * different agent.\n */\nexport async function unwireAgent(input: UnwireInput): Promise<UnwireOutcome> {\n  const homeDir = input.homeDir ?? homedir()\n  const [identity, sidecar] = await Promise.all([identityAt(input.directory), readRuntimeSidecar(input.directory)])\n  const agentId = identity?.agent_id ?? 'unknown'\n  const slug = input.slug ?? sidecar?.server_name\n  const names = serverNamesFor(slug)\n  const runtimes: UnwireRuntimeOutcome[] = []\n\n  // ── Tombstone first (#1681 ordering): the long-lived host that still\n  //    references this wrapper must hear \"retired\", never \"ENOENT\". ─────────\n  const { written: tombstoned, mirrorError } = await tombstoneDirectoryIfAbsent({\n    directory: input.directory,\n    agentId,\n    reason: input.reason ?? 'unwired via --unwire',\n    replacedBy: input.replacedBy,\n    tombstonesDir: input.tombstonesDir,\n  })\n\n  // ── Runtime configs. ──────────────────────────────────────────────────────\n  for (const model of RUNTIMES) {\n    const path = runtimeConfigPathFor(model.runtime, homeDir)\n    if (path === null) continue\n    const text = await readOptionalText(path)\n    if (text === null) continue\n    try {\n      if (!slug) {\n        // Unnamed pair: positive proof of ownership is the wrapper path.\n        // Only the wrapper in the config distinguishes two unnamed agents\n        // (#1695); without it we must not touch the bare names.\n        const owned = sidecar?.wrapper_path != null && text.includes(sidecar.wrapper_path)\n        if (!owned) {\n          const pairPresent = removeForModel(text, model, names, path) !== text\n          if (!pairPresent) continue\n          runtimes.push({\n            runtime: model.runtime,\n            label: model.label,\n            path,\n            status: 'refused',\n            detail:\n              'the bare haven / haven-signer pair in this config launches a different agent ' +\n              '(no wrapper from this directory in the file); refusing to guess which one is yours',\n          })\n          continue\n        }\n      }\n      const next = removeForModel(text, model, names, path)\n      if (next === text) continue\n      await writeFile(path, next, 'utf8')\n      runtimes.push({ runtime: model.runtime, label: model.label, path, status: 'removed' })\n    } catch (err) {\n      if (err instanceof UnreadableRuntimeConfigError) {\n        runtimes.push({ runtime: model.runtime, label: model.label, path, status: 'unreadable', detail: err.message })\n        continue\n      }\n      throw err\n    }\n  }\n\n  // ── Hermes dotenv key — the half a config-only removal misses (#2169). ────\n  const envPath = hermesEnvPath(homeDir)\n  const envText = await readOptionalText(envPath)\n  if (envText !== null) {\n    try {\n      if (!slug) {\n        // The bare key is shared by every unnamed agent; it is OURS only when\n        // its value is this directory's stored key (#1695's own hazard note).\n        const value = envLineValue(envText, names.hermesEnvKey)\n        if (value === undefined) {\n          // No managed key line at all — nothing of ours to remove here.\n        } else if (!identity?.api_key) {\n          runtimes.push({\n            runtime: 'hermes',\n            label: 'Hermes env',\n            path: envPath,\n            status: 'refused',\n            detail: 'MCP_HAVEN_API_KEY is shared by unnamed agents and this directory has no stored API key to compare against; refusing to remove another agent\\'s credential',\n          })\n        } else if (value !== identity.api_key) {\n          runtimes.push({\n            runtime: 'hermes',\n            label: 'Hermes env',\n            path: envPath,\n            status: 'refused',\n            detail: 'MCP_HAVEN_API_KEY in the Hermes env holds a different agent\\'s key; refusing to remove another agent\\'s credential',\n          })\n        } else {\n          const next = removeHermesEnv(envText, names.hermesEnvKey)\n          if (next !== envText) {\n            await writeFile(envPath, next, 'utf8')\n            runtimes.push({ runtime: 'hermes', label: 'Hermes env', path: envPath, status: 'removed' })\n          }\n        }\n      } else {\n        const next = removeHermesEnv(envText, names.hermesEnvKey)\n        if (next !== envText) {\n          await writeFile(envPath, next, 'utf8')\n          runtimes.push({ runtime: 'hermes', label: 'Hermes env', path: envPath, status: 'removed' })\n        }\n      }\n    } catch (err) {\n      if (err instanceof Error && err.message.includes('ambiguous managed key')) {\n        runtimes.push({\n          runtime: 'hermes',\n          label: 'Hermes env',\n          path: envPath,\n          status: 'refused',\n          detail: err.message,\n        })\n      } else {\n        throw err\n      }\n    }\n  }\n\n  // ── #3122: release this directory's MCP server-name binding record. ──────\n  // Independent of the key-material decision below: the wiring is gone, so a\n  // legitimately free name must not keep warning the next setup.\n  const bindingReleased = await clearMcpServerBinding(input.directory)\n\n  // ── Local teardown of THIS directory's key material (#2169 AC, #3123). ───\n  // Unlike --tombstone's touch-nothing retirement, unwire tears the target's\n  // local half down: its signer private key and any abandoned re-key are\n  // deleted, and identity.json keeps its orientation fields but drops the API\n  // key. That is what --doctor's mutation-proof rule requires before it will\n  // say `retired` instead of `superseded` (tombstone never excuses a live\n  // key), and #2155's mirrored record is what keeps the retirement observable\n  // after the keys are gone. The backend is NOT revoked — that stays an owner\n  // action on the Haven agent page.\n  //\n  // #3123 ORDER (S3): the runtime configs and the Hermes env — the copies of\n  // the API key that live in world-readable editor files — were scrubbed\n  // ABOVE, before this decision, so a refusal here leaves the key in the\n  // 0o600 credential file and in any config this run could not clean (those\n  // are reported `refused` / `unreadable` above, never silently). The\n  // decision itself asks\n  // the one question the connector can answer with the probe it already has\n  // and refuses on every answer but \"nothing to preserve\" (option c).\n  const teardown = await decideTeardown(identity, input)\n  if (teardown.status !== 'retained') await teardownLocalKeyMaterial(input.directory, identity)\n\n  return {\n    directory: input.directory, agentId, slug, tombstoned, runtimes, teardown, bindingReleased,\n    ...(mirrorError === undefined ? {} : { mirrorError }),\n  }\n}\n\nconst DESTROY_FLAG = '--destroy-key-material'\n\n/**\n * #3123 decision table. The probe (`GET /machine-payments/agent`, the agent's\n * own key) answers spend-capability on the route it calls: `ok` ⟺ active.\n * `unauthorized` is deliberately ambiguous on the backend (revoked, archived,\n * paused, unknown key all read the same) and the connector must not claim\n * more than that. No balance read exists; unknown is never \"safe to delete\".\n */\nasync function decideTeardown(identity: IdentityFile | null, input: UnwireInput): Promise<TeardownOutcome> {\n  const ended =\n    'Local recovery of a stranded delegate balance ends with it: the sweep-recovery routes accept only this ' +\n    'agent\\'s API key and delegate signature, and neither exists on this machine any more.'\n  if (!identity?.api_key || !identity.api_url) {\n    return {\n      status: input.destroyKeyMaterial ? 'forced' : 'destroyed',\n      probe: 'not_probed',\n      detail: 'No stored API key + API URL to probe with — nothing the sweep-recovery routes would accept, so nothing to preserve.',\n    }\n  }\n  const probe = await (input.probeHostedIdentity ?? probeHostedAgentIdentity)(identity.api_key, identity.api_url, input.fetch)\n  if (input.destroyKeyMaterial) {\n    return {\n      status: 'forced',\n      probe: probe.status,\n      detail: `Key material destroyed under ${DESTROY_FLAG} (probe: ${probe.status}): signer.json, any parked re-key, and the API key in identity.json.`,\n      remedy: ended,\n    }\n  }\n  switch (probe.status) {\n    case 'ok':\n      return {\n        status: 'retained',\n        probe: 'ok',\n        detail:\n          'This agent is still ACTIVE on the backend: its API key and delegate key still carry spend authority, so ' +\n          'destroying them would be a live spend-authority change. Key material kept in this directory (0o600); its MCP wiring above is gone.',\n        remedy:\n          'Use Remove agent\\u2026 on the Haven agent page (connect never revokes), then re-run --unwire; or, to delete ' +\n          `the key anyway, re-run with ${DESTROY_FLAG}.`,\n      }\n    case 'unauthorized':\n      return {\n        status: 'retained',\n        probe: 'unauthorized',\n        detail:\n          'This key no longer authenticates on normal routes (revoked, archived, paused, pending approval, rotated, ' +\n          'or not a key the backend knows — it does not say which). A stranded delegate balance MAY still exist and ' +\n          'the connector CANNOT check: this directory may hold the only local credential the sweep-recovery routes ' +\n          'would still accept. Key material kept.',\n        remedy:\n          'Recover any stranded balance first (haven_sweep_delegate from a runtime still wired to this agent, or the ' +\n          `Haven agent page), then re-run with ${DESTROY_FLAG} to remove the key material.`,\n      }\n    default:\n      return {\n        status: 'retained',\n        probe: probe.status,\n        detail:\n          `Could not verify what this key is still good for (${probe.status}). Unknown is not \"safe to delete\": ` +\n          'destroying it on a failed check would erase the evidence of a live key. Key material kept.',\n        remedy: `Retry when the backend is reachable, or re-run with ${DESTROY_FLAG} to remove the key material regardless.`,\n      }\n  }\n}\n\n/**\n * Write the #1681 tombstone unless the directory already carries one.\n * Returns whether THIS call wrote it, and — #3259 — the mirror failure when\n * the surviving ledger record could not be written (the in-place tombstone\n * still stands, so callers carry on and report it). Shared with the #2551\n * replace path, which retires a superseded directory after the new wiring is\n * written.\n */\nexport async function tombstoneDirectoryIfAbsent(input: {\n  directory: string\n  agentId: string\n  reason: string\n  replacedBy?: string\n  tombstonesDir?: string\n}): Promise<{ written: boolean; mirrorError?: string }> {\n  if ((await readOptionalText(join(input.directory, TOMBSTONE_FILENAME))) !== null) return { written: false }\n  const { mirrorError } = await writeAgentTombstone(input)\n  return mirrorError === undefined ? { written: true } : { written: true, mirrorError }\n}\n\n/**\n * The local half of a retirement: delete the signer private key and any\n * abandoned re-key, and strip the API key from `identity.json` while keeping\n * its orientation fields. This is what `--doctor`'s mutation-proof rule\n * requires before it will say `retired` instead of `superseded` — a tombstone\n * never excuses a live key. Nothing is revoked on the backend; that stays an\n * owner action on the Haven agent page. Shared by `--unwire` (#2169) and the\n * #2551 replace path.\n */\nexport async function teardownLocalKeyMaterial<T extends { api_key?: string }>(\n  directory: string,\n  identity: T | null,\n): Promise<void> {\n  await Promise.all([\n    rm(join(directory, 'signer.json'), { force: true }),\n    rm(join(directory, REKEY_PENDING_FILENAME), { force: true }),\n  ])\n  if (identity && identity.api_key !== undefined) {\n    const { api_key: _dropped, ...rest } = identity\n    await writeFile(join(directory, 'identity.json'), `${JSON.stringify(rest, null, 2)}\\n`, { mode: 0o600 })\n  }\n}\n\n/** Parse a directory's `identity.json`, or `null` when absent/unreadable. Exported for the #2551 replace path. */\nexport async function readIdentityFile(directory: string): Promise<IdentityFile | null> {\n  return identityAt(directory)\n}\n","import { join } from 'node:path'\nimport { readFile, readdir, stat } from 'node:fs/promises'\nimport { createConnectApiClient, ConnectRequestError, type ConnectApiClient, type ResolvedSetup } from './api.js'\nimport { connectorRerunCommand, resolveTokenFromAddress } from '@haven_ai/sdk'\nimport {\n  agentApiKeyPrefix,\n  generateAgentApiKey,\n  generateDelegateKey,\n  hashAgentApiKey,\n  type LocalDelegateKey,\n} from './key.js'\nimport { redactForAutomation, redactSecrets, shortAddress, withoutUserinfo } from './redact.js'\nimport { assertValidServerSlug, serverNamesFor } from './server-names.js'\nimport {\n  assertServerSlugAvailable,\n  defaultCredentialRoot,\n  preflightCredentialStorage,\n  writeConnectOutcomeRecord,\n  writeCredentialFiles,\n  writeMcpServerBinding,\n  clearMcpServerBinding,\n  listMcpServerBindings,\n  readStoredAccountAddress,\n  CONNECT_OUTCOME_FILENAME,\n  type StoredCredentialPaths,\n  type McpServerBinding,\n} from './storage.js'\nimport {\n  installRuntime,\n  runtimeInstallCapabilities,\n  supportsLocalMcp,\n  type RuntimeInstallResult,\n} from './runtime-install.js'\nimport { normalizeRuntime, resolveRuntimeSelection, runtimeProfile, runtimeVerificationInstruction, RUNTIME_FLAG_VALUES, RUNTIME_FLAG_VALUE_LIST, type RuntimeId, type RuntimeProfile } from './runtime-registry.js'\nimport { ConnectError } from './connect-error.js'\nimport {\n  defaultPromptIo,\n  installedClientHint,\n  resolveRuntimeByInstalledClientPrompt,\n  scanInstalledClients,\n  type InstalledClientHint,\n} from './installed-clients.js'\nimport {\n  deriveServerSlug,\n  detectWiringCollision,\n  listTakenDirectoryNames,\n  promptWiringCollisionResolution,\n  type WiringCollision,\n  type WiringCollisionResolution,\n} from './wiring-collision.js'\nimport { readIdentityFile, teardownLocalKeyMaterial, tombstoneDirectoryIfAbsent } from './unwire.js'\nimport { tombstonesDirForCredentialRoot } from './tombstone.js'\nimport { assertSupportedNodeVersion } from './local-mcp-runtime.js'\nimport { MCP_RUNTIME_MANIFEST } from './runtime-manifest.js'\n\nexport const CONNECTOR_VERSION = '0.10.0-alpha.0'\n\n/**\n * #3737 owner decision 4: the derived slug marks NON-production backends\n * (`<slug>-dev`); production gets the plain slug. Production is Base\n * mainnet, chain id 8453 — 84532 is Base Sepolia. Any other or unknown\n * chain id counts as non-production: an unmarked slug on a dev backend is\n * the exact confusion this exists to remove, while a `-dev` mark on an\n * exotic chain is merely cosmetic.\n */\nconst PRODUCTION_CHAIN_ID = 8453\n/** #3772: agent ids are uuids; an identity that fell back to a directory name is not one. */\nconst UUID_SHAPE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\n/** #3303: the `X-Haven-Client` value every Haven API request from this connector carries. */\nexport const CONNECTOR_CLIENT_IDENTITY = `@haven_ai/connect/${CONNECTOR_VERSION}`\n\nexport interface ConnectOptions {\n  setupToken: string\n  apiBaseUrl: string\n  runtime?: string\n  /** #1672 escape hatch: use exactly this runtime, ignoring environment detection. */\n  runtimeForce?: string\n  /**\n   * #1719: the harness an AGENT running this command reported for itself. Enters\n   * at the same precedence as `runtime`, so it can only fill a vacuum — never\n   * override a detected environment.\n   */\n  runtimeSelfReport?: string\n  /**\n   * #1719: this run may ask a human which installed client to configure. The\n   * CLI sets it for a non-`--json` run; a library caller must opt in. Combined\n   * with `deps.isTty`, it is what makes the prompt rung SKIPPED rather than\n   * answered in CI, in `--json` automation, and in library embeddings.\n   */\n  interactive?: boolean\n  credentialsDir?: string\n  environmentLabel?: string\n  /** #1696: wiring slug for a named MCP pair + slug-keyed credential dir. */\n  serverName?: string\n  /**\n   * #3737: derive the wiring slug from the agent's display name and install\n   * a NAMED pair (`haven-<slug>` / `haven-signer-<slug>`) instead of the bare\n   * one. The CLI passes this by default so that adding an agent never\n   * targets the bare pair and therefore never has to ask replace-vs-\n   * alongside; the LIBRARY keeps today's bare behaviour when neither\n   * `serverName` nor this option is set, so existing programmatic callers\n   * are unchanged. An explicit `serverName` always wins over derivation.\n   * The derived slug de-collides against EVERY directory name under the\n   * credential root, marks non-production backends with a `-dev` suffix\n   * (owner decision 4), and is refused nothing — it never displaces anyone.\n   */\n  deriveServerName?: boolean\n  /**\n   * #2551: when the bare pair on this machine is already wired to a different\n   * agent with a live key, replace it — re-point `haven` / `haven-signer` at\n   * the new agent (the #1569 remove-first install) and retire the superseded\n   * directory locally afterwards. Without it, such a collision is put to a\n   * human at a TTY and REFUSED everywhere else (`wiring_collision`), before\n   * anything is minted or written. Contradicts `serverName`, which installs\n   * alongside instead; the CLI refuses the pair.\n   */\n  replaceExistingWiring?: boolean\n  connectorVersion?: string\n  ackSigner?: boolean\n  ackLocalTools?: boolean\n  localMcp?: boolean\n  /**\n   * #1377 D: keep the process alive after registering and poll for the\n   * user's budget approval. Set false for structured/automation runs (--json)\n   * where prompt output emission matters more than narration. #2484: when\n   * UNSPECIFIED (the default), the wait runs only when stdout is a TTY — the\n   * wait exists to narrate to a watching human, and a prose run whose stdout\n   * is not a TTY (an agent tool call) skips it. An explicit true waits\n   * regardless of TTY.\n   */\n  waitForApproval?: boolean\n  /** Test/injection overrides for the approval poll cadence and clock. */\n  approvalWait?: ApprovalWaitOptions\n  /**\n   * #2528: how this run was invoked, reported to the backend at register so\n   * the onboarding funnel can segment machine-readable runs from narrated\n   * ones (D1, #2529).\n   *\n   * An explicit option rather than an inference from `waitForApproval`: that\n   * flag is already false for a prose run with no TTY (#2484) and can be set\n   * false by hand, so reading `--json` off it would mislabel real prose runs.\n   * Defaults to `'prose'` — the mode a caller who says nothing is in.\n   */\n  runMode?: 'json' | 'prose'\n}\n\n/** The stable machine-readable result emitted by `haven-connect --json`. */\nexport const CONNECT_OUTCOME_SCHEMA_VERSION = 1 as const\n\nexport type ConnectOutcomeStatus = 'complete' | 'action_required' | 'failed'\n\nexport interface ConnectOutcome {\n  schema_version: typeof CONNECT_OUTCOME_SCHEMA_VERSION\n  outcome: ConnectOutcomeStatus\n  runtime: string\n  topology: string\n  configuration: {\n    hosted_mcp: boolean\n    local_signer: boolean\n    local_mcp: boolean\n  }\n  probe: { result: string }\n  activation: {\n    restart_required: boolean\n    instruction: string\n  }\n  next_action: string\n  /**\n   * `url` is #2528, additive within schema_version 1 — the same convention\n   * #2173, #2174, #2551, #2091 and #2279 followed for this object. Present\n   * only when the backend returned one: a deployment older than #2528 sends\n   * nothing, and a key whose value is `undefined` disappears from\n   * `JSON.stringify` anyway, so a consumer must test for it rather than\n   * assume it. `required: false` runs carry no url — there is nothing to\n   * approve.\n   */\n  approval: { required: boolean; expires_at: string | null; url?: string }\n  verification: {\n    tools: readonly ['haven_get_agent', 'haven_get_allowances']\n    instruction: string\n  }\n  delegate_address?: string\n  setup_challenge_expires_at?: string\n  /**\n   * #2173, additive within schema_version 1. Both are present on a completed\n   * run and absent on `failedConnectOutcome`, which by construction has\n   * neither a registration nor a credential scan behind it.\n   *\n   * `hosted_mcp_url` is the endpoint Connect wired this run up to — written\n   * into the runtime's MCP config, or, on a manual runtime that Connect cannot\n   * configure, printed as the endpoint to enter by hand. It is deliberately\n   * NOT the `--api` backend URL: the hosted MCP\n   * server is a separate deployment, and an automation caller comparing the\n   * two used to read that intentional topology as an environment mismatch. It\n   * is non-secret — the same string already sits in the user's own config file\n   * — and carries no credential; the API key travels beside it in a header.\n   *\n   * `superseded_agent_ids` is the #1688 heads-up made structural: previously\n   * it was prose on stderr, so a `--json` caller could not see that the run it\n   * just completed left older agents alive with their own keys. Empty on a\n   * clean first run. An empty list is NOT proof of a clean machine — a scan\n   * that cannot read the credential root also yields an empty list, and the\n   * connector prefers that to failing a completed setup.\n   */\n  hosted_mcp_url?: string\n  superseded_agent_ids?: readonly string[]\n  /**\n   * #2551, additive within schema_version 1. Present only on a run that\n   * REPLACED existing wiring (`--replace`, or \"replace\" chosen at the\n   * prompt): `true` when every superseded directory was retired locally —\n   * tombstoned and its local key files removed — and `false` when the\n   * runtime install ended with an errorCode and the retirement was therefore\n   * skipped, because the old wiring may still be the only working one. It\n   * says nothing about the backend: nothing is revoked by the connector.\n   *\n   * `retired_agent_ids` names exactly WHICH directories that retirement\n   * reached — the collision set, and only the members whose tombstone and\n   * teardown both succeeded. It is deliberately a separate list from\n   * `superseded_agent_ids`, which is every OTHER directory on the machine\n   * (#1688) and so also names NAMED agents that coexist with the replaced\n   * bare pair and were never touched; reading the boolean against that list\n   * would overclaim (review finding on #2551).\n   */\n  superseded_agents_retired_locally?: boolean\n  retired_agent_ids?: readonly string[]\n  /**\n   * #3259, additive within schema_version 1: present only on a replace run\n   * where a retired directory's surviving ledger record could NOT be written —\n   * agent id → errno code (or `mirror_write_failed`). The directory is still\n   * retired (tombstoned in place, key files removed) and counts in\n   * `retired_agent_ids`; only `--doctor`'s view after the directory is deleted\n   * is lost.\n   */\n  retirement_mirror_errors?: Readonly<Record<string, string>>\n  /**\n   * #3122, additive within schema_version 1. Every OTHER credential directory\n   * on this machine that still held key material when this run began — named\n   * BEFORE the first credential write (the same list the pre-write heads-up\n   * prints), with the account each can spend from, so a `--json` caller\n   * learns of the condition without parsing prose. \"Live\" here means \"holds\n   * a stored API key locally\" — no network call is made to ask the backend\n   * whether the key still authenticates (that is the doctor's probe). Always\n   * present on a completed run, `[]` on a clean machine; like\n   * `superseded_agent_ids`, an empty list from a root that could not be read\n   * is not proof of a clean machine.\n   */\n  existing_agents_before_write?: ReadonlyArray<{ agent_id: string; account_address: string | null }>\n  // (A subset of `superseded_agent_ids`, which names every other\n  // directory with an identity.json at all — key-less and tombstoned ones\n  // included; this list is the ones that still hold a key.)\n  /**\n   * #3122, additive. Present only when this run took an MCP server name over\n   * from another agent's local binding record (`mcp-server-binding.json` in\n   * that directory): the previous holder, the backend it pointed at, when it\n   * was bound, and whether the backend changed — the case the backend cannot\n   * answer and the one that silently repoints a saved session.\n   */\n  server_name_rebound_from?: { server_name: string; agent_id: string; api_url: string; bound_at: string; backend_changed: boolean }\n  /**\n   * #3737, additive within schema_version 1: the hosted MCP server name this\n   * run actually wired — `haven-<slug>` for a named run (derived or\n   * explicit), bare `haven` for a `--bare` / `--replace` run. The mirror of\n   * what `mcpServerName` reported to the backend at register and what the\n   * completion text names, carried structurally so a `--json` caller can\n   * verify `hermes mcp test <name>` without parsing prose. Always present on\n   * a completed run; absent on `failedConnectOutcome`, which wired nothing.\n   */\n  server_name?: string\n  /**\n   * #2091, additive within schema_version 1: `message` is the redacted human\n   * refusal (automation used to get code + next_action and nothing to act\n   * on), and `allowed_runtimes` carries the valid `--runtime` retry values on\n   * runtime-selection refusals — the list the backend's setup prompt requires\n   * a retry to be drawn from, which `--json` previously discarded with the\n   * prose.\n   */\n  error?: {\n    code: string\n    next_action: string\n    message?: string\n    allowed_runtimes?: readonly string[]\n    /**\n     * #2174, additive within schema_version 1. What the installed-client scan\n     * found on THIS machine, narrowing a `runtime_undetermined` retry from the\n     * nine-value `allowed_runtimes` menu to what is actually here.\n     *\n     * A hint an agent may echo back as `--runtime`, never a selection: the\n     * outcome stays `failed` with `rerun_connect_with_explicit_runtime`, and\n     * the connector never proceeds on it (#1719's populates-never-selects\n     * invariant). Absent when the scan found nothing OR could not run —\n     * both are honestly \"no finding\"; neither is a claim the machine is bare.\n     * `suggested_runtime` appears only when one candidate is unambiguously\n     * top, so it is never the winner of an arbitrary tiebreak.\n     */\n    installed_clients?: readonly string[]\n    suggested_runtime?: string\n    /**\n     * #2551, additive within schema_version 1, on a `wiring_collision`\n     * refusal: the agents a bare-pair setup would have displaced, and a\n     * valid, collision-checked `--name` the run can be re-issued with. The\n     * refusal is a RELAY instruction — the human chooses replace-vs-alongside\n     * — so the record carries what that human needs, never a default.\n     */\n    superseded_agent_ids?: readonly string[]\n    suggested_name?: string\n  }\n}\n\nexport interface ConnectDeps {\n  api?: ConnectApiClient\n  generateKey?: () => LocalDelegateKey\n  generateApiKey?: () => string\n  preflightStorage?: typeof preflightCredentialStorage\n  writeCredentials?: typeof writeCredentialFiles\n  installRuntime?: typeof installRuntime\n  log?: (message: string) => void\n  /** JSON CLI mode must not expose owner-only credential file locations. */\n  redactPaths?: boolean\n  /** Overridable so the Node-floor refusal is testable without spawning a Node. */\n  nodeVersion?: string\n  /** Overridable so runtime detection (#1672) is testable without faking process.env. */\n  env?: NodeJS.ProcessEnv\n  /** Overridable so the #1719 TTY gate is testable without faking process.stdin. */\n  isTty?: boolean\n  /**\n   * Overridable so the #2484 non-TTY narration gate is testable without\n   * faking process.stdout. Distinct from `isTty`: that gate decides whether\n   * the stdin prompt rung can run (INTERACTIVITY); this one decides whether\n   * the budget-approval wait has a watching human to narrate to, so it is\n   * keyed on STDOUT.\n   */\n  isStdoutTty?: boolean\n  /** Overridable so the #1719 installed-client prompt is testable without readline. */\n  promptRuntime?: () => Promise<RuntimeId>\n  /**\n   * Overridable so the DEFAULT prompt thunk is observable: the call site in\n   * `runtimeSelectionPrompt` must pass the hint scan's `env` to it (#3732) —\n   * the prompt rung and the `--json` refusal describe ONE machine, so they\n   * must look at the same environment. Takes the full scan options, env\n   * included; defaults to `resolveRuntimeByInstalledClientPrompt`.\n   */\n  promptRuntimeByInstalledClient?: typeof resolveRuntimeByInstalledClientPrompt\n  /**\n   * Overridable so the #2551 replace-vs-alongside prompt is testable without\n   * readline. Reached only through the same `interactive` + TTY gate as\n   * `promptRuntime`; a `--json` or piped run never gets here.\n   */\n  promptWiringCollision?: (collision: WiringCollision, agentName: string) => Promise<WiringCollisionResolution>\n  /**\n   * Overridable so the #2173 recovery-record write is testable without a real\n   * credential directory — and so a FAILING writer can be injected to prove\n   * that a broken record write never fails a completed setup.\n   */\n  writeOutcomeRecord?: typeof writeConnectOutcomeRecord\n  /**\n   * Overridable so the #2174 refusal hint is testable without depending on\n   * which agent clients happen to be installed on the machine running the\n   * suite — and so a THROWING scan can be injected to prove the refusal\n   * degrades to its un-hinted shape.\n   */\n  scanInstalledClients?: typeof scanInstalledClients\n}\n\nexport interface ConnectResult {\n  setupId: string\n  agentId: string\n  delegateAddress: string\n  credentialPaths: StoredCredentialPaths\n  /** Additive, secret-free completion contract shared by library callers and --json. */\n  outcome: ConnectOutcome\n}\n\n/**\n * What a failing run has to hand back to the wrapper below (#2173).\n *\n * The failure record has to reach the same recovery file as the success\n * record, and the only place the credential directory exists is inside the\n * run. Reporting it into this box as soon as it exists keeps the whole body\n * un-indented; the wrapper writes the failure outcome there and re-throws the\n * error unchanged.\n *\n * A refusal that happens BEFORE credentials are written — `runtime_undetermined`,\n * an expired setup challenge, the Node floor — leaves the box empty by\n * construction. There is no directory to write into, and nothing was created\n * that a caller could need to recover.\n */\ninterface ConnectRunTrace {\n  directory?: string\n  runtime?: string\n}\n\n/**\n * The failure record a run already built, keyed on the error it threw (#2173).\n *\n * The run knows the RESOLVED runtime; a caller reconstructing the record from\n * the same error knows only the raw `--runtime` hint, and detection can\n * override that hint (#1672). Without this, one failed run could persist\n * `runtime: claude-code` to the recovery file and print `runtime: cursor` on\n * stdout — two records for one run, which is precisely the \"the file is\n * exactly what was emitted\" guarantee the recovery file rests on.\n *\n * A WeakMap rather than a property on the error: nothing is mutated, nothing\n * can be serialized into a message by accident, and the entry dies with the\n * error it describes.\n */\nconst failureOutcomesByError = new WeakMap<object, ConnectOutcome>()\n\n/**\n * The failure record for an error thrown by `runConnect` — the run's own, when\n * it built one, and a freshly derived record otherwise (a rejection that never\n * entered the run at all, such as an argument-parse refusal, or an injected\n * one in a test).\n */\nexport function failureOutcomeFor(runtimeHint: string | undefined, error: unknown): ConnectOutcome {\n  if (error !== null && typeof error === 'object') {\n    const recorded = failureOutcomesByError.get(error)\n    if (recorded) return recorded\n  }\n  return failedConnectOutcome(runtimeHint, error)\n}\n\nexport async function runConnect(options: ConnectOptions, deps: ConnectDeps = {}): Promise<ConnectResult> {\n  const trace: ConnectRunTrace = {}\n  try {\n    return await executeConnect(options, deps, trace)\n  } catch (err) {\n    // Built ONCE, from the resolved runtime, then both persisted and handed to\n    // the caller — so the file and the stdout line can never disagree. Derived\n    // even when there is no directory to write into: the caller still prints\n    // it, and the resolved runtime is the true answer either way.\n    const outcome = failedConnectOutcome(trace.runtime ?? options.runtime, err)\n    if (err !== null && typeof err === 'object') failureOutcomesByError.set(err, outcome)\n    if (trace.directory) await recordConnectOutcome(deps, trace.directory, outcome)\n    throw err\n  }\n}\n\n/**\n * Park the terminal outcome where a caller that lost the stream can read it.\n *\n * Best-effort, and the swallow lives HERE rather than in the writer: the setup\n * has already either succeeded or failed for its own reason by the time this\n * runs, and neither verdict may be changed by a filesystem write that exists\n * only as a convenience.\n */\nasync function recordConnectOutcome(\n  deps: ConnectDeps,\n  directory: string,\n  outcome: ConnectOutcome,\n): Promise<string | undefined> {\n  try {\n    return await (deps.writeOutcomeRecord ?? writeConnectOutcomeRecord)(directory, outcome)\n  } catch {\n    return undefined\n  }\n}\n\nasync function executeConnect(\n  options: ConnectOptions,\n  deps: ConnectDeps,\n  trace: ConnectRunTrace,\n): Promise<ConnectResult> {\n  // FIRST, before anything with a side effect (#1161).\n  //\n  // This runs ahead of the setup-token resolve, the storage preflight, key\n  // generation, the agent registration, and every credential write — so a\n  // refusal cannot strand a half-created agent or burn a one-shot setup token,\n  // the same discipline the hosted-MCP-URL guard adopted in #1129.\n  //\n  // It is checked on EVERY topology, which is the actual fix here. The guard\n  // already existed but only ran inside local-MCP installation, reached solely\n  // via `--local`; the default hosted-MCP + local-signer path — what nearly\n  // every user runs — never touched it. The floor was enforced on the advanced\n  // path and unenforced on the common one.\n  //\n  // Refuse rather than warn: what gets installed is the signer, which holds the\n  // delegate key and produces every payment signature. An unsupported runtime\n  // under a signing component is not a state to continue from, and npm's own\n  // EBADENGINE notice is advisory unless the user happens to run engine-strict.\n  assertSupportedNodeVersion(deps.nodeVersion, MCP_RUNTIME_MANIFEST.minimumNodeVersion)\n\n  const connectorVersion = options.connectorVersion ?? CONNECTOR_VERSION\n  const api = deps.api ?? createConnectApiClient(options.apiBaseUrl, undefined, CONNECTOR_CLIENT_IDENTITY)\n  const log = secureLogger(\n    deps.log ?? ((message) => process.stdout.write(`${message}\\n`)),\n    deps.redactPaths === true,\n  )\n  const writeCredentials = deps.writeCredentials ?? writeCredentialFiles\n  const preflightStorage = deps.preflightStorage ?? preflightCredentialStorage\n  const runRuntimeInstall = deps.installRuntime ?? installRuntime\n  const generateKey = deps.generateKey ?? generateDelegateKey\n  const generateLocalApiKey = deps.generateApiKey ?? generateAgentApiKey\n  // #1672: detection-first runtime resolution, BEFORE any side effect — the\n  // connector command no longer carries --runtime, and a hint that contradicts a\n  // confident detection must not write another client's config. Refusing here\n  // keeps the #1161 discipline: no half-created agent, no burned setup token.\n  //\n  // #1719 extends the ladder past detection: an agent that knows its own\n  // harness may say so (as a re-run carrying --runtime, which is why the\n  // backend's setup prompt now permits exactly that one change), and a human\n  // at a TTY is offered the clients actually installed here. The prompt rung\n  // is OMITTED — not answered — whenever this is not an interactive terminal\n  // run, so CI and --json automation still reach the refusal below instead of\n  // blocking on stdin.\n  const selection = await resolveRuntimeSelection(options.runtime, options.runtimeForce, {\n    env: deps.env ?? process.env,\n    selfReported: options.runtimeSelfReport,\n    promptForRuntime: runtimeSelectionPrompt(options, deps),\n  })\n  if (!selection.runtime) {\n    const hint = await installedClientHintFor(deps)\n    throw new ConnectError(\n      'runtime_undetermined',\n      'Could not determine the agent runtime: nothing was detected in this environment and no --runtime was given. ' +\n        'If you are an AI agent running this command: re-run it once, unchanged except for adding ' +\n        `--runtime <name>, naming the harness you are running in — one of: ${RUNTIME_FLAG_VALUES} ` +\n        '(the aliases cowork, codex and openclaw are accepted too). Do not guess: if your harness is ' +\n        'not one of those, use --runtime other, which stores the credentials and prints the manual MCP steps. ' +\n        installedClientProse(hint) +\n        'Nothing was written and the Haven setup token is still unused.',\n      'rerun_connect_with_explicit_runtime',\n      // #2091: the values must ride structurally too. The backend's setup\n      // prompt permits a retry only with \"one of the values that refusal\n      // lists\" — and --json discards prose, so a prose-only list deadlocked\n      // every automation run in an undetected runtime (Codex in the field:\n      // npx needs network, Codex runs network commands unsandboxed, and the\n      // unsandboxed path carries none of the CODEX_* detection vars).\n      //\n      // #2174: the list alone still leaves the retry a nine-value guess. The\n      // scan below narrows it to what is actually on this machine — as a\n      // HINT. It does not select, and this stays a refusal: see\n      // `installedClientHint`.\n      { allowedRuntimes: RUNTIME_FLAG_VALUE_LIST, ...hint },\n    )\n  }\n  const runtime = selection.runtime\n  trace.runtime = runtime\n  const installCapabilities = runtimeInstallCapabilities(runtime)\n\n  if (options.localMcp) {\n    if (!supportsLocalMcp(runtime)) {\n      throw new Error(\n        `--local (fully-local Haven MCP) is only available for Claude Code and Codex. ` +\n        `The detected runtime is ${runtimeProfile(runtime).label}. ` +\n        'Re-run without --local to use the default hosted MCP + local signer setup.',\n      )\n    }\n  }\n\n  if (selection.overrodeHint) {\n    log(`runtime: ${runtime} (detected; ignoring the ${selection.overrodeHint} hint — pass --runtime-force ${selection.overrodeHint} to override)`)\n  }\n  if (selection.discardedHint) {\n    // #1719: never silent. The caller asked for something this connector has\n    // no name for; detection is what saved the run, and the user has to be\n    // able to see that their value did nothing.\n    log(`runtime: ${runtime} (detected; \"${selection.discardedHint}\" is not a runtime Haven knows — valid values: ${RUNTIME_FLAG_VALUES})`)\n  }\n  if (selection.source === 'prompted') {\n    log(`runtime: ${runtime} (chosen at the prompt — nothing was detected in this environment)`)\n  }\n\n  log('Warming up your connection to Haven…')\n  let setup: ResolvedSetup\n  try {\n    setup = await api.resolveSetup({\n      setupToken: options.setupToken,\n      connectorVersion,\n      runtime,\n    })\n  } catch (err) {\n    throw deadSetupTokenError(err) ?? err\n  }\n  assertSetupChallengeIsUsable(setup.challenge.expires_at)\n  printSetupSummary(setup, log)\n\n  await preflightStorage({ baseDir: options.credentialsDir, warn: log })\n  if (options.serverName) {\n    // Validated HERE too, not only in the CLI parser (#1696 review): runConnect\n    // is exported, and a library caller passing a reserved or malformed slug\n    // would otherwise register a live agent and write real key material to\n    // disk before failing deep inside the config writer — the exact orphaned\n    // -agent outcome this ordering exists to prevent.\n    assertValidServerSlug(options.serverName)\n    // #1696: the slug keys the credential directory, and connect never\n    // overwrites credential files — so a taken slug must refuse HERE, before\n    // a key is minted or an agent registered, not fail on the write and\n    // leave an orphaned registration behind.\n    await assertServerSlugAvailable(options.serverName, options.credentialsDir)\n  }\n  log('Checked local credential storage — all clear.')\n\n  // #2551: resolve an existing-agent wiring collision HERE — after the local\n  // reads that can see it and BEFORE the key is minted or the agent is\n  // registered, so a declined or refused run leaves no orphaned\n  // `pending_approval` agent behind. A --name run displaces nothing (its own\n  // pair coexists with the bare one) and is never asked; the bare-pair run is\n  // what the #1569 remove-first install would otherwise resolve by silently\n  // overwriting, with the #1688 heads-up arriving after the fact.\n  //\n  // #3737: a DERIVED-slug run (`deriveServerName`, which the CLI now passes\n  // by default) also displaces nothing — it names its own pair from the\n  // agent's display name and never asks. The bare pair, and with it the\n  // replace-vs-alongside question, is reached only through an explicit\n  // `--bare` / `--replace` (owner decision 2): a default run without a name\n  // used to be the one action that could silently overwrite or refuse, and\n  // now it simply adds an agent.\n  let serverName = options.serverName\n  let replacing: WiringCollision | undefined\n  if (!serverName && options.deriveServerName) {\n    // The widest `taken` set — every directory name under the credential\n    // root, retired and key-removed ones included — so a slug freed by\n    // `--unwire` is never handed out again (`deriveServerSlug`'s contract).\n    const taken = await listTakenDirectoryNames(options.credentialsDir)\n    const nonProduction = setup.haven_wallet.chain_id !== PRODUCTION_CHAIN_ID\n    serverName = deriveServerSlug(setup.agent.name, taken, nonProduction)\n    // Belt and braces: the derivation guarantees availability, but this is\n    // the same two-layer check the explicit `--name` path applies above.\n    await assertServerSlugAvailable(serverName, options.credentialsDir)\n    const derivedNames = serverNamesFor(serverName)\n    log(\n      `Naming this agent's MCP pair from its display name: ${derivedNames.hosted} / ${derivedNames.signer}. ` +\n        'Nothing was displaced; to wire the bare haven / haven-signer pair instead, re-run with --bare, ' +\n        'or choose the name yourself with --name <slug>.',\n    )\n  } else if (!serverName) {\n    const collision = await detectWiringCollision({\n      credentialsDir: options.credentialsDir,\n      agentName: setup.agent.name,\n    })\n    if (collision) {\n      const resolution = await resolveWiringCollision(collision, setup.agent.name, options, deps)\n      if (resolution.action === 'replace') {\n        replacing = collision\n        log(\n          `Replacing the existing haven / haven-signer wiring (previous agent(s): ${supersededIds(collision)}). ` +\n            'The previous directory is retired locally once the new wiring is written; nothing is revoked.',\n        )\n      } else {\n        serverName = resolution.serverName\n        // The same two refusals the CLI's --name path applies, because the\n        // slug came from a prompt (or a proposal) rather than from argv.\n        assertValidServerSlug(serverName)\n        await assertServerSlugAvailable(serverName, options.credentialsDir)\n        log(`Installing alongside the existing wiring as a named agent: ${serverNamesFor(serverName).hosted} / ${serverNamesFor(serverName).signer}.`)\n      }\n    }\n  }\n\n  // ── #3122: the two heads-ups that used to arrive AFTER the writes. ────────\n  // Both are computed here — after the local reads, BEFORE the key is minted,\n  // the agent registered or a credential written — from local files only (no\n  // network call; the backend is not asked whether any key still\n  // authenticates). The run still succeeds: this warns, it does not refuse\n  // (owner decision 1 on #3119).\n  const existingAgents = await listExistingKeyedAgents(options.credentialsDir)\n  if (existingAgents.length > 0) {\n    log('')\n    log(\n      `Heads-up (before anything is written to this machine): it already carries ${existingAgents.length} agent director` +\n        `${existingAgents.length === 1 ? 'y' : 'ies'} with stored keys — ` +\n        existingAgents\n          .map((a) => `${a.agentId}${a.accountAddress ? ` (spends from ${shortAddress(a.accountAddress)})` : ''}`)\n          .join(', ') +\n        '. This setup creates a NEW agent alongside them and revokes nothing.',\n    )\n  }\n  const hostedNameForRun = serverNamesFor(serverName).hosted\n  let reboundFrom: ConnectOutcome['server_name_rebound_from']\n  // The NEWEST previous holder is the one a saved session most likely means\n  // (#3154 review S1): several records can claim one name when directories\n  // are retired by hand, and readdir order is neither recency nor portable.\n  const holders = (await listMcpServerBindings(options.credentialsDir))\n    .filter(({ binding }) => binding.server_name === hostedNameForRun)\n    .sort((a, b) => (a.binding.bound_at < b.binding.bound_at ? 1 : a.binding.bound_at > b.binding.bound_at ? -1 : 0))\n  const newest = holders[0]\n  if (newest) {\n    const { binding, directory } = newest\n    // Both sides stripped (#3154 code review r4): the record is written\n    // stripped since eb725028, but a record written before that may still\n    // carry userinfo, and the CURRENT run's --api may carry it too. Trailing\n    // slashes are normalised by the same helper.\n    const backendChanged = withoutUserinfo(binding.api_url) !== withoutUserinfo(options.apiBaseUrl)\n    const previousApiUrl = withoutUserinfo(binding.api_url)\n    reboundFrom = { server_name: binding.server_name, agent_id: binding.agent_id, api_url: previousApiUrl, bound_at: binding.bound_at, backend_changed: backendChanged }\n    // On a --replace run the newest holder is normally the directory this run\n    // is about to retire: the owner just consented to that, so say so rather\n    // than sound the takeover alarm about their own decision (review N3).\n    const beingReplaced = replacing?.superseded.some((entry) => entry.directory === directory) ?? false\n    log(\n      `Heads-up: the MCP server name '${binding.server_name}' was bound to agent ${binding.agent_id} on ${previousApiUrl} ` +\n        `at ${binding.bound_at} (locally recorded${holders.length > 1 ? `; ${holders.length - 1} older record${holders.length > 2 ? 's' : ''} also claim${holders.length > 2 ? '' : 's'} it` : ''}). ` +\n        (beingReplaced\n          ? `This run replaces that wiring, as you chose, with a new agent on ${withoutUserinfo(options.apiBaseUrl)}`\n          : `This run rebinds it to a new agent on ${withoutUserinfo(options.apiBaseUrl)}`) +\n        (backendChanged\n          ? ' — a DIFFERENT backend: any saved session, script or document naming this MCP server now resolves to a different backend and agent.'\n          : '.'),\n    )\n  }\n\n  const localKey = generateKey()\n  const localApiKey = generateLocalApiKey()\n  log('Minting a fresh signing key and API key — both stay on this machine.')\n  const proofSignature = await localKey.signChallenge(setup.challenge.message)\n\n  log('Introducing your agent to Haven…')\n  let registration: Awaited<ReturnType<ConnectApiClient['registerSetup']>>\n  try {\n    registration = await api.registerSetup({\n      setupToken: options.setupToken,\n      connectorVersion,\n      runtime,\n      challengeId: setup.challenge.id,\n      delegateAddress: localKey.address,\n      proofSignature,\n      apiKeyHash: hashAgentApiKey(localApiKey),\n      apiKeyPrefix: agentApiKeyPrefix(localApiKey),\n      // #1878: report the pair we are ACTUALLY wiring, bare pair included, so\n      // the dashboard can name it. Derived here rather than sent as the raw\n      // slug — `serverNamesFor` is the one place the naming rule lives, and\n      // the hosted name is what a user pastes into an MCP config.\n      mcpServerName: serverNamesFor(serverName).hosted,\n      // #2528: 'prose' is the default because it is what a caller who says\n      // nothing is doing — the library entry point is not a --json run.\n      runMode: options.runMode ?? 'prose',\n      connectorContext: {\n        environment_label: options.environmentLabel ?? 'Local workspace',\n        config_target: installCapabilities.canWriteRuntimeConfig\n          ? 'agent runtime MCP config'\n          : 'local credential files',\n      },\n      installCapabilities,\n    })\n  } catch (err) {\n    // #2091 review: the token can die HERE too — register happens after\n    // runtime detection, key generation, and any interactive prompt, well\n    // inside the 30-minute TTL race — and the backend's 410 wording carries\n    // no \"challenge\" for the legacy regex below to catch.\n    const dead = deadSetupTokenError(err)\n    if (dead) throw dead\n    if (isExpiredSetupChallenge(err)) {\n      throw new Error(\n        'The Haven setup challenge expired while connecting. Return to Haven, start a fresh connection, and run its new connector command. Do not reuse or paste credentials.',\n      )\n    }\n    throw err\n  }\n\n  log(`Registered signing address with Haven: ${shortAddress(registration.delegate_address)}.`)\n\n  log('Tucking your credentials away safely on disk…')\n  const credentialPaths = await writeCredentials({\n    baseDir: options.credentialsDir,\n    agentId: registration.agent_id,\n    serverName,\n    apiKey: localApiKey,\n    delegateKey: localKey.privateKey,\n    delegateAddress: localKey.address,\n    accountAddress: setup.haven_wallet.address,\n    chainId: setup.haven_wallet.chain_id,\n    network: setup.haven_wallet.network,\n    agentBudget: setup.agent_budget.map((budget) => ({\n      token_symbol: budget.token_symbol,\n      allowance_amount: budget.allowance_amount,\n      reset_period_min: budget.reset_period_min,\n    })),\n    apiUrl: options.apiBaseUrl,\n    hostedMcpUrl: registration.hosted_mcp_url,\n    x402BindingSigner: setup.x402_binding_signer ?? undefined,\n    warn: log,\n  })\n  // From here on a failure has somewhere to leave its verdict (#2173).\n  trace.directory = credentialPaths.directory\n  // #3122: record what this setup bound, beside the outcome record. Non-secret\n  // by construction (no key material is passed in); best-effort like the\n  // outcome record — never lets a completed write fail.\n  try {\n    const bindingRecord: McpServerBinding = {\n      version: 1,\n      server_name: hostedNameForRun,\n      signer_name: serverNamesFor(serverName).signer,\n      agent_id: registration.agent_id,\n      api_url: withoutUserinfo(options.apiBaseUrl), // never persist `user:pass@` (#3154 doc review r2)\n      ...(registration.hosted_mcp_url ? { hosted_mcp_url: registration.hosted_mcp_url } : {}),\n      bound_at: new Date().toISOString(),\n    }\n    await writeMcpServerBinding(credentialPaths.directory, bindingRecord)\n  } catch {\n    // Best-effort, like the outcome record — and no error text here, which\n    // would carry the directory path into a run whose output is redacted.\n    log('Could not record the MCP server-name binding locally (non-fatal; the next setup cannot see this binding).')\n  }\n  log(`Stored Haven identity credential locally: ${credentialPaths.identityPath}`)\n  log(`Stored local signer credential locally: ${credentialPaths.signerPath}`)\n  log(`Stored non-secret agent orientation locally: ${credentialPaths.agentPath}`)\n  if (setup.x402_binding_signer) {\n    log('Configured x402 binding signer for the local signer.')\n  } else {\n    // Fail loud here rather than silently at x402 sign time: without a trusted\n    // binding signer the edge signer refuses to sign x402 funding hashes.\n    log(\n      'Warning: Haven did not provide an x402 binding signer, so x402 payments will not sign ' +\n        'until HAVEN_X402_BINDING_SIGNER is set for the signer. Non-x402 payments are unaffected.',\n    )\n  }\n\n  const runtimeInstall = await runRuntimeInstall({\n    runtime,\n    hostedMcpUrl: registration.hosted_mcp_url,\n    apiKey: localApiKey,\n    signerPath: credentialPaths.signerPath,\n    identityPath: credentialPaths.identityPath,\n    credentialDirectory: credentialPaths.directory,\n    environmentLabel: options.environmentLabel ?? 'Local workspace',\n    ackSigner: options.ackSigner,\n    ackLocalTools: options.ackLocalTools,\n    localMcp: options.localMcp,\n    serverName,\n  }, {\n    onProgress: log,\n    // #1543: report \"runtime configured\" the moment the config write settles,\n    // so the dashboard can expose its budget-approval controls without\n    // waiting on the probes and skill install — a tail that approval does not\n    // depend on. Silent and best-effort: the complete report below remains\n    // authoritative (it overwrites these keys, adding the probe verdicts and\n    // skill state), so an early failure costs nothing but the head start.\n    onRuntimeConfigured: async (early) => {\n      try {\n        await api.updateInstallStatus(registration.setup_id, localApiKey, {\n          runtime: early.runtime,\n          connectorVersion,\n          runtimeMcpMode: early.runtimeMcpMode,\n          hostedMcpConfigured: early.hostedMcpConfigured,\n          localSignerConfigured: early.localSignerConfigured,\n          localMcpConfigured: early.localMcpConfigured,\n          credentialFilesWritten: true,\n          signerAcknowledged: early.signerAcknowledged,\n          localMcpAcknowledged: early.localMcpAcknowledged,\n          restartRequired: early.restartRequired,\n          nextUserAction: early.nextUserAction,\n          errorCode: early.errorCode ?? null,\n          environmentLabel: options.environmentLabel ?? 'Local workspace',\n        })\n        // #2279: THIS report landing is the exact moment the dashboard's\n        // approve-budget controls unlock — so say so now, imperatively,\n        // instead of running the install tail (probes, consent, skill) in\n        // silence and only asking after it finishes. The field report: the\n        // user watched the live button for minutes while the terminal said\n        // nothing about it.\n        //\n        // Two distinct gates, from review. Liveness: the dashboard unlocks\n        // on any DELIVERED report, clean or errored (`runtimeConfigured ||\n        // installErrored`, useAgentConnectionSetup.ts) — so only a report\n        // that never arrived (the catch below) may leave the button dead.\n        // Coherence: the CTA also stays silent when the errorCode's own\n        // completion handoff will say \"start a fresh connection\" — a fresh\n        // connection mints a NEW agent (#1688), so \"approve now\" would spend\n        // the approval on a setup this very run is about to disown. The one\n        // errorCode whose handoff still recommends approving is\n        // manual_runtime_setup_required. One name for the gate: the budget\n        // (#1542).\n        if (!early.errorCode || early.errorCode === 'manual_runtime_setup_required') {\n          // #2484: the CTA carries the approval-relevant facts — budget\n          // amount/token/period and the wallet label + network — so an agent\n          // relaying it verbatim hands the user everything without a second\n          // call. No secrets: every value here is already in the\n          // printSetupSummary output; nothing in it is a key or an address.\n          log(approveBudgetCta(setup, registration.approval_url))\n        }\n      } catch {\n        // ignore — the final report follows either way\n      }\n    },\n  })\n  printRuntimeInstall(runtimeInstall, log)\n\n  // Tell the user they're done and what to do next BEFORE the telemetry call —\n  // the install-status report is best-effort and must not sit between them and\n  // the \"you're finished\" signal. The agent who reported the setup couldn't tell\n  // whether the connector had finished; this affirms it explicitly. Only claim\n  // completion when the runtime install actually succeeded — an errorCode means\n  // manual steps remain (e.g. an unrecognized runtime), so don't overstate it.\n  if (runtimeInstall.errorCode) {\n    log('Haven setup needs a couple more steps on this machine — see the notes above.')\n  } else {\n    log('Haven setup on this machine is complete.')\n  }\n\n  // #2551: a REPLACE retires the superseded directory locally, but only once\n  // the new wiring is actually written — an install that ended with an\n  // errorCode may have left the old wiring as the only working one, and\n  // retiring its key behind that would fail open into \"no agent works\".\n  // Local retirement = tombstone (#1681) + the UNCONDITIONAL key-material\n  // teardown (#2169), so --doctor reads `retired`, not `superseded`. #3123\n  // made --unwire probe before that teardown; this path deliberately does\n  // not — the owner has just consented to overwrite — and whether it should\n  // is the #3119 follow-up, stated, not silently inherited.\n  // Nothing is revoked: that stays the owner's action on the Haven agent page.\n  let supersededAgentsRetiredLocally: boolean | undefined\n  const retiredAgentIds: string[] = []\n  const retirementMirrorErrors: Record<string, string> = {}\n  if (replacing) {\n    if (runtimeInstall.errorCode) {\n      supersededAgentsRetiredLocally = false\n      log(\n        `Previous agent(s) ${supersededIds(replacing)} were NOT retired: the runtime install did not complete, ` +\n          'so their wiring may still be the only working one. Resolve the install, then retire them with ' +\n          `${RERUN_HINT} --unwire <dir>.`,\n      )\n    } else {\n      supersededAgentsRetiredLocally = true\n      for (const entry of replacing.superseded) {\n        try {\n          const { mirrorError } = await tombstoneDirectoryIfAbsent({\n            directory: entry.directory,\n            agentId: entry.agentId,\n            reason: 'replaced by a new setup (--replace)',\n            replacedBy: registration.agent_id,\n            // #3251: the ledger follows this run's credential root (default\n            // root → ~/.haven/tombstones, as before; any other → <root>/.tombstones).\n            tombstonesDir: tombstonesDirForCredentialRoot(options.credentialsDir),\n          })\n          // #3259: a mirror failure no longer throws — the in-place tombstone\n          // is written, so the key teardown below MUST still run, or the\n          // directory reads retired while its key can still spend.\n          if (mirrorError !== undefined) {\n            retirementMirrorErrors[entry.agentId] = mirrorError\n            log(\n              `Warning: the surviving tombstone record for ${entry.agentId} could not be written to ` +\n                `${tombstonesDirForCredentialRoot(options.credentialsDir)} (${mirrorError}). ` +\n                'The in-place TOMBSTONE.json stands; --doctor will not list this retirement once the directory is deleted.',\n            )\n          }\n          await teardownLocalKeyMaterial(entry.directory, await readIdentityFile(entry.directory))\n          // #3122: a retired directory releases its server-name binding.\n          await clearMcpServerBinding(entry.directory)\n          retiredAgentIds.push(entry.agentId)\n          log(`Retired previous agent ${entry.agentId} locally: tombstoned, local key files removed.`)\n        } catch (err) {\n          supersededAgentsRetiredLocally = false\n          log(`Could not retire previous agent ${entry.agentId} locally: ${err instanceof Error ? err.message : String(err)}`)\n        }\n      }\n    }\n  }\n\n  // #1688: a re-run minted a NEW agent, and nothing retires the old one — the\n  // previous directory keeps an API key and a signing key, and any host that\n  // started before this run keeps spending as that agent. Name the superseded\n  // agents here, at the moment the user is watching, with the one action only\n  // they can take. Connect never revokes or deletes credentials itself.\n  // `null` means the scan could not run — kept apart from `[]` all the way to\n  // the install-status report (#2561), even though the `--json` outcome below\n  // still flattens it to `[]` for compatibility.\n  let supersededScan: string[] | null = null\n  let supersededAgentIds: string[] = []\n  try {\n    supersededScan = await listOtherAgentIds(options.credentialsDir, credentialPaths.directory)\n    supersededAgentIds = supersededScan ?? []\n    if (supersededAgentsRetiredLocally === true) {\n      // #2551: the local half is done; what remains is the owner's half, and\n      // the restart every long-lived host still needs (#1681).\n      log('')\n      log(\n        `Replaced: previous agent(s) ${supersededIds(replacing!)} are retired on this machine but NOT revoked — ` +\n          'use Remove agent\\u2026 on the Haven agent page for each (it ends their live budgets), then restart EVERY long-lived host (gateways, TUI workers, ' +\n          'editors): each holds the MCP wiring snapshot from its own start time, and the tombstone speaks only ' +\n          'when a stale host next probes the old path.',\n      )\n    } else if (supersededAgentIds.length > 0) {\n      // #3830: this list is every OTHER agent directory on the machine, not a\n      // replace set — since #3737 a run without `--name` adds a named agent\n      // alongside the ones already here. So the text claims only what is true\n      // of ANY id in it (a normal run, a `--replace` run whose local\n      // retirement was skipped, a key-less or tombstoned directory): the\n      // directory exists, and this run revoked nothing. Never \"previous\", and\n      // a host acting as its own agent is not described as a fault.\n      log('')\n      log(\n        `Heads-up: other agent directories on this machine — ${supersededAgentIds.join(', ')}. ` +\n          'This setup created a NEW agent and revoked none of them; any not revoked in Haven keep their own keys and any budgets.',\n      )\n      log(\n        'To retire one you no longer use: use Remove agent\\u2026 on its Haven agent page (it ends its live budget), restart any ' +\n          'long-lived host (gateways, TUI workers, editors) still wired to it — each holds the MCP wiring snapshot from its own start time — ' +\n          `and remove its directory under ~/.haven/agents (or ${RERUN_HINT} --tombstone <dir> to leave a diagnostic in its place). ` +\n          `To rewire the bare haven / haven-signer pair instead of adding an agent, re-run with --replace. Run ${RERUN_HINT} --doctor to check which keys are still live.`,\n      )\n    }\n  } catch {\n    // Best-effort — never let the heads-up break a completed setup. The\n    // outcome's `superseded_agent_ids` then reports the empty list, the same\n    // thing a genuinely clean machine reports: a scan that could not run is\n    // not evidence, and the field's doc comment says so rather than letting a\n    // caller read emptiness as a guarantee.\n  }\n\n  // Report the completed runtime state before polling for budget approval.\n  // The dashboard intentionally withholds approval controls until it knows the\n  // local runtime is configured; polling first would wait on controls the\n  // connector itself has not made available yet. Since #1543 the unlock\n  // usually happened already, via the early config-written report above —\n  // this complete report refines it with the probe verdicts and skill state,\n  // and stays the fallback unlock path when the early one failed. It remains\n  // best-effort readiness metadata only: a failed report cannot activate the\n  // agent or change its budget authority.\n  try {\n    await api.updateInstallStatus(registration.setup_id, localApiKey, {\n      runtime: runtimeInstall.runtime,\n      connectorVersion,\n      runtimeMcpMode: runtimeInstall.runtimeMcpMode,\n      hostedMcpConfigured: runtimeInstall.hostedMcpConfigured,\n      localSignerConfigured: runtimeInstall.localSignerConfigured,\n      localMcpConfigured: runtimeInstall.localMcpConfigured,\n      credentialFilesWritten: true,\n      signerAcknowledged: runtimeInstall.signerAcknowledged,\n      localMcpAcknowledged: runtimeInstall.localMcpAcknowledged,\n      activationCommandAvailable: Boolean(runtimeInstall.activationCommand),\n      skillInstalled: runtimeInstall.skillInstalled,\n      probeResult: runtimeInstall.probeResult,\n      restartRequired: runtimeInstall.restartRequired,\n      nextUserAction: runtimeInstall.nextUserAction,\n      errorCode: runtimeInstall.errorCode,\n      environmentLabel: options.environmentLabel ?? 'Local workspace',\n      // The raw scan result, `null` and all — NOT the flattened\n      // `supersededAgentIds` the outcome carries. Flattening here would hand\n      // the dashboard the same ambiguity this field exists to remove (#2561).\n      supersededAgentIds: supersededScan,\n    })\n  } catch (err) {\n    log(`Could not report install status to Haven: ${err instanceof Error ? err.message : String(err)}`)\n  }\n\n  // #3772: tell Haven which agents THIS run retired, so a session still running\n  // as one of them is warned on its own reads. Only `retiredAgentIds` (the\n  // directories whose tombstone and teardown succeeded) — never the\n  // `supersededScan`, which names every other agent on the machine. Identity can\n  // fall back to a directory name, so non-uuid ids are dropped. Best-effort: a\n  // failure (or an older backend's 404) is a note, never a change of outcome.\n  const reportableRetiredIds = [...new Set(retiredAgentIds.filter((id) => UUID_SHAPE.test(id)))]\n  if (reportableRetiredIds.length > 0 && api.reportRetiredAgents) {\n    try {\n      await api.reportRetiredAgents({\n        setupId: registration.setup_id,\n        apiKey: localApiKey,\n        retiredAgentIds: reportableRetiredIds,\n      })\n    } catch (err) {\n      log(`Could not tell Haven which agents were retired: ${err instanceof Error ? err.message : String(err)}`)\n    }\n  }\n\n  // #1377 D: stay alive through the approval instead of going dead exactly\n  // while the user acts. Skipped in structured/automation mode\n  // (waitForApproval: false — the --json contract emits promptly) and when\n  // the install itself needs manual completion first. The observed outcome\n  // shapes the printed next steps (#1542): an approval the wait just\n  // celebrated must not be requested again two lines later.\n  //\n  // #2484: a prose run whose STDOUT is not a TTY also skips the wait unless\n  // the caller explicitly demands it. The wait exists to narrate live to a\n  // watching human; an agent running the prose command as a tool call has no\n  // watching human, and before this it sat opaque for up to 3 minutes while\n  // the CTA it could have relayed was trapped inside the unfinished command's\n  // output. Keyed on STDOUT rather than STDIN on purpose: the #1719 prompt\n  // gate keys on stdin because it decides INTERACTIVITY; this gate decides\n  // NARRATION. An explicit waitForApproval: true from a library caller still\n  // waits regardless of TTY.\n  let approval: BudgetApprovalOutcome | undefined\n  const narrateApprovalWait =\n    options.waitForApproval === true ||\n    (options.waitForApproval === undefined && (deps.isStdoutTty ?? Boolean(process.stdout.isTTY)))\n  if (narrateApprovalWait && !runtimeInstall.errorCode) {\n    approval = await waitForBudgetApproval(api, registration.setup_id, localApiKey, log, options.approvalWait)\n  }\n\n  printNextSteps(runtimeInstall, log, approval, registration.approval_url)\n\n  const outcome = completionOutcome({\n    runtimeInstall,\n    delegateAddress: registration.delegate_address,\n    hostedMcpUrl: registration.hosted_mcp_url,\n    // #3737: the resolved name — derived, explicit, or the bare pair — rides\n    // the machine-readable outcome alongside the prose completion text.\n    serverName,\n    supersededAgentIds,\n    supersededAgentsRetiredLocally,\n    ...(replacing ? { retiredAgentIds } : {}),\n    ...(Object.keys(retirementMirrorErrors).length > 0 ? { retirementMirrorErrors } : {}),\n    existingAgentsBeforeWrite: existingAgents.map((a) => ({ agent_id: a.agentId, account_address: a.accountAddress })),\n    ...(reboundFrom ? { serverNameReboundFrom: reboundFrom } : {}),\n    // #3772: only when the install completed. An install that ended with an\n    // error code may not have written the wiring, and on --replace it leaves the\n    // old agent's wiring as possibly the only working one (retirement is skipped\n    // on the same condition) — so it gets no such sentence. That includes\n    // manual_runtime_setup_required, deliberately: the connector wrote nothing\n    // and the manual instruction already says to start a fresh session. A\n    // --replace names every displaced agent even when no binding record exists\n    // (pre-0.4.0 wiring, or a failed best-effort write).\n    ...(!runtimeInstall.errorCode && (replacing || reboundFrom)\n      ? {\n          staleSession: {\n            agentIds: [...new Set([...(replacing?.superseded.map((entry) => entry.agentId) ?? []), ...(reboundFrom ? [reboundFrom.agent_id] : [])])],\n            ...(reboundFrom?.backend_changed ? { otherBackendAgentId: reboundFrom.agent_id } : {}),\n          },\n        }\n      : {}),\n    setupChallengeExpiresAt: setup.challenge.expires_at,\n    approvalRequired: registration.agent_status === 'pending_approval',\n    approvalUrl: registration.approval_url,\n  })\n\n  // #2173: park the verdict on disk before returning it. A harness whose watch\n  // window closed during the cold signer install gets the same object here that\n  // it missed on stdout — including the restart instruction and the read-only\n  // verification sequence. The FILENAME only: the credential directory is\n  // deliberately withheld from `--json` output, and naming it on the progress\n  // stream would put back what `redactPaths` takes out.\n  if (await recordConnectOutcome(deps, credentialPaths.directory, outcome)) {\n    log(`Saved this run's outcome to ${CONNECT_OUTCOME_FILENAME} in the agent's credential directory.`)\n  }\n\n  return {\n    setupId: registration.setup_id,\n    agentId: registration.agent_id,\n    delegateAddress: registration.delegate_address,\n    credentialPaths,\n    outcome,\n  }\n}\n\n\n/**\n * #3772: the warning a rebind owes the user. Connect re-points the server name\n * on disk, but an MCP client that is already running keeps the entries it\n * loaded at start-up, so that session goes on acting as the previous agent.\n * Connect revokes nothing in Haven (a replace retires the old directory\n * locally only), so the previous agent may still be able to spend.\n */\nexport function staleSessionNotice(previousAgentIds: readonly string[], otherBackendAgentId?: string): string {\n  const one = previousAgentIds.length === 1\n  return (\n    `Any session that was already running keeps acting as the previous agent${one ? '' : 's'} (${previousAgentIds.join(', ')}) until it is restarted, ` +\n    `and ${one ? 'that agent' : 'they'} may still be active in Haven` +\n    (otherBackendAgentId ? ` (${otherBackendAgentId} is on the backend it was created on, not this one)` : '') +\n    `: if ${one ? 'it' : 'they'} should no longer spend, use Remove agent\\u2026 on the Haven agent page (it ends ${one ? 'its' : 'their'} live budgets).`\n  )\n}\nexport function completionOutcome(input: {\n  runtimeInstall: RuntimeInstallResult\n  delegateAddress: string\n  hostedMcpUrl?: string\n  /** #3737: the resolved wiring slug; absent means the bare pair. */\n  serverName?: string\n  supersededAgentIds?: readonly string[]\n  /** #2551: only a replace run sets these; see the outcome fields' doc comments. */\n  supersededAgentsRetiredLocally?: boolean\n  retiredAgentIds?: readonly string[]\n  /** #3259: only set when a retirement's ledger mirror failed. */\n  retirementMirrorErrors?: Readonly<Record<string, string>>\n  setupChallengeExpiresAt?: string\n  approvalRequired: boolean\n  approvalUrl?: string\n  existingAgentsBeforeWrite?: ReadonlyArray<{ agent_id: string; account_address: string | null }>\n  serverNameReboundFrom?: ConnectOutcome['server_name_rebound_from']\n  /** #3772: set only when this run re-pointed wiring another agent held. */\n  staleSession?: { agentIds: readonly string[]; otherBackendAgentId?: string }\n}): ConnectOutcome {\n  const { runtimeInstall } = input\n  const manualSetup = runtimeInstall.errorCode === 'manual_runtime_setup_required'\n  const nextAction = runtimeInstall.nextUserAction\n  const outcome: ConnectOutcome = {\n    schema_version: CONNECT_OUTCOME_SCHEMA_VERSION,\n    outcome: runtimeInstall.errorCode ? 'action_required' : 'complete',\n    runtime: runtimeInstall.runtime,\n    topology: runtimeInstall.runtimeMcpMode,\n    configuration: {\n      hosted_mcp: runtimeInstall.hostedMcpConfigured,\n      local_signer: runtimeInstall.localSignerConfigured,\n      local_mcp: runtimeInstall.localMcpConfigured,\n    },\n    probe: { result: runtimeInstall.probeResult },\n    activation: {\n      restart_required: runtimeInstall.restartRequired,\n      instruction:\n        (manualSetup\n          ? 'Finish the manual MCP setup using the secret-free references shown in normal Connect output, then start a fresh session.'\n          : runtimeProfile(runtimeInstall.runtime).activationInstruction) +\n        // #3772: a rebind changes which agent the server name means, but a\n        // session that is already running keeps the config it loaded — it\n        // goes on acting as the previous agent, which Connect never revokes.\n        (input.staleSession && input.staleSession.agentIds.length > 0\n          ? ` ${staleSessionNotice(input.staleSession.agentIds, input.staleSession.otherBackendAgentId)}`\n          : ''),\n    },\n    next_action: nextAction,\n    approval: {\n      required: input.approvalRequired,\n      expires_at: null,\n      // Only when there is something to approve AND the backend supplied a\n      // link. Never synthesised here: the connector does not know the\n      // dashboard's origin, and a guessed URL is worse than none — it is the\n      // \"do not invent one\" rule the agent runbook states, applied to the\n      // tool rather than the agent.\n      ...(input.approvalRequired && input.approvalUrl ? { url: input.approvalUrl } : {}),\n    },\n    verification: {\n      tools: ['haven_get_agent', 'haven_get_allowances'] as const,\n      instruction: runtimeVerificationInstruction(runtimeInstall.runtime),\n    },\n    // The backend contract supplies a 20-byte address. If an unexpected\n    // malformed value arrives, do not echo it into an automation-facing\n    // record; the human log has already been redacted separately.\n    delegate_address: /^0x[0-9a-fA-F]{40}$/.test(input.delegateAddress)\n      ? shortAddress(input.delegateAddress)\n      : '[delegate-address-redacted]',\n    // The endpoint Connect wrote into the runtime's MCP config, verbatim — the\n    // same string that already sits in the user's own config file. Passed\n    // through the secret filter anyway: this is the automation contract, the\n    // value is server-supplied, and belts are cheap (the #1589 stance).\n    ...(input.hostedMcpUrl ? { hosted_mcp_url: redactSecrets(input.hostedMcpUrl) } : {}),\n    // Always emitted on a completed run, empty list included: \"no superseded\n    // agents\" is a fact a caller needs, and an omitted key would be\n    // indistinguishable from an older connector that never reported it.\n    superseded_agent_ids: input.supersededAgentIds ?? [],\n    ...(input.supersededAgentsRetiredLocally !== undefined\n      ? { superseded_agents_retired_locally: input.supersededAgentsRetiredLocally }\n      : {}),\n    ...(input.retiredAgentIds ? { retired_agent_ids: input.retiredAgentIds } : {}),\n    ...(input.retirementMirrorErrors ? { retirement_mirror_errors: input.retirementMirrorErrors } : {}),\n    // #3122: always emitted on a completed run (empty list included), for the\n    // same reason as superseded_agent_ids above.\n    existing_agents_before_write: input.existingAgentsBeforeWrite ?? [],\n    // #3737: the resolved hosted server name — always present on a completed\n    // run, bare pair included, so a caller never has to parse the prose.\n    server_name: serverNamesFor(input.serverName).hosted,\n    ...(input.serverNameReboundFrom ? { server_name_rebound_from: input.serverNameReboundFrom } : {}),\n    ...(input.setupChallengeExpiresAt ? { setup_challenge_expires_at: input.setupChallengeExpiresAt } : {}),\n    ...(runtimeInstall.errorCode\n      ? { error: { code: runtimeInstall.errorCode, next_action: nextAction } }\n      : {}),\n  }\n  return outcome\n}\n\n/**\n * The installed-client scan, as a hint on the `runtime_undetermined` refusal\n * (#2174).\n *\n * Best-effort and read-only: `scanInstalledClients` does filesystem existence\n * checks and nothing else, and this runs at a point where no setup token has\n * been resolved and no key or credential exists. A scan that throws degrades\n * to the un-hinted refusal rather than replacing a precise refusal with a\n * filesystem error — the caller's problem is still \"name your runtime\", and\n * an `EACCES` on someone's home directory must not bury that.\n *\n * Returns `{}` rather than an empty list when the scan found nothing, so the\n * refusal carries no `installed_clients` key at all: \"the scan found none\" and\n * \"the scan could not run\" are both honestly represented by absence, whereas\n * an empty array would assert a finding neither case made.\n */\nasync function installedClientHintFor(deps: ConnectDeps): Promise<Partial<InstalledClientHint>> {\n  try {\n    const candidates = await (deps.scanInstalledClients ?? scanInstalledClients)({ env: deps.env })\n    const hint = installedClientHint(candidates)\n    return hint.installedClients.length > 0 ? hint : {}\n  } catch {\n    return {}\n  }\n}\n\n/**\n * The same finding in the prose channel, so the human and machine refusals\n * cannot say different things about the same machine. Phrased as evidence\n * (\"Haven can see …\"), never as an instruction to use it: the retry is still\n * the agent's explicit choice.\n */\nfunction installedClientProse(hint: Partial<InstalledClientHint>): string {\n  const found = hint.installedClients ?? []\n  if (found.length === 0) return ''\n  const suggestion = hint.suggestedRuntime\n    ? ` The likeliest is ${hint.suggestedRuntime}, but Haven will not choose for you — pass it yourself if it is right.`\n    : ' Haven will not choose between them for you.'\n  return `Haven can see these agent clients installed here, likeliest first: ${found.join(', ')}.${suggestion} `\n}\n\n/**\n * The prompt rung's gate (#1719), in one place so the two conditions that\n * SKIP it cannot drift apart: a run that is not interactive (`--json`, a\n * library embedding) and a run whose stdin is not a terminal (CI, a pipe).\n * Returning `undefined` omits the rung from the ladder entirely, so those runs\n * reach the `runtime_undetermined` refusal instead of blocking on stdin.\n */\nfunction runtimeSelectionPrompt(\n  options: ConnectOptions,\n  deps: ConnectDeps,\n): (() => Promise<RuntimeId>) | undefined {\n  if (!interactivePromptAllowed(options, deps)) return undefined\n  if (deps.promptRuntime) return deps.promptRuntime\n  // The prompt's scan gets the same `env` the hint scan got (#3732): both\n  // rungs describe ONE machine, so they must look at the same environment.\n  return () => (deps.promptRuntimeByInstalledClient ?? resolveRuntimeByInstalledClientPrompt)({ env: deps.env })\n}\n\n/**\n * The ONE interactive gate (#1719), shared by every prompt rung so a second\n * prompt cannot grow its own slightly different conditions (#2551 review):\n * the caller opted in (`interactive`, which the CLI sets for a non-`--json`\n * run) AND stdin is a terminal. The TTY gate is checked BEFORE any injected\n * prompt, not after: an override that could skip it would make the gate\n * untestable through the seam that exists to test it.\n */\nfunction interactivePromptAllowed(options: ConnectOptions, deps: ConnectDeps): boolean {\n  if (options.interactive !== true) return false\n  return deps.isTty ?? Boolean(process.stdin.isTTY)\n}\n\nfunction supersededIds(collision: WiringCollision): string {\n  return collision.superseded.map((entry) => entry.agentId).join(', ')\n}\n\n/**\n * #2551: the decision at the conflict. `--replace` answers it for an\n * unattended run; a human at a TTY is asked; every other run is refused with\n * a typed error that is itself a RELAY instruction — the dashboard's setup\n * prompt permits an agent `--json`, `--runtime` after a `runtime_undetermined`\n * refusal, and — only once the user has answered this refusal — one re-run\n * with the flag the user chose (#3689), so the refusal tells the agent to hand\n * the choice to its user rather than to add a flag on its own initiative.\n * Never a default: replacing retires a working agent's local key material,\n * and installing alongside changes the server names every host sees.\n */\nasync function resolveWiringCollision(\n  collision: WiringCollision,\n  agentName: string,\n  options: ConnectOptions,\n  deps: ConnectDeps,\n): Promise<Exclude<WiringCollisionResolution, { action: 'abort' }>> {\n  if (options.replaceExistingWiring) return { action: 'replace' }\n  if (interactivePromptAllowed(options, deps)) {\n    const prompt =\n      deps.promptWiringCollision ??\n      ((c: WiringCollision, name: string) => promptWiringCollisionResolution(c, name, defaultPromptIo()))\n    const resolution = await prompt(collision, agentName)\n    if (resolution.action === 'abort') {\n      throw new ConnectError(\n        'wiring_collision_declined',\n        `Setup stopped at your request: this machine is already wired to ${supersededIds(collision)} and you chose ` +\n          'neither to replace that wiring nor to install alongside it. Nothing was written: no agent was created, ' +\n          'no credentials were stored, and the Haven setup token is still unused. Run the connector command again with ' +\n          `--replace to re-point haven / haven-signer at the new agent, or with --name <slug> (e.g. --name ${collision.suggestedServerName}) ` +\n          'to install alongside.',\n        'rerun_connect_with_replace_or_name',\n        { supersededAgentIds: collision.superseded.map((e) => e.agentId), suggestedServerName: collision.suggestedServerName },\n      )\n    }\n    return resolution\n  }\n  throw new ConnectError(\n    'wiring_collision',\n    `This machine is already wired to a Haven agent with a live key (${supersededIds(collision)}), and setting up ` +\n      `\"${agentName}\" on the bare haven / haven-signer pair would replace that wiring. Nothing was written and the ` +\n      'Haven setup token is still unused. If you are an AI agent running this command: do NOT add a flag yourself — ' +\n      'relay this to your user and stop. Your user decides: REPLACE the existing wiring (re-run the same command with ' +\n      '--replace added, which re-points the pair at the new agent and retires the previous directory locally — they ' +\n      'still use Remove agent\\u2026 on the Haven agent page to end the old agent\\u2019s budgets), or install ALONGSIDE it (re-run with --name <slug> added, ' +\n      `e.g. --name ${collision.suggestedServerName}, which gives the new agent its own haven-<slug> / haven-signer-<slug> pair). ` +\n      'Re-run only with the flag your user chooses.',\n    'relay_wiring_collision_to_user',\n    { supersededAgentIds: collision.superseded.map((e) => e.agentId), suggestedServerName: collision.suggestedServerName },\n  )\n}\n\n/**\n * The failure record for the `--json` contract.\n *\n * #1719: a `ConnectError` carries its own code and next action, so it is read\n * rather than guessed. The regex ladder below survives only for the refusals\n * that are still plain `Error`s — every new failure mode joins the vocabulary\n * instead of joining that ladder.\n *\n * #2091: the record now carries the redacted message rather than omitting it.\n * The old stance — terse because \"messages can contain server or filesystem\n * detail\" — left automation with a code and nothing to act on; the field\n * failure was a Codex agent staring at `connect_failed` with, in its own\n * words, \"no additional safe error detail\". Sanitize, don't silence.\n */\nexport function failedConnectOutcome(runtimeHint: string | undefined, error: unknown): ConnectOutcome {\n  const message = error instanceof Error ? error.message : ''\n  const code = error instanceof ConnectError\n    ? error.code\n    : /Node\\.js >=/i.test(message)\n      ? 'unsupported_node_version'\n      : /setup challenge.*expired|expired or invalid/i.test(message)\n        ? 'setup_challenge_expired_or_invalid'\n        : /only available for Claude Code and Codex/i.test(message)\n          ? 'local_mcp_unsupported_runtime'\n          : 'connect_failed'\n  const runtime = normalizeRuntime(runtimeHint)\n  const nextAction = error instanceof ConnectError\n    ? error.nextAction\n    : code === 'setup_challenge_expired_or_invalid'\n      ? 'return_to_haven_for_fresh_setup'\n      : code === 'unsupported_node_version'\n        ? 'install_supported_node_and_rerun_connect'\n        : code === 'local_mcp_unsupported_runtime'\n          ? 'rerun_without_local_mcp'\n          : 'review_the_safe_error_output_and_start_a_fresh_haven_setup_if_needed'\n  return {\n    schema_version: CONNECT_OUTCOME_SCHEMA_VERSION,\n    outcome: 'failed',\n    runtime,\n    topology: 'unknown',\n    configuration: { hosted_mcp: false, local_signer: false, local_mcp: false },\n    probe: { result: 'not_run' },\n    activation: { restart_required: false, instruction: 'Resolve the reported problem before activating Haven tools.' },\n    next_action: nextAction,\n    approval: { required: false, expires_at: null },\n    verification: {\n      tools: ['haven_get_agent', 'haven_get_allowances'] as const,\n      instruction: 'After a successful setup and activation, verify only with haven_get_agent and haven_get_allowances.',\n    },\n    error: {\n      code,\n      next_action: nextAction,\n      // Only a ConnectError's message enters the JSON record: the vocabulary's\n      // prose is connector-authored and safe to serialize, while a plain\n      // Error can carry arbitrary server or filesystem detail (that stance is\n      // pinned by test). Redaction stays on as belt-and-braces; plain-Error\n      // runs still get their redacted message on stderr via the CLI mirror.\n      ...(error instanceof ConnectError && message ? { message: redactForAutomation(message) } : {}),\n      ...(error instanceof ConnectError && error.details.allowedRuntimes\n        ? { allowed_runtimes: error.details.allowedRuntimes }\n        : {}),\n      ...(error instanceof ConnectError && error.details.installedClients?.length\n        ? { installed_clients: error.details.installedClients }\n        : {}),\n      ...(error instanceof ConnectError && error.details.suggestedRuntime\n        ? { suggested_runtime: error.details.suggestedRuntime }\n        : {}),\n      ...(error instanceof ConnectError && error.details.supersededAgentIds\n        ? { superseded_agent_ids: error.details.supersededAgentIds }\n        : {}),\n      ...(error instanceof ConnectError && error.details.suggestedServerName\n        ? { suggested_name: error.details.suggestedServerName }\n        : {}),\n    },\n  }\n}\n\nfunction printSetupSummary(setup: ResolvedSetup, log: (message: string) => void): void {\n  log(`Fetched Haven setup for ${setup.agent.name}.`)\n  log(`Haven wallet: ${setup.haven_wallet.name} on ${setup.haven_wallet.network}.`)\n  if (setup.agent_budget.length > 0) {\n    for (const budget of setup.agent_budget) {\n      log(\n        `Agent budget: ${budget.allowance_amount} atomic ${budget.token_symbol} / ${budget.reset_period_min} minute reset.`,\n      )\n    }\n  }\n  log(`Setup challenge expires at ${setup.challenge.expires_at}. If it expires, return to Haven for a fresh setup and rerun Connect — do not reuse or paste credentials.`)\n}\n\n/**\n * #2484: the approve-budget CTA carries the facts an agent relaying it\n * verbatim would otherwise have to go fetch — budget amount/token/period and\n * the wallet label + network. No secrets: those exact values are already\n * printed by `printSetupSummary` (atomic amounts, and the wallet label —\n * nothing here is a key or an address). The budget phrase reuses the same\n * formatter as the celebration line (`describeApprovedBudget` —\n * `formatAtomicAmount` + `describeResetPeriod` + `resolveTokenFromAddress`,\n * with the tokenless atomic-units fallback), so the CTA, the celebration,\n * and the pending handoff can never phrase the same setup differently. A\n * setup with no budget rows keeps today's plain phrasing. Multiple budget\n * rows join with commas. One name for the gate throughout: the budget\n * (#1542).\n */\nfunction approveBudgetCta(setup: ResolvedSetup, approvalUrl?: string): string {\n  // #2528: the link replaces \"in the Haven dashboard\", which was a place the\n  // user had to go find. Falls back to the previous wording when the backend\n  // is older than #2528 and sent none — degrading to the old sentence is\n  // correct; printing `undefined` is not.\n  const where = approvalUrl ? `at ${approvalUrl}` : 'in the Haven dashboard'\n  const budgetPhrase =\n    setup.agent_budget.length > 0\n      ? setup.agent_budget.map((budget) => `up to ${describeSetupBudget(budget)}`).join(', ')\n      : undefined\n  if (budgetPhrase) {\n    return `→ Action needed: approve this agent's budget — ${budgetPhrase} from ${setup.haven_wallet.name} on ${setup.haven_wallet.network} — ${where}. The approval button is live now; setup continues here in the meantime.`\n  }\n  return `→ Action needed: approve this agent's budget ${where} — the approval button is live now. Setup continues here in the meantime.`\n}\n\nfunction describeSetupBudget(budget: ResolvedSetup['agent_budget'][number]): string {\n  // The celebration line's formatter takes the connector-status shape (atomic\n  // `amount`, token ident pair, reset period); the setup row carries the same\n  // fields under its own names, so adapt and reuse rather than fork.\n  return describeApprovedBudget({\n    token_symbol: budget.token_symbol,\n    token_address: budget.token_address,\n    amount: budget.allowance_amount,\n    reset_period_min: budget.reset_period_min,\n  })\n}\n\nfunction assertSetupChallengeIsUsable(expiresAt: string): void {\n  const expiresAtMs = Date.parse(expiresAt)\n  if (!Number.isNaN(expiresAtMs) && expiresAtMs > Date.now()) return\n  throw new Error(\n    'This Haven setup challenge is expired or invalid. Return to Haven, start a fresh connection, and rerun Connect. No local credentials were written.',\n  )\n}\n\n/**\n * #2091: a dead setup token is a first-class verdict, not `connect_failed`.\n * The backend answers 410 \"Setup token expired\" (30-minute TTL) and 401\n * \"Invalid setup token\" (no matching setup at all — a mistyped or garbled\n * token reads the same as a purged one); neither wording matched the legacy\n * expiry regexes, so a --json run degraded to the generic code with no usable\n * next action — per #1719, the failure mode joins the ConnectError vocabulary\n * instead of that ladder. Checked at BOTH token-bearing calls (resolve and\n * register): the token can expire in the gap between them, since register\n * runs after runtime detection, key generation, and any interactive prompt.\n * Returns null for anything that is not this verdict.\n */\nfunction deadSetupTokenError(err: unknown): ConnectError | null {\n  if (!(err instanceof ConnectRequestError) || (err.status !== 410 && err.status !== 401)) return null\n  return new ConnectError(\n    'setup_challenge_expired_or_invalid',\n    'This Haven setup token is expired or invalid — tokens are single-use and expire 30 minutes after ' +\n      'the dashboard issues them, and a mistyped token reads the same way. Return to Haven, start a ' +\n      'fresh connection, and run its new connector command. No local credentials were written.',\n    'return_to_haven_for_fresh_setup',\n  )\n}\n\nfunction isExpiredSetupChallenge(err: unknown): boolean {\n  return err instanceof Error && /(?:setup )?challenge.*expir|expir.*(?:setup )?challenge/i.test(err.message)\n}\n\nfunction secureLogger(log: (message: string) => void, redactPaths = false): (message: string) => void {\n  return (message) => {\n    log(redactPaths ? redactForAutomation(message) : redactSecrets(message))\n  }\n}\n\nfunction printRuntimeInstall(result: RuntimeInstallResult, log: (message: string) => void): void {\n  for (const message of result.messages) log(message)\n  if (result.localMcpConfigured) {\n    log('Configured local Haven MCP tools.')\n  } else if (result.hostedMcpConfigured) {\n    log('Configured hosted Haven MCP identity.')\n  } else {\n    log('Haven MCP tools still need runtime setup.')\n  }\n  if (result.localSignerConfigured) {\n    log('Configured local Haven signer.')\n  } else {\n    log('Local Haven signer still needs runtime setup.')\n  }\n}\n\n/**\n * #1377 D: after registering, the connector no longer goes dead while the\n * user approves in Haven — it polls the narrow connector-status endpoint\n * (agent-API-key auth, works during `setup_pending`) and narrates progress in\n * the flow's voice, ending in a concrete celebration naming the granted\n * authority. Bounds (stated per the issue): poll every 5 s, give up after\n * 3 minutes (36 polls; with the immediate first check below the last one\n * lands at ~175 s) — the connector ALWAYS terminates on its own; a timeout\n * is a clean exit with guidance, never a hang. Injectable clock/cadence for\n * tests.\n *\n * #1542: the first check happens BEFORE the \"waiting for you to approve\" line\n * is printed. Users routinely approve in the dashboard while the runtime\n * install is still running, and announcing a wait that is already over made\n * the very next line (\"Budget approved 🎉\") read as a contradiction — the\n * field-test agent relayed the pair verbatim as a bug.\n */\nexport interface ApprovalWaitOptions {\n  intervalMs?: number\n  timeoutMs?: number\n  sleep?: (ms: number) => Promise<void>\n}\n\n/** Human form of an atomic amount — whole numbers stay whole (\"25\", not \"25.0\"). */\nfunction formatAtomicAmount(atomic: bigint, decimals: number): string {\n  const s = atomic.toString().padStart(decimals + 1, '0')\n  const intPart = s.slice(0, s.length - decimals) || '0'\n  const fracPart = s.slice(s.length - decimals).replace(/0+$/, '')\n  return fracPart ? `${intPart}.${fracPart}` : intPart\n}\n\n/**\n * #1426: one voice with the dashboard. The celebration line renders next to\n * the dashboard's approved screen describing the SAME grant, so every period\n * the dashboard offers (RESET_PERIODS: 0/1440/10080/43200) must phrase\n * identically to `budgetPeriodLabel`'s sentence form — \"per 10080 minutes\"\n * made the user do arithmetic on a reassurance message. `0` says \"in total\"\n * (the dashboard's sentence form), not \"with no automatic reset\" — one voice,\n * decided here rather than left as a recorded divergence.\n *\n * Deliberately NOT one source of truth with the frontend: the shared mapping\n * lives in dashboard code, and the only shared home would be\n * `@haven_ai/core` — a PRIVATE workspace package that published packages\n * (this one) must never depend on. Same structural reason the frontend keeps\n * an inline copy of the skill content; the parity tests are the coupling.\n */\nfunction describeResetPeriod(resetPeriodMin: number): string {\n  if (resetPeriodMin === 1440) return 'per day'\n  if (resetPeriodMin === 10080) return 'per week'\n  if (resetPeriodMin === 43200) return 'per month'\n  if (resetPeriodMin === 60) return 'per hour'\n  if (resetPeriodMin === 0) return 'in total'\n  return `every ${resetPeriodMin} minutes`\n}\n\nfunction describeApprovedBudget(budget: {\n  token_symbol: string\n  token_address: string\n  amount: string\n  reset_period_min: number\n}): string {\n  const token = resolveTokenFromAddress(budget.token_address)\n  const amount = token\n    ? `${formatAtomicAmount(BigInt(budget.amount), token.decimals)} ${budget.token_symbol}`\n    : `${budget.amount} ${budget.token_symbol} (atomic units)`\n  return `${amount} ${describeResetPeriod(budget.reset_period_min)}`\n}\n\n/** \"3 minutes\" for the default bound; seconds for the sub-2-minute test cadences. */\nfunction describeWaitBound(timeoutMs: number): string {\n  if (timeoutMs >= 120_000) {\n    const minutes = Math.round(timeoutMs / 60_000)\n    return `${minutes} minutes`\n  }\n  return `${Math.round(timeoutMs / 1_000)}s`\n}\n\nexport type BudgetApprovalOutcome = 'approved' | 'pending' | 'ended'\n\nexport async function waitForBudgetApproval(\n  api: Pick<ConnectApiClient, 'getConnectorStatus'>,\n  setupId: string,\n  apiKey: string,\n  log: (message: string) => void,\n  options: ApprovalWaitOptions = {},\n): Promise<BudgetApprovalOutcome> {\n  const intervalMs = options.intervalMs ?? 5_000\n  const timeoutMs = options.timeoutMs ?? 180_000\n  const sleep = options.sleep ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms)))\n  const maxPolls = Math.max(1, Math.floor(timeoutMs / intervalMs))\n  const remindEvery = Math.max(1, Math.floor(30_000 / intervalMs))\n\n  // Announced only once a check has actually observed a pending (or unknown)\n  // state — never ahead of a first check that may find the wait already over.\n  //\n  // #2279: phrased as status, not as the first ask — the imperative CTA now\n  // prints when the early install-status report unlocks the dashboard button,\n  // usually minutes before this line. When that CTA did not print (early\n  // report failed or errored), the complete report just before this wait is\n  // what unlocked the button, so this line still carries the instruction.\n  let waitingAnnounced = false\n  const announceWaiting = () => {\n    if (waitingAnnounced) return\n    waitingAnnounced = true\n    log('Now waiting for you to approve the budget in the Haven dashboard — approval is what unlocks the agent\\'s Haven tools…')\n  }\n\n  for (let i = 0; i < maxPolls; i++) {\n    // The first check is immediate (#1542); only the retries pace themselves.\n    if (i > 0) await sleep(intervalMs)\n    let status: Awaited<ReturnType<ConnectApiClient['getConnectorStatus']>>\n    try {\n      status = await api.getConnectorStatus(setupId, apiKey)\n    } catch (err) {\n      // 401/404 are verdicts, not noise: the user cancelled the setup from\n      // the dashboard (key revoked) or the setup is gone. Retrying for the\n      // rest of the window and then saying \"still pending\" would be wrong —\n      // there is nothing left to approve.\n      if (err instanceof ConnectRequestError && (err.status === 401 || err.status === 404)) {\n        log('This setup ended in Haven — start a fresh connection from the dashboard when ready.')\n        return 'ended'\n      }\n      // A flaky poll is not a verdict — keep waiting inside the same bound,\n      // and say so, rather than sitting silent until a check succeeds.\n      announceWaiting()\n      continue\n    }\n    if (status.status === 'active') {\n      log(\n        status.approved_budget\n          ? `Budget approved 🎉 — I can now spend up to ${describeApprovedBudget(status.approved_budget)} from your Haven wallet.`\n          : 'Budget approved 🎉 — the agent can now spend within its Haven rules.',\n      )\n      return 'approved'\n    }\n    if (status.status === 'cancelled' || status.status === 'expired' || status.status === 'failed') {\n      log(`This setup ended in Haven (${status.status}) — start a fresh connection from the dashboard when ready.`)\n      return 'ended'\n    }\n    announceWaiting()\n    if (i > 0 && i % remindEvery === 0) {\n      // #2279: a watcher could not tell active polling from a hang, and the\n      // give-up bound (#1377 D) was invisible until it fired. Elapsed time is\n      // poll-count arithmetic, not a clock read, so the injectable-clock\n      // tests stay deterministic.\n      const elapsedSeconds = Math.round((i * intervalMs) / 1_000)\n      log(\n        `Still waiting for budget approval in Haven — ${elapsedSeconds}s elapsed, checking every ` +\n          `${Math.round(intervalMs / 1_000)}s. I'll stop waiting after ${describeWaitBound(timeoutMs)}; ` +\n          'you can approve later and the tools unlock then.',\n      )\n    }\n  }\n  log(\n    'Budget approval is still pending in Haven. Approve it in the dashboard whenever you are ready — ' +\n      'the agent tools unlock the moment you do. Verify later with the read-only haven_get_agent tool.',\n  )\n  return 'pending'\n}\n\n/**\n * The two remaining gates after the local connector finishes: approve the\n * budget in Haven, then (for most runtimes) restart so the freshly-written MCP\n * config is loaded. The approval line states the dependency explicitly — tools\n * never appear before approval, restart or not — because an agent that had\n * already approved still couldn't tell whether missing tools meant \"not\n * approved\" or \"needs restart.\"\n *\n * #1542, from the field test:\n * - The lines are shaped by what the approval wait observed. `'approved'`\n *   replaces the approve instruction with a confirmation — the connector must\n *   never celebrate the approval and then instruct the user to go perform it.\n *   `undefined` (wait skipped: --json mode, or an install errorCode) keeps the\n *   full instruction.\n * - One name for the gate throughout this file: the BUDGET — the word the wait\n *   loop, the celebration, and the dashboard's grant screen already use.\n *   \"Agent rules\" here made one gate read as two.\n * - The restart step says WHY it survives the connector's own verification:\n *   session/app-scoped runtimes only read MCP config at start-up.\n */\nexport function completionHandoffLines(\n  result: RuntimeInstallResult,\n  approval?: BudgetApprovalOutcome,\n  approvalUrl?: string,\n): string[] {\n  // #2528: \"Return to Haven\" is the sentence an agent had to translate into a\n  // place for its user. With a link it relays a destination instead. Optional\n  // throughout — a backend older than #2528 sends none and these lines read\n  // exactly as they did before.\n  const approveStep = approvalUrl\n    ? `Approve the budget at ${approvalUrl}. Approval — not restarting — unlocks Haven tools.`\n    : 'Return to Haven and approve the budget. Approval — not restarting — unlocks Haven tools.'\n  if (result.errorCode === 'manual_runtime_setup_required') {\n    return [\n      'Next steps:',\n      `1. ${approveStep}`,\n      '2. Finish the manual MCP setup using the secret-free file references printed above, then start a fresh session in your runtime.',\n      `3. ${runtimeVerificationInstruction(result.runtime)}`,\n    ]\n  }\n  if (result.errorCode) {\n    return [\n      'Recovery: runtime setup is not complete. Resolve the reported problem, then return to Haven for a fresh connection and run its new connector command. Do not manually edit runtime config or paste credentials into prompts, logs, or config.',\n    ]\n  }\n\n  if (approval === 'ended') {\n    return [\n      'Next step: this setup ended in Haven before the budget was approved, so there is nothing left to approve on it — start a fresh connection from the dashboard when ready.',\n    ]\n  }\n\n  const profile = runtimeProfile(result.runtime)\n  const activation = activationInstructionWithWhy(profile)\n  if (approval === 'approved') {\n    return [\n      'Next steps — the budget is already approved, so there is nothing more to do in Haven:',\n      `1. ${activation}`,\n      `2. ${runtimeVerificationInstruction(result.runtime)}`,\n    ]\n  }\n  return [\n    'Next steps:',\n    `1. ${approveStep}`,\n    `2. ${activation}`,\n    `3. ${runtimeVerificationInstruction(result.runtime)}`,\n  ]\n}\n\n/**\n * The field-test agent had just watched the connector print \"Verified Claude\n * Code MCP entry\" and reasonably asked why a restart was still demanded. Say\n * the reason in the instruction itself: verification ran in the connector's\n * process, but the runtime only reads MCP config at session start (or app\n * launch). Hot-reload and manual runtimes keep their registry copy untouched —\n * their instructions already carry their own activation story.\n */\nfunction activationInstructionWithWhy(profile: RuntimeProfile): string {\n  if (profile.restartMode === 'restart-session') {\n    return `${profile.activationInstruction} (The entries are already written and verified — ${profile.label} only reads MCP config when a session starts, which is why this step is still needed.)`\n  }\n  if (profile.restartMode === 'restart-app') {\n    return `${profile.activationInstruction} (The entries are already written and verified — ${profile.label} only reads MCP config at app launch, which is why this step is still needed.)`\n  }\n  return profile.activationInstruction\n}\n\nconst RERUN_HINT = connectorRerunCommand()\n\n/**\n * Agent ids of every OTHER credential directory (#1688) — the agents this run\n * just superseded — or `null` when the scan could not run.\n *\n * Reads identity.json for the id; a directory that does not parse is named by\n * its directory name, because \"I could not read it\" is still a directory the\n * user should know exists.\n *\n * The `null` is the whole point of the signature (#2561). This used to return\n * `[]` for both \"the credential root holds no other agent\" and \"the credential\n * root could not be read\", and the outcome field's own doc comment had to warn\n * readers that emptiness was not a guarantee. A warning in prose cannot reach\n * a dashboard: rendering \"nothing to revoke\" for a machine nobody scanned\n * states something Haven does not know. So the two cases are distinguishable\n * at the source, where the difference is actually observed.\n *\n * What a NON-null return does and does not promise: the root was readable, not\n * that every entry under it was. A per-entry `stat` or read that fails is\n * skipped — correct for a `.DS_Store`, and it also silently drops a real agent\n * directory that is merely unreadable (a permission error, say). So a list can\n * UNDER-report. That direction is the safe one — fewer revoke offers, never a\n * spurious one — but it is a limit of the success branch rather than a\n * guarantee, and saying so here is cheaper than a reader inferring the\n * opposite.\n */\n/**\n * #3122: every credential directory under the root that still holds a stored\n * API key, with the account it can spend from (read from identity.json /\n * agent.json, never from signer.json). Local files only — no network. Runs\n * BEFORE this setup writes anything, so it needs no exclusion and names no\n * directory that does not yet exist. Never throws: an unreadable root is an\n * empty list (not proof of a clean machine, as the outcome field's doc says).\n */\nasync function listExistingKeyedAgents(baseDir: string | undefined): Promise<Array<{ agentId: string; directory: string; accountAddress: string | null }>> {\n  const root = defaultCredentialRoot(baseDir)\n  let entries: string[] = []\n  try {\n    entries = await readdir(root)\n  } catch {\n    return []\n  }\n  const out: Array<{ agentId: string; directory: string; accountAddress: string | null }> = []\n  for (const entry of entries) {\n    const directory = join(root, entry)\n    try {\n      const identity = JSON.parse(await readFile(join(directory, 'identity.json'), 'utf8')) as Record<string, unknown>\n      if (typeof identity.api_key !== 'string' || identity.api_key.length === 0) continue\n      let agent: Record<string, unknown> = {}\n      try {\n        agent = JSON.parse(await readFile(join(directory, 'agent.json'), 'utf8')) as Record<string, unknown>\n      } catch {\n        // No agent.json: the account may still be on identity.json.\n      }\n      const { accountAddress } = readStoredAccountAddress(identity, agent)\n      out.push({ agentId: typeof identity.agent_id === 'string' ? identity.agent_id : entry, directory, accountAddress: accountAddress ?? null })\n    } catch {\n      // No identity.json, or unreadable: not a keyed agent directory.\n    }\n  }\n  return out\n}\n\nasync function listOtherAgentIds(baseDir: string | undefined, currentDirectory: string): Promise<string[] | null> {\n  const root = defaultCredentialRoot(baseDir)\n  let entries: string[] = []\n  try {\n    entries = await readdir(root)\n  } catch {\n    // The scan did not run. Callers that only want the heads-up treat this as\n    // empty; callers that report to Haven send `null` and let the dashboard\n    // stay silent rather than reassure.\n    return null\n  }\n  const ids: string[] = []\n  for (const entry of entries) {\n    // Exclude by the DIRECTORY this run wrote, never by agent id (#1696\n    // review): a named agent's directory is its slug, which never equals the\n    // agent uuid, so an id comparison would name the agent just created as a\n    // superseded one and tell the user to revoke it on a clean first run.\n    if (join(root, entry) === currentDirectory) continue\n    const identityPath = join(root, entry, 'identity.json')\n    // Gate on the FILE EXISTING before treating the entry as an agent at all\n    // (#1688 review, B1): readdir returns every filesystem entry, and a\n    // .DS_Store or sync-relic that merely fails to read must be skipped —\n    // naming it would tell the user to \"revoke\" a file. A directory whose\n    // identity.json EXISTS but does not parse is the case worth surfacing,\n    // by directory name, because a corrupt agent dir is still an agent dir.\n    try {\n      await stat(identityPath)\n    } catch {\n      continue\n    }\n    try {\n      const identity = JSON.parse(await readFile(identityPath, 'utf8')) as { agent_id?: string }\n      ids.push(identity.agent_id ?? entry)\n    } catch {\n      ids.push(entry)\n    }\n  }\n  return ids\n}\n\nfunction printNextSteps(\n  result: RuntimeInstallResult,\n  log: (message: string) => void,\n  approval?: BudgetApprovalOutcome,\n  approvalUrl?: string,\n): void {\n  for (const line of completionHandoffLines(result, approval, approvalUrl)) log(line)\n}\n","/**\n * Refusal prose shared between the argument parser and the re-key\n * implementation (#2187).\n *\n * Both layers legitimately refuse a `--rekey-finish` with no new API key, and\n * neither is redundant:\n *\n * - `args.ts` refuses the bad INVOCATION at parse time, before anything is read\n *   from disk — the #1161 fail-early ordering this package holds to elsewhere.\n * - `rekey.ts` refuses the bad CALL whoever made it. `startRekey` and\n *   `finishRekey` share one `RekeyOptions`, so `newApiKey` is optional in the\n *   type only because phase one does not take one; for `finishRekey` it is\n *   required in practice, and this is what makes that contract honest at\n *   runtime. `rekey.test.ts` calls the function directly, and a plain-JS caller\n *   could pass `undefined` past any type we could write.\n *\n * What was NOT legitimate was two copies of the sentence, with nothing pinning\n * them together — edit one and they drift silently, and the copy a user\n * actually sees is the parser's.\n *\n * This module deliberately imports nothing: `args.ts` is loaded on every CLI\n * invocation while `rekey.ts` is dynamically imported only for `--rekey`, so a\n * shared home with any dependency of its own would pull the re-key graph into\n * the parse path and defeat that lazy load.\n */\nexport const REKEY_FINISH_NEEDS_API_KEY =\n  '--rekey-finish needs --api-key <key> — the one the Haven agent page showed once.'\n","/**\n * #3123: reclaim signer-runtime directories nothing depends on.\n *\n * `~/.haven/signer-runtime/<key>/` is written once per pinned manifest\n * version — and, since #2424, once per `HAVEN_*_SPEC` override, under a\n * `directory_key` that is a hash of the resolved specs, so on a developer\n * machine the override-keyed directories are likely the bulk of the pile.\n * Nothing ever reclaimed them (`git grep -i prune` over the connector was\n * empty before this file).\n *\n * The rule is the safe one: a directory is KEPT when any credential\n * directory names it — through its `signer-runtime.json` `runtime_directory`\n * OR through the path its `bin/haven-signer.mjs` wrapper launches (a\n * directory with a missing or corrupt sidecar but an intact wrapper still\n * depends on its runtime; #3151 review) — wired, superseded, retired,\n * whatever its classification, because \"a directory nobody is using\" is\n * exactly what the doctor exists to decide, not this — or when it is the\n * manifest's current pin (what `--repair` would install into). Credential\n * directories are read from the default root AND, when `--credentials-dir`\n * names an agent elsewhere, from that directory's parent as well — a union,\n * never either/or, so pointing the prune at one agent cannot blind it to the\n * others (#3151 review). Paths are normalized (resolved, realpath where the\n * directory exists, no trailing slash) on both sides of the comparison.\n * Everything else under the root is removed, or listed under `--dry-run`.\n * Enumeration walks the ROOT, never the manifest's version list, so\n * override-keyed directories are seen (S4).\n *\n * The prune trusts those two reference sources; it does not read runtime\n * configs. A running signer whose directory is removed: on POSIX the process\n * keeps its open files and keeps serving until it restarts; a removed\n * directory is one no sidecar and no wrapper named, so a configured agent is\n * not started against it. On a platform where the removal fails (`EBUSY`),\n * the entry is reported `failed` and the exit code says so; nothing else is\n * affected.\n *\n * Sizes: `directoryBytes` walks every file (287k files, 2.0 GB on disk, on\n * one developer machine: 28 s cold / 34 s warm in one #3151 reviewer's run,\n * 1059 s cold in the other reviewer's sandbox — cache- and box-dependent,\n * none of it a contract), so it\n * runs only for the directories the run would remove, and only when the\n * caller asks (`measure: true`, the CLI). The doctor's dry run passes\n * `measure: false` and reports names only.\n *\n * Findings use #3121's three levels rather than a second scale: `removed` and\n * `kept` are `ok`, a `would_remove` under --dry-run is an `advisory`\n * (worth reading, nothing broken), a `failed` removal is `failed`.\n */\nimport { readdir, readFile, realpath, rm, stat } from 'node:fs/promises'\nimport { homedir } from 'node:os'\nimport { dirname, join, resolve } from 'node:path'\nimport { MCP_RUNTIME_MANIFEST } from './runtime-manifest.js'\nimport type { DoctorLevel } from './doctor.js'\n\nexport interface PruneEntry {\n  directory: string\n  key: string\n  kind: 'version' | 'override' | 'unknown'\n  /** Size in bytes — `0` for every kept entry and for any `measure: false` run: sizing runs only for directories the run would remove. */\n  bytes: number\n  /** The credential directories whose sidecar or wrapper names this runtime (empty when unreferenced). */\n  referencedBy: string[]\n  action: 'kept' | 'removed' | 'would_remove' | 'failed'\n  level: DoctorLevel\n  detail: string\n}\n\nexport interface PruneReport {\n  version: 1\n  root: string\n  dryRun: boolean\n  entries: PruneEntry[]\n  removed: number\n  reclaimedBytes: number\n  level: DoctorLevel\n}\n\nexport interface PruneDeps {\n  homeDir?: string\n  /** An explicit `--credentials-dir` names ONE agent directory; its siblings are its parent's (#1688 B2). */\n  credentialsDir?: string\n  rm?: (directory: string) => Promise<void>\n}\n\nexport function signerRuntimeRoot(homeDir: string): string {\n  return join(homeDir, '.haven', 'signer-runtime')\n}\n\nfunction classifyKey(key: string): PruneEntry['kind'] {\n  if (key.startsWith('override-')) return 'override'\n  if (key === MCP_RUNTIME_MANIFEST.signerVersion || /^\\d+\\.\\d+\\.\\d+/.test(key)) return 'version'\n  return 'unknown'\n}\n\nasync function directoryBytes(directory: string): Promise<number> {\n  let total = 0\n  const walk = async (dir: string): Promise<void> => {\n    let entries: import('node:fs').Dirent[] = []\n    try {\n      entries = await readdir(dir, { withFileTypes: true })\n    } catch {\n      return\n    }\n    for (const entry of entries) {\n      const path = join(dir, entry.name)\n      if (entry.isDirectory()) await walk(path)\n      else if (entry.isFile()) {\n        try {\n          total += (await stat(path)).size\n        } catch {\n          // A file that vanished mid-walk counts nothing.\n        }\n      }\n    }\n  }\n  await walk(directory)\n  return total\n}\n\n/** Resolve, strip trailing separators, and follow symlinks when the path exists — so both sides compare alike. */\nexport async function normalizeRuntimePath(path: string): Promise<string> {\n  const resolved = resolve(path).replace(/[\\\\/]+$/, '')\n  try {\n    return await realpath(resolved)\n  } catch {\n    return resolved\n  }\n}\n\nfunction escapeRegExp(text: string): string {\n  return text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\n/**\n * Every runtime directory any credential directory names — through its\n * sidecar's `runtime_directory` or the path its wrapper launches — keyed by\n * the normalized directory, valued by the credential directories naming it.\n * Reads the default root AND the explicit directory's parent (a union).\n */\nexport async function referencedRuntimeDirectories(homeDir: string, credentialsDir?: string): Promise<Map<string, string[]>> {\n  const roots = new Set<string>([join(homeDir, '.haven', 'agents')])\n  if (credentialsDir) roots.add(dirname(resolve(credentialsDir)))\n  const referenced = new Map<string, string[]>()\n  const runtimeRoot = await normalizeRuntimePath(signerRuntimeRoot(homeDir))\n  // A wrapper may spell the root as written at install time (before symlink\n  // resolution — macOS's /var vs /private/var) or as its realpath; match both.\n  const rootSpellings = [...new Set([resolve(signerRuntimeRoot(homeDir)), runtimeRoot])]\n  const wrapperRe = new RegExp(`(?:${rootSpellings.map(escapeRegExp).join('|')})[\\\\/]+([^\\\\/'\"\\\\s]+)`, 'g')\n  const add = async (runtimeDirectory: string, by: string) => {\n    const key = await normalizeRuntimePath(runtimeDirectory)\n    const list = referenced.get(key) ?? []\n    if (!list.includes(by)) list.push(by)\n    referenced.set(key, list)\n  }\n  for (const root of roots) {\n    let entries: string[] = []\n    try {\n      entries = await readdir(root)\n    } catch {\n      continue\n    }\n    for (const entry of entries) {\n      const directory = join(root, entry)\n      try {\n        const sidecar = JSON.parse(await readFile(join(directory, 'signer-runtime.json'), 'utf8')) as { runtime_directory?: unknown }\n        if (typeof sidecar.runtime_directory === 'string' && sidecar.runtime_directory.length > 0) {\n          await add(sidecar.runtime_directory, directory)\n        }\n      } catch {\n        // No sidecar, or unreadable: the wrapper below is the second source.\n      }\n      try {\n        const wrapper = await readFile(join(directory, 'bin', 'haven-signer.mjs'), 'utf8')\n        // The wrapper launches `<runtime root>/<key>/node_modules/...`; every\n        // root child it names is a reference, whatever the sidecar says.\n        for (const match of wrapper.matchAll(wrapperRe)) await add(join(runtimeRoot, match[1]), directory)\n      } catch {\n        // No wrapper: nothing more to learn from this directory.\n      }\n    }\n  }\n  return referenced\n}\n\nexport function rollUpPruneLevel(entries: ReadonlyArray<Pick<PruneEntry, 'level'>>): DoctorLevel {\n  if (entries.some((e) => e.level === 'failed')) return 'failed'\n  if (entries.some((e) => e.level === 'advisory')) return 'advisory'\n  return 'ok'\n}\n\n/**\n * Enumerate the root and decide each directory. `dryRun` reports without\n * removing; otherwise unreferenced directories are removed one by one and a\n * removal that throws is reported `failed` rather than aborting the run.\n */\nexport async function pruneSignerRuntimes(input: { dryRun: boolean; measure?: boolean }, deps: PruneDeps = {}): Promise<PruneReport> {\n  const homeDir = deps.homeDir ?? homedir()\n  const root = signerRuntimeRoot(homeDir)\n  const measure = input.measure ?? true\n  const referenced = await referencedRuntimeDirectories(homeDir, deps.credentialsDir)\n  const pin = await normalizeRuntimePath(join(root, MCP_RUNTIME_MANIFEST.signerVersion))\n  const remove = deps.rm ?? (async (directory: string) => rm(directory, { recursive: true, force: false }))\n  const entries: PruneEntry[] = []\n  let keys: string[] = []\n  try {\n    keys = (await readdir(root, { withFileTypes: true })).filter((d) => d.isDirectory()).map((d) => d.name).sort()\n  } catch {\n    return { version: 1, root, dryRun: input.dryRun, entries, removed: 0, reclaimedBytes: 0, level: 'ok' }\n  }\n  let removed = 0\n  let reclaimedBytes = 0\n  for (const key of keys) {\n    const directory = join(root, key)\n    const normalized = await normalizeRuntimePath(directory)\n    const referencedBy = referenced.get(normalized) ?? []\n    const kind = classifyKey(key)\n    if (referencedBy.length > 0 || normalized === pin) {\n      entries.push({\n        directory, key, kind, bytes: 0, referencedBy,\n        action: 'kept', level: 'ok',\n        detail: referencedBy.length > 0\n          ? `kept — named by ${referencedBy.length} credential director${referencedBy.length === 1 ? 'y' : 'ies'} (sidecar or wrapper)`\n          : 'kept — the connector\\'s current pinned version (what --repair installs)',\n      })\n      continue\n    }\n    // Sized only here — a directory the run would remove — and only when asked.\n    const bytes = measure ? await directoryBytes(directory) : 0\n    if (input.dryRun) {\n      entries.push({\n        directory, key, kind, bytes, referencedBy,\n        action: 'would_remove', level: 'advisory',\n        detail: `would remove — no credential directory names it (${kind}-keyed)`,\n      })\n      continue\n    }\n    try {\n      await remove(directory)\n      removed += 1\n      reclaimedBytes += bytes\n      entries.push({ directory, key, kind, bytes, referencedBy, action: 'removed', level: 'ok', detail: `removed — no credential directory named it (${kind}-keyed)` })\n    } catch (err) {\n      entries.push({\n        directory, key, kind, bytes, referencedBy,\n        action: 'failed', level: 'failed',\n        detail: `removal failed: ${err instanceof Error ? err.message : String(err)} — a signer process may still hold it open; stop it and re-run`,\n      })\n    }\n  }\n  return { version: 1, root, dryRun: input.dryRun, entries, removed, reclaimedBytes, level: rollUpPruneLevel(entries) }\n}\n","/**\n * `--rekey` — replace an agent's signing key on the machine that runs it\n * (#1700, epic #1694).\n *\n * ## Two phases, and why it cannot be one\n *\n * Re-key is authorised by the account OWNER through the dashboard: every\n * backend re-key route sits behind the dashboard session and explicitly\n * refuses an agent credential, because an agent rotating its own credentials\n * would be an agent editing its own authority (#1694). So this connector never\n * calls the re-key API at all. It brackets it:\n *\n * 1. `--rekey` generates a fresh keypair HERE and prints its public address.\n *    The owner pastes that into the dashboard, which runs the five owner-signed\n *    steps and hands back a new API key, shown once.\n * 2. `--rekey-finish --api-key <key>` writes both halves into the existing\n *    credential files and rewrites this agent's MCP config pair.\n *\n * The issue text called the input \"a re-key setup token\". There is no such\n * token and no endpoint that would redeem one; the shipped dashboard asks for\n * a pasted address and returns a pasted key. This follows the shipped flow.\n *\n * ## The non-custodial invariant, restated because this is where it could slip\n *\n * The new private key is generated on this machine and never leaves it. Haven\n * receives an ADDRESS. Nothing here accepts, uploads or transports key\n * material, and a design that \"restores\" a key to a new host is refused rather\n * than built (#1694).\n *\n * ## Why the config must be rewritten, not just the credential files\n *\n * The MCP config embeds the API key directly — `Authorization: Bearer <key>`\n * for the JSON and TOML runtimes, `MCP_HAVEN[_SLUG]_API_KEY` for Hermes. A\n * re-key that rewrote only `identity.json` would leave every wired host\n * presenting the rotated-away key and 401ing forever, which is the failure the\n * whole epic exists to remove.\n *\n * The wiring SLUG does not move, so the server names do not move, so no host\n * needs reconfiguring beyond a restart — that is the point of rewriting in\n * place at a stable path.\n */\n\nimport { createConnectApiClient, type AgentIdentity, type ConnectApiClient } from './api.js'\nimport { connectorRerunCommand } from '@haven_ai/sdk'\nimport { writeHostedRuntimeConfig } from './runtime-install.js'\nimport { prepareSignerRuntime } from './signer-runtime.js'\nimport { describeRuntimeSpecOverride } from './runtime-spec-override.js'\nimport { generateDelegateKey } from './key.js'\nimport { redactSecrets } from './redact.js'\nimport { REKEY_FINISH_NEEDS_API_KEY } from './rekey-messages.js'\nimport { CONNECTOR_CLIENT_IDENTITY } from './runtime.js'\nimport { serverNamesFor } from './server-names.js'\nimport {\n  REKEY_PENDING_TTL_MS,\n  clearRekeyPending,\n  readRekeyPending,\n  readStoredCredentials,\n  rewriteCredentialFiles,\n  writeRekeyPending,\n  type StoredCredentialSnapshot,\n} from './storage.js'\n\nexport interface RekeyOptions {\n  /** Wiring slug (`--name`). Absent = the unnamed pair's directory. */\n  serverName?: string\n  /** Agent id, for an unnamed agent whose directory is keyed by it. */\n  agentId?: string\n  credentialsDir?: string\n  /** Phase two only: the new API key the dashboard showed once. */\n  newApiKey?: string\n  /** Set for phase two when the config pair must be rewritten. */\n  runtime?: string\n  homeDir?: string\n}\n\nexport interface RekeyDeps {\n  createApi?: (baseUrl: string) => ConnectApiClient\n  generateKey?: typeof generateDelegateKey\n  now?: () => number\n  log?: (message: string) => void\n  /** Injected so the config rewrite is testable without touching a real host config. */\n  writeConfig?: typeof writeHostedRuntimeConfig\n  prepareSigner?: typeof prepareSignerRuntime\n  runCommand?: Parameters<typeof prepareSignerRuntime>[1] extends { runCommand?: infer R } ? R : never\n  /** #2424: the runtime-spec override env, threaded so a re-key reinstalls the same build setup did. */\n  env?: NodeJS.ProcessEnv\n}\n\nexport interface RekeyStartResult {\n  started: true\n  agentId: string\n  directory: string\n  newDelegateAddress: string\n  expiresAt: string\n  messages: string[]\n}\n\nexport interface RekeyFinishResult {\n  finished: true\n  agentId: string\n  directory: string\n  newDelegateAddress: string\n  serverNames: { hosted: string; signer: string }\n  /** False when no --runtime was given, so the caller can say the config is stale. */\n  configRewritten: boolean\n  messages: string[]\n}\n\n/** Phase one: generate the key, park it, print the address to paste. */\nexport async function startRekey(\n  options: RekeyOptions,\n  deps: RekeyDeps = {},\n): Promise<RekeyStartResult> {\n  const now = deps.now ?? (() => Date.now())\n  const stored = await readStoredCredentials(\n    options.serverName,\n    options.agentId,\n    options.credentialsDir,\n  )\n\n  const api = (deps.createApi ?? ((url: string) => createConnectApiClient(url, undefined, CONNECTOR_CLIENT_IDENTITY)))(stored.apiUrl)\n  const identity = await probeIdentity(api, stored.apiKey, 'current')\n  assertRekeyable(identity, stored)\n\n  // Generated HERE. The address is the only half that will ever be sent.\n  const key = (deps.generateKey ?? generateDelegateKey)()\n  const startedAt = new Date(now()).toISOString()\n  const expiresAt = new Date(now() + REKEY_PENDING_TTL_MS).toISOString()\n\n  await writeRekeyPending(stored.directory, {\n    agent_id: stored.agentId,\n    new_delegate_address: key.address,\n    new_delegate_key: key.privateKey,\n    started_at: startedAt,\n    expires_at: expiresAt,\n  })\n\n  // #3737 owner decision 3: an auto-selected named agent prints its exact\n  // --name, so phase two does not depend on the sole-agent discovery still\n  // holding by the time the owner returns with the key. A bare agent prints\n  // no --name, exactly as before.\n  const finishName = options.serverName ?? stored.discoveredSlug\n  const finishCommand = [\n    connectorRerunCommand('--rekey-finish'),\n    finishName ? `--name ${finishName}` : undefined,\n    '--api-key <the key the dashboard showed you>',\n    options.runtime ? `--runtime ${options.runtime}` : '--runtime <your runtime>',\n  ]\n    .filter(Boolean)\n    .join(' ')\n\n  return {\n    started: true,\n    agentId: stored.agentId,\n    directory: stored.directory,\n    newDelegateAddress: key.address,\n    expiresAt,\n    messages: [\n      `New signing key generated on this machine for agent ${identity.name || stored.agentId}.`,\n      '',\n      `  New signing address:  ${key.address}`,\n      '',\n      'The private half stays here — Haven never receives it, and there is no way to move it',\n      'between machines. That is what keeps the account non-custodial.',\n      '',\n      'Next, on the Haven agent page: choose \"Replace signing key\" and paste that address.',\n      'When it finishes it shows a new API key ONCE. Come back here and run:',\n      '',\n      `  ${finishCommand}`,\n      '',\n      `Nothing has changed yet — the agent keeps working on its old key until you finish.`,\n      `This pending re-key expires ${expiresAt}.`,\n    ],\n  }\n}\n\n/** Phase two: verify the pasted key, then rewrite credentials and config. */\nexport async function finishRekey(\n  options: RekeyOptions,\n  deps: RekeyDeps = {},\n): Promise<RekeyFinishResult> {\n  const now = deps.now ?? (() => Date.now())\n  if (!options.newApiKey) {\n    throw new Error(REKEY_FINISH_NEEDS_API_KEY)\n  }\n  const stored = await readStoredCredentials(\n    options.serverName,\n    options.agentId,\n    options.credentialsDir,\n  )\n  const pending = await readRekeyPending(stored.directory, now())\n\n  if (pending.agent_id !== stored.agentId) {\n    throw new Error(\n      `The pending re-key at ${stored.directory} belongs to agent ${pending.agent_id}, but that ` +\n        `directory now holds ${stored.agentId}. Refusing to write a key into the wrong agent.`,\n    )\n  }\n\n  const api = (deps.createApi ?? ((url: string) => createConnectApiClient(url, undefined, CONNECTOR_CLIENT_IDENTITY)))(stored.apiUrl)\n  const identity = await probeIdentity(api, options.newApiKey, 'new')\n\n  // The load-bearing check, and the reason this phase talks to Haven at all.\n  // It proves three things at once with one read: the pasted key authenticates,\n  // it belongs to THIS agent, and the backend re-key actually completed against\n  // the address this machine generated. Any of those being false and writing\n  // anyway produces a credential set that fails at the next payment instead of\n  // here, with the old key already gone.\n  if (identity.id !== stored.agentId) {\n    throw new Error(\n      `That API key belongs to agent ${identity.id}, not ${stored.agentId}. Nothing was changed.`,\n    )\n  }\n  const onChain = (identity.delegate_address ?? '').toLowerCase()\n  const expected = pending.new_delegate_address.toLowerCase()\n  if (onChain !== expected) {\n    throw new Error(\n      `Haven says this agent's signing address is ${identity.delegate_address ?? 'unset'}, but this ` +\n        `machine generated ${pending.new_delegate_address}. Nothing was changed. Either the ` +\n        're-key on the agent page used a different address, or it has not finished yet.',\n    )\n  }\n\n  await rewriteCredentialFiles({\n    baseDir: options.credentialsDir,\n    agentId: stored.agentId,\n    serverName: options.serverName,\n    apiKey: options.newApiKey,\n    delegateKey: pending.new_delegate_key,\n    delegateAddress: pending.new_delegate_address,\n    // The stored value (already new-name-first, from the credential-FILE\n    // permanent fallback) wins; the hosted identity's `account_address` is a\n    // LIVE server read, which as of #2914 emits only that name.\n    accountAddress: stored.accountAddress ?? identity.account_address ?? undefined,\n    chainId: stored.chainId ?? identity.chain_id ?? undefined,\n    network: stored.network,\n    agentBudget: stored.agentBudget,\n    apiUrl: stored.apiUrl,\n    hostedMcpUrl: stored.hostedMcpUrl,\n    x402BindingSigner: stored.x402BindingSigner,\n    warn: deps.log,\n  })\n\n  // Only now. A pending key deleted before the rewrite lands would make a\n  // failed rewrite unrecoverable — the private half would be gone with the\n  // credential files still naming the old one.\n  await clearRekeyPending(stored.directory)\n\n  const names = serverNamesFor(options.serverName)\n  const messages = [\n    `Agent ${identity.name || stored.agentId} is now on its new signing key.`,\n    `  Signing address:  ${pending.new_delegate_address}`,\n    `  Credentials:      ${stored.directory} (rewritten in place)`,\n    `  MCP servers:      ${names.hosted} / ${names.signer} (unchanged names)`,\n  ]\n\n  // ── The MCP config, which is NOT optional bookkeeping ────────────────────\n  //\n  // The API key is embedded in the config itself — `Authorization: Bearer\n  // <key>` for the JSON and TOML runtimes, `MCP_HAVEN[_SLUG]_API_KEY` for\n  // Hermes. Rewriting only the credential files would leave every wired host\n  // presenting the key the backend just retired, 401ing on every call, with a\n  // credential set on disk that looks perfectly correct.\n  //\n  // Only THIS agent's pair is touched: the writers key off `serverName`, so a\n  // sibling agent's entries in the same config file are carried through\n  // untouched (#1695).\n  let configRewritten = false\n  if (options.runtime) {\n    const prepared = await (deps.prepareSigner ?? prepareSignerRuntime)(\n      {\n        credentialDirectory: stored.directory,\n        signerPath: `${stored.directory}/signer.json`,\n        homeDir: options.homeDir,\n      },\n      { runCommand: deps.runCommand, env: deps.env },\n    )\n    // `writeHostedRuntimeConfig`, NOT `writeRuntimeConfig`. The latter has no\n    // `claude-code` case — that runtime is configured by shelling out to\n    // `claude mcp add-json` — so calling it directly returns a\n    // `hostedConfigured: false` result for the single most common runtime while\n    // reporting like a success. Review of this slice caught exactly that.\n    const result = await (deps.writeConfig ?? writeHostedRuntimeConfig)(\n      { runCommand: deps.runCommand, homeDir: options.homeDir },\n      {\n        runtime: options.runtime,\n        hostedMcpUrl: stored.hostedMcpUrl,\n        apiKey: options.newApiKey,\n        identityPath: `${stored.directory}/identity.json`,\n        signerPath: `${stored.directory}/signer.json`,\n        credentialDirectory: stored.directory,\n        serverName: options.serverName,\n      },\n      { command: prepared.command, args: prepared.args },\n    )\n    configRewritten = result.hostedConfigured\n    // #2424: a re-key reinstalls the signer runtime, so the override is\n    // printed here exactly as setup prints it — a developer must not learn\n    // from a 401-free but wrong-build agent that the variable was still set.\n    if (prepared.runtimeSpecOverride) {\n      messages.push(\n        `  Signer runtime:   RUNTIME SPEC OVERRIDE ACTIVE — ${describeRuntimeSpecOverride(prepared.runtimeSpecOverride.specs)} ` +\n          `(NOT the pinned manifest; installed into ${prepared.runtimeDirectory})`,\n      )\n    }\n    messages.push(`  Config:           ${result.target}`)\n    messages.push(...result.messages.map((line) => `  ${line}`))\n    if (!configRewritten) {\n      // The write reported failure — a runtime with no writer, or a `claude`\n      // CLI that is not on PATH. Say what it costs, in the same words as the\n      // no-runtime case: a credential set that is correct on disk while every\n      // wired host presents the retired key reads as \"the re-key broke my\n      // agent\", and the generic writer message does not say that.\n      messages.push(\n        '',\n        'WARNING: the MCP config was NOT updated, so it still carries the OLD API key and every',\n        `wired host will fail with 401. Fix the cause above and re-run with --runtime ${options.runtime},`,\n        'or update the config by hand. The credential files on disk are already on the new key.',\n      )\n    }\n  } else {\n    // Said loudly rather than skipped quietly: without this the user has a\n    // rotated credential file and a config still carrying the dead key, which\n    // presents as \"the re-key broke my agent\".\n    messages.push(\n      '',\n      'NOTE: no --runtime was given, so the MCP config still carries the OLD API key and every',\n      'wired host will fail with 401. Re-run with --runtime <name> to rewrite it.',\n    )\n  }\n\n  return {\n    finished: true,\n    agentId: stored.agentId,\n    directory: stored.directory,\n    newDelegateAddress: pending.new_delegate_address,\n    serverNames: { hosted: names.hosted, signer: names.signer },\n    configRewritten,\n    messages,\n  }\n}\n\nasync function probeIdentity(\n  api: ConnectApiClient,\n  apiKey: string,\n  which: 'current' | 'new',\n): Promise<AgentIdentity> {\n  try {\n    return await api.getAgentIdentity(apiKey)\n  } catch (err) {\n    const status = (err as { status?: number } | null)?.status\n    if (status === 401 || status === 403) {\n      throw new Error(\n        which === 'current'\n          ? 'This machine\\'s Haven API key is no longer accepted. If a re-key already finished ' +\n            'elsewhere, run --rekey-finish with the key that re-key produced instead of starting a new one.'\n          : 'Haven rejected that API key. Check you pasted the whole key from the agent page — ' +\n            'nothing was changed.',\n      )\n    }\n    throw new Error(\n      `Could not reach Haven to check this agent (${redactSecrets(\n        err instanceof Error ? err.message : String(err),\n      )}). Nothing was changed.`,\n    )\n  }\n}\n\n/**\n * Refuse what the backend would refuse, before the owner starts anything.\n *\n * The legacy AllowanceModule rail is retired — no account can enter it since\n * #1984 and it cannot spend since #1986 — and its authority was per-token\n * allowances rather than a signed delegation, so there is no delegation to\n * revoke and re-issue — the backend answers a 409 naming re-onboarding as the\n * path (#1694). Finding that out here costs one read; finding it out from the\n * dashboard costs the owner a wallet prompt first.\n */\nfunction assertRekeyable(identity: AgentIdentity, stored: StoredCredentialSnapshot): void {\n  if (identity.id !== stored.agentId) {\n    throw new Error(\n      `The credentials at ${stored.directory} say agent ${stored.agentId}, but Haven says that key ` +\n        `belongs to ${identity.id}. Refusing to re-key an agent this directory does not own.`,\n    )\n  }\n  if (identity.execution_rail === 'legacy') {\n    throw new Error(\n      `Agent ${identity.name || identity.id} is on the legacy rail, which cannot be re-keyed — its ` +\n        'authority is per-token Safe allowances, not a signed delegation there is anything to ' +\n        're-issue. Re-onboard the agent on the delegation rail instead.',\n    )\n  }\n  if (identity.status === 'revoked') {\n    throw new Error(\n      `Agent ${identity.name || identity.id} is revoked. Re-keying would hand a revoked agent fresh ` +\n        'credentials — create a new agent instead.',\n    )\n  }\n}\n","/**\n * Restart guidance after a re-key (#1700).\n *\n * ## Why this is not `activationInstruction`\n *\n * The runtime registry already carries an activation line per runtime, and it\n * is right for what it does — a first-time setup, where the user is sitting in\n * front of the one thing they just configured. A re-key is a different\n * situation: the agent was ALREADY running, in however many places it was\n * wired, and every one of those processes is holding the old API key in memory.\n *\n * #1681 finding B is the reason this exists at all: different long-lived\n * processes park on different stale wiring, so restarting the one in front of\n * you is not enough and \"restart your session\" is not an instruction, it is a\n * shrug. #1694's review then asked for the specific fix — print the COMMAND.\n * \"Restart Hermes\" cost the reporter time that `systemctl --user restart\n * hermes-gateway` would not have.\n *\n * ## What these commands are, and are not\n *\n * They are the common case, named concretely so the ninety-percent user can\n * copy one. They are NOT a claim to know this machine's process supervision —\n * a gateway under launchd, docker, pm2 or a bare `nohup` is none of these. So\n * every runtime's guidance ends with the sweep instruction rather than\n * implying the listed command is exhaustive, and the sweep is the part that is\n * always true.\n */\n\nexport interface RestartGuidance {\n  /** Copy-pasteable commands, most likely first. Possibly empty. */\n  commands: string[]\n  /** Rendered lines, commands included, for the human-readable path. */\n  lines: string[]\n}\n\nconst SWEEP =\n  'Then restart EVERY other long-lived MCP host on this machine — gateways, TUI workers, ' +\n  'editors. Each holds the wiring snapshot from its own start time, so after a re-key each ' +\n  'one is still presenting the OLD API key and will fail with 401 until it restarts.'\n\nconst BY_RUNTIME: Record<string, { commands: string[]; how: string }> = {\n  'claude-code': {\n    commands: ['claude --continue'],\n    how: 'Exit this Claude Code session and start a new one:',\n  },\n  'codex-cli': {\n    commands: ['codex resume --last'],\n    how: 'Start a fresh Codex CLI session:',\n  },\n  'codex-desktop': {\n    commands: [],\n    how: 'Quit Codex Desktop completely (not just the window) and reopen it.',\n  },\n  'claude-desktop': {\n    commands: [],\n    how: 'Quit Claude Desktop completely (not just the window) and reopen it.',\n  },\n  hermes: {\n    commands: ['systemctl --user restart hermes-gateway', '/restart'],\n    how:\n      'Restart the Hermes gateway, or run /restart inside a Hermes session. The first form is ' +\n      'the one that matters if you run it as a user service:',\n  },\n  cursor: {\n    commands: [],\n    how:\n      'Cursor hot-reloads MCP config, so it will pick the new key up on its own. If a tool call ' +\n      'still fails with 401, reload the window (Cmd/Ctrl+Shift+P → \"Reload Window\").',\n  },\n  vscode: {\n    commands: [],\n    how:\n      'VS Code hot-reloads MCP config. If a tool call still fails with 401, reload the window ' +\n      '(Cmd/Ctrl+Shift+P → \"Reload Window\").',\n  },\n  'vscode-insiders': {\n    commands: [],\n    how:\n      'VS Code Insiders hot-reloads MCP config. If a tool call still fails with 401, reload the ' +\n      'window (Cmd/Ctrl+Shift+P → \"Reload Window\").',\n  },\n}\n\nexport function restartGuidance(runtime?: string): RestartGuidance {\n  const profile = runtime ? BY_RUNTIME[runtime] : undefined\n  const lines: string[] = ['The new key is only live in a process that started after now.', '']\n\n  if (profile) {\n    lines.push(profile.how)\n    for (const command of profile.commands) lines.push(`    ${command}`)\n    if (profile.commands.length > 0) lines.push('')\n  } else {\n    // No --runtime, or one with no known command. Say so rather than printing\n    // a command for the wrong host — a confidently wrong restart command is\n    // worse than none, because it looks like it worked.\n    lines.push(\n      runtime\n        ? `No standard restart command is known for \"${runtime}\" — restart it the way you start it.`\n        : 'Pass --runtime <name> to get the restart command for a specific host.',\n    )\n    lines.push('')\n  }\n\n  lines.push(SWEEP)\n  return { commands: profile?.commands ?? [], lines }\n}\n","/**\n * `--doctor` / `--repair` (#1589, epic #1585) — end-to-end setup diagnosis\n * without hand-building an MCP stdio client, which is what the 2026-08-18\n * external Codex Desktop tester was reduced to.\n *\n * Doctor is READ-ONLY (its one spawn is the same read-only tools/list\n * handshake setup itself uses) and secret-free: checks report names, paths,\n * versions and verdicts — never the api key or any key material. Repair\n * re-runs the pieces setup already owns — reinstall the pinned signer\n * runtime, rewrite wrapper + sidecar, re-write the runtime config from the\n * STORED identity — and never touches credentials or needs a new setup token.\n *\n * Design notes carried in from #1587's review:\n * - the signer probe reports the initialize payload, so compat versions come\n *   from the SAME handshake (no second probe);\n * - a probe against an un-acknowledged consent gate exits 1 — the doctor\n *   reports that as \"consent missing\" with the ack re-run as the repair,\n *   never as \"signer broken\".\n *\n * #1911 extends \"secret-free\" to the newest file that holds key material: the\n * doctor reports THAT a `--rekey` is parked (#1700's `rekey-pending.json`),\n * when, where and at which public address — through an accessor that does not\n * return the private half at all, so no output path can leak it by omission.\n * Repair still never deletes it: an expired TTL is a refusal to use the key,\n * not a licence to destroy key material the owner may still be mid-flow on.\n */\n\nimport { pruneSignerRuntimes } from './prune-runtimes.js'\nimport { spawn } from 'node:child_process'\nimport { readFile, readdir, stat } from 'node:fs/promises'\nimport { connectorRerunCommand } from '@haven_ai/sdk'\nimport { homedir } from 'node:os'\nimport { basename, dirname, join } from 'node:path'\nimport { MCP_RUNTIME_MANIFEST, signerPackageSpec } from './runtime-manifest.js'\nimport {\n  probeHostedAgentIdentity,\n  probeHostedMcpTools,\n  probeLocalMcpTools,\n  type LocalMcpProbeResult,\n} from './probes.js'\nimport {\n  installedRuntimeMatchesVersions,\n  prepareSignerRuntime,\n  readRuntimeSidecar,\n  type SignerRuntimeSidecar,\n} from './signer-runtime.js'\nimport {\n  RUNTIME_SPEC_ENV,\n  describeRuntimeSpecOverride,\n  resolveRuntimeSpecOverride,\n  RuntimeSpecOverrideError,\n} from './runtime-spec-override.js'\nimport { runtimeConfigPathFor, writeRuntimeConfig } from './config-writers.js'\nimport { normalizeRuntimeName, restartRequiredForRuntime, RUNTIME_FLAG_VALUE_LIST, type RuntimeId } from './runtime-registry.js'\nimport { getLocalSignerConsentStatus } from './signer-consent.js'\nimport { TOMBSTONE_FILENAME, readAgentTombstone, readTombstoneRecords, tombstonesDirForAgentDirectory } from './tombstone.js'\nimport { serverNamesFor, type ServerNames } from './server-names.js'\nimport { CONNECT_OUTCOME_FILENAME, readConnectOutcomeRuntime, readMcpServerBinding, REKEY_PENDING_FILENAME, inspectRekeyPending, resolveAgentDirectoryBySlug, assertDirectoryRecordsSlug, type RekeyPendingStatus } from './storage.js'\nimport { shortAddress, withoutUserinfo } from './redact.js'\n\n/**\n * #3121: three verdicts, not two. `ok` is \"nothing to say\"; `advisory` is\n * \"worth telling you, and nothing is broken\" — an intact install that is\n * behind the connector's pin, or a classification the connector cannot make\n * on this runtime; `failed` is a real failure. Only `failed` reaches the exit\n * code. Before #3121 an advisory had to be reported as a failure or not at\n * all, and an install that passed one day failed the next with no action by\n * anyone, because the pinned dev build had moved overnight.\n */\nexport type DoctorLevel = 'ok' | 'advisory' | 'failed'\n\nexport interface DoctorCheck {\n  id: string\n  label: string\n  /**\n   * Kept for `--json` consumers that branch on it (#1589 shape): `true` for\n   * `ok` AND `advisory`, `false` only for `failed` — so `check.ok`, like\n   * `report.ok`, answers \"is anything broken\", never \"is there nothing to\n   * say\". The level is the finer answer. Derived from `level` in one place\n   * (`finalizeCheck`); the two cannot disagree.\n   */\n  ok: boolean\n  level: DoctorLevel\n  /** Human detail — never secret material. */\n  detail: string\n  /** One concrete action, present when the check is not `ok` (a `failed` check always; an `advisory` when there is one). */\n  repair?: string\n}\n\n/** A check as its site states it: the level, never `ok` — `finalizeCheck` derives that. */\ntype CheckVerdict = Omit<DoctorCheck, 'ok'>\n\nfunction finalizeCheck(check: CheckVerdict): DoctorCheck {\n  return { ...check, ok: check.level !== 'failed' }\n}\n\n/** The rolled-up level: `failed` if any check failed, else `advisory` if any advised, else `ok`. */\nexport function rollUpLevel(checks: ReadonlyArray<Pick<DoctorCheck, 'level'>>): DoctorLevel {\n  if (checks.some((check) => check.level === 'failed')) return 'failed'\n  if (checks.some((check) => check.level === 'advisory')) return 'advisory'\n  return 'ok'\n}\n\nexport interface DoctorReport {\n  version: 1\n  /**\n   * `true` exactly when `level !== 'failed'` — the same predicate the exit\n   * code uses, so `--json` consumers that branch on `ok` see exit 0 ⇔ ok.\n   * Before #3121 this meant \"every check passed\"; an advisory now leaves it\n   * `true`. Additive within `version: 1` (#3121 decisions 3 and 4).\n   */\n  ok: boolean\n  /** #3121: the rolled-up verdict over the flat checks and every WIRED agent's checks. */\n  level: DoctorLevel\n  runtime: string\n  credentialDirectory?: string\n  checks: DoctorCheck[]\n  /** #1697: one entry per credential directory found on this machine. */\n  agents: AgentInventoryEntry[]\n  /** Signer compat surface from the live handshake, when it succeeded. */\n  signerCapabilities?: Record<string, unknown>\n}\n\nexport interface DoctorDeps {\n  /** #3123 test seam: the dry-run prune the doctor consults (names only — see the call site). */\n  pruneSignerRuntimes?: typeof pruneSignerRuntimes\n  homeDir?: string\n  fetch?: typeof fetch\n  probeSignerTools?: typeof probeLocalMcpTools\n  probeHosted?: typeof probeHostedMcpTools\n  probeHostedIdentity?: typeof probeHostedAgentIdentity\n  runCommand?: (command: string, args: string[]) => Promise<void>\n  env?: NodeJS.ProcessEnv\n  /**\n   * #3799 test seam: re-acknowledge consent by running the recorded wrapper's\n   * `--ack` (the INSTALLED signer writes the ack, so a HAVEN_SIGNER_SPEC\n   * override cannot produce a mismatching hash). Default: execFile below.\n   */\n  runSignerAck?: (wrapperPath: string) => Promise<{ stdout: string }>\n  /** Injected clock — the pending-re-key TTL is the only time-dependent check (#1911). */\n  now?: () => number\n}\n\n/**\n * #3799: token-free re-consent. Run the recorded wrapper with `--ack` and\n * stdin closed — the signer prints its consent block and writes the ack next\n * to the credential file. Going through the wrapper (not this process's\n * bundled signer) is the point: the ack must describe the signer that will\n * actually run.\n */\nfunction runWrapperAck(wrapperPath: string, timeoutMs = 30_000): Promise<{ stdout: string }> {\n  return new Promise((resolve, reject) => {\n    const child = spawn(wrapperPath, ['--ack'], { stdio: ['ignore', 'pipe', 'pipe'] })\n    let stdout = ''\n    let settled = false\n    const timer = setTimeout(() => {\n      if (settled) return\n      settled = true\n      child.kill()\n      reject(new Error(`signer --ack timed out after ${Math.round(timeoutMs / 1000)}s`))\n    }, timeoutMs)\n    child.stdout?.on('data', (chunk: Buffer) => {\n      stdout += chunk.toString('utf8')\n    })\n    child.on('error', (err) => {\n      if (settled) return\n      settled = true\n      clearTimeout(timer)\n      reject(err)\n    })\n    child.on('close', (code) => {\n      if (settled) return\n      settled = true\n      clearTimeout(timer)\n      if (code === 0) resolve({ stdout })\n      else reject(new Error(`signer --ack exited ${code ?? 'abnormally'}`))\n    })\n  })\n}\n\n/**\n * #3799: the `--name <slug>` repair line for a named pair — no\n * `--credentials-dir` needed, the pair record selects the directory.\n */\nfunction repairCommandNamedFor(runtime: string, slug: string): string {\n  const nameFlag = ` --name ${slug}`\n  if (normalizeRuntimeName(runtime)) return `Run: ${RERUN} --doctor --repair --runtime ${runtime}${nameFlag}`\n  return (\n    `Run: ${RERUN} --doctor --repair --runtime <runtime>${nameFlag} — --repair needs the runtime named; ` +\n    `one of: ${RUNTIME_FLAG_VALUE_LIST.join(', ')}.`\n  )\n}\n\ninterface IdentityFile {\n  api_key?: string\n  agent_id?: string\n  api_url?: string\n  hosted_mcp_url?: string\n  /** #2908: the name this package writes from this release on. */\n  account_address?: string\n  /** Pre-#2908 name; still read by every runtime, rewritten on the next re-key. */\n  safe_address?: string\n}\n\n// #2423: the channel comes from the SDK's build-time `HAVEN_CONNECTOR_CHANNEL`,\n// so a `@dev` snapshot tells its tester to re-run `@dev` instead of quietly\n// pointing them back at the production connector.\nconst RERUN = connectorRerunCommand()\n\n/**\n * #3120: the `--runtime <id>` fragment for a `--doctor` rerun string, or ''\n * when the runtime is unknown. A flagless `--doctor` rerun is a real command\n * (#3210: it resolves the runtime from the setup record again), so the empty\n * case renders as plain `--doctor` instead of a truncated `--runtime ` that\n * breaks when pasted.\n */\nfunction runtimeFlagFor(runtime: string): string {\n  return normalizeRuntimeName(runtime) ? ` --runtime ${runtime}` : ''\n}\n\nasync function pathExists(path: string): Promise<boolean> {\n  try {\n    await stat(path)\n    return true\n  } catch {\n    return false\n  }\n}\n\n/**\n * #3412: ` --credentials-dir <dir>` for a repair line, or '' when no directory\n * is named. A repair REWRITES the runtime config from one agent's stored\n * credentials, and without the flag `runRepair` picks the newest credential\n * directory by mtime — which on a machine with several agents is not\n * necessarily the agent the doctor just described (2026-09-28: a repair meant\n * for a dev agent re-wired a newer prod one). So every repair line names its\n * directory whenever more than one agent lives here. Quoted for a POSIX shell\n * only when it needs to be, so the common `~/.haven/agents/<id>` prints unquoted.\n */\nfunction credentialsDirFlagFor(credentialsDir?: string): string {\n  if (!credentialsDir) return ''\n  const quoted = /^[\\w@%+=:,./~-]+$/.test(credentialsDir)\n    ? credentialsDir\n    : `'${credentialsDir.replace(/'/g, `'\\\\''`)}'`\n  return ` --credentials-dir ${quoted}`\n}\n\n/**\n * #3210 review: the `--doctor --repair` command for a repair string. `--repair`\n * REQUIRES `--runtime` in the parser (it rewrites that runtime's config), so a\n * bare `--doctor --repair` is refused when pasted — the exact dead end the\n * unknown-runtime path used to render. With the runtime unknown the command\n * carries an explicit `<runtime>` placeholder — the form the #2424\n * `runtime_spec_override` repair already uses unconditionally — and names the\n * allowed values, so the user is told what to fill in rather than bounced.\n * `suffix` may end with a period; the unknown branch drops it so the\n * explanatory clause reads on from the command.\n */\nfunction repairCommandFor(runtime: string, suffix = '', credentialsDir?: string): string {\n  const dirFlag = credentialsDirFlagFor(credentialsDir)\n  if (normalizeRuntimeName(runtime)) return `Run: ${RERUN} --doctor --repair --runtime ${runtime}${dirFlag}${suffix}`\n  return (\n    `Run: ${RERUN} --doctor --repair --runtime <runtime>${dirFlag}${suffix.replace(/\\.$/, '')} — --repair needs the runtime named; ` +\n    `one of: ${RUNTIME_FLAG_VALUE_LIST.join(', ')}.`\n  )\n}\n\n/**\n * #3120: which runtime the doctor is actually looking at.\n *\n * `cli.ts` passes `parsed.options.runtime ?? ''` — an absent flag is the empty\n * string, which is \"nobody said\", not a runtime. `runtimeConfigPathFor('')`\n * falls through to null and the pre-#3120 doctor reported that as a green\n * \"CLI-managed\" check no runtime could distinguish from Claude Code's real\n * one. Resolution order:\n *\n * 1. An explicit, non-empty `--runtime` wins VERBATIM. The doctor reports what\n *    was asked for, not a re-spelled alias: `--runtime Cowork` stays\n *    `Cowork` in the report and in `--json`, while `runtimeConfigPathFor` and\n *    the registry normalize it internally as they always have.\n * 2. Otherwise the connector's own record: the `ConnectOutcome` each setup\n *    (success or failure) parks in the agent credential directory's\n *    `last-connect-outcome.json`. The PRIMARY directory's record answers for\n *    the run — per-directory resolution feeds `agentIsWired`, which is #3121's\n *    consequence to own, not this one's.\n * 3. Otherwise unknown (''). Every consumer treats unknown as its honest\n *    degraded verdict; nothing falls back to env detection, which would guess\n *    from the doctor's own shell rather than the runtime the agent uses.\n *\n * `origin` says where a non-flag value came from, so `--doctor --repair` can\n * state which runtime it resolved and from where before it rewrites a config.\n */\nasync function resolveDoctorRuntime(\n  input: { runtime: string; credentialsDir?: string },\n  directory: string | undefined,\n): Promise<{ runtime: string; origin: 'flag' | 'record' | 'unknown' }> {\n  const explicit = input.runtime.trim()\n  if (explicit) return { runtime: explicit, origin: 'flag' }\n  if (directory) {\n    const recorded = await readConnectOutcomeRuntime(directory)\n    if (recorded !== null && normalizeRuntimeName(recorded)) {\n      return { runtime: recorded, origin: 'record' }\n    }\n  }\n  return { runtime: '', origin: 'unknown' }\n}\n\n/**\n * Newest agent directory that holds an identity.json, plus every OTHER such\n * directory (#1688). The others used to be a cosmetic note (\"N dirs found;\n * examining the newest\") — which downgraded the exact fact that matters: a\n * re-run mints a fresh agent and, without `--replace` (#2551), retires\n * nothing, so a directory this doctor did NOT select can hold a key that\n * still authenticates and still spends.\n * The superseded_agents check now owns that fact; the note is gone.\n *\n * ## Three tells, not two (#1915)\n *\n * A directory is an agent credential directory if it holds ANY of\n * `identity.json`, `TOMBSTONE.json` or `rekey-pending.json`. The third was\n * added because #1911 shipped a diagnostic for abandoned re-key key material\n * and this was the one directory shape that diagnostic could not look at: no\n * enumeration, no `agents[]` entry, no `inspectRekeyPending` call, and so a\n * live private key at mode 0600 invisible in both the human output and\n * `--json`.\n *\n * The shipped `--rekey` flow cannot produce that shape — `writeRekeyPending`\n * writes into an EXISTING agent's directory, `startRekey` reads stored\n * credentials first, and tombstoning does not delete the pending file — so it\n * takes an out-of-band deletion of `identity.json` while the pending file\n * survives. Narrow. It is guarded anyway because of what is in the file: this\n * is the only tell whose *presence* is itself the hazard being reported, so a\n * blind spot here is a hole in the tool's stated job rather than a missing\n * nice-to-have. Cost is one `stat`, reached only when the two prior tells\n * both miss.\n *\n * `parkedOnly` records WHY such a directory was enumerated, so the classifier\n * can say `parked` from evidence instead of inferring it from an absent\n * identity — a corrupt `identity.json` must keep reading `orphaned`.\n */\nasync function discoverCredentialDirectory(\n  homeDir: string,\n  explicit?: string,\n): Promise<{ directory?: string; others: string[]; parkedOnly: Set<string>; identityDirectories: string[] }> {\n  // An explicit --credentials-dir names the agent DIRECTORY itself, so its\n  // siblings live in its parent — never in the default root. Scanning the\n  // default root under an explicit override would live-probe real keys in a\n  // location the caller explicitly pointed away from (#1688 review, B2).\n  const root = explicit ? dirname(explicit) : join(homeDir, '.haven', 'agents')\n  let entries: string[] = []\n  try {\n    entries = await readdir(root)\n  } catch {\n    return explicit\n      ? { directory: explicit, others: [], parkedOnly: new Set(), identityDirectories: [explicit] }\n      : { others: [], parkedOnly: new Set(), identityDirectories: [] }\n  }\n  const candidates: Array<{ directory: string; mtimeMs: number }> = []\n  // #1681: a directory whose keys were removed but that carries TOMBSTONE.json\n  // is a deliberately retired agent — reportable in the superseded scan, but\n  // never selectable as the active credential directory.\n  const tombstonedOnly: string[] = []\n  // #1915: neither identity nor tombstone, but parked re-key key material.\n  // Like `tombstonedOnly` this is a REPORTABLE, never SELECTABLE directory —\n  // it holds no credentials to describe, so promoting it to the primary would\n  // make the flat check list describe an agent that is not there.\n  const parkedOnly: string[] = []\n  for (const entry of entries) {\n    const directory = join(root, entry)\n    // #3496: the tombstone tell is checked BEFORE identity, not inside the\n    // missing-identity catch. A retired directory that kept its identity.json\n    // beside its TOMBSTONE.json (the --replace-era shape) was selectable as\n    // the primary whenever that identity was the newest on disk — the doctor\n    // then reported the live agent as superseded and prescribed a full\n    // re-setup. Still reportable as retired (#1681); never selectable,\n    // whether or not identity.json survives.\n    if (await pathExists(join(directory, TOMBSTONE_FILENAME))) {\n      tombstonedOnly.push(directory)\n      continue\n    }\n    try {\n      const s = await stat(join(directory, 'identity.json'))\n      candidates.push({ directory, mtimeMs: s.mtimeMs })\n    } catch {\n      try {\n        await stat(join(directory, REKEY_PENDING_FILENAME))\n        parkedOnly.push(directory)\n      } catch {\n        // not an agent credential dir\n      }\n    }\n  }\n  const parkedOnlySet = new Set(parkedOnly)\n  candidates.sort((a, b) => b.mtimeMs - a.mtimeMs)\n  // #3412: every directory holding an identity.json — the agents a repair could\n  // land on. More than one means a repair line must name its directory.\n  const identityDirectories = candidates.map((c) => c.directory)\n  if (explicit) {\n    return {\n      directory: explicit,\n      others: [...candidates.map((c) => c.directory), ...tombstonedOnly, ...parkedOnly]\n        .filter((d) => d !== explicit),\n      parkedOnly: parkedOnlySet,\n      identityDirectories: [explicit, ...identityDirectories.filter((d) => d !== explicit)],\n    }\n  }\n  if (candidates.length === 0 && tombstonedOnly.length === 0 && parkedOnly.length === 0) {\n    return { others: [], parkedOnly: parkedOnlySet, identityDirectories }\n  }\n  return {\n    directory: candidates[0]?.directory,\n    others: [...candidates.slice(1).map((c) => c.directory), ...tombstonedOnly, ...parkedOnly],\n    parkedOnly: parkedOnlySet,\n    identityDirectories,\n  }\n}\n\n/**\n * #1697: one entry per credential directory on this machine.\n *\n * \"Newest wins\" was a single-agent heuristic: it named one directory the real\n * one and demoted the rest to a note. Multi-agent (#1696) makes several\n * agents legitimately live at once, so the doctor enumerates instead of\n * choosing, and says which of four things each directory IS.\n */\n/**\n * What a credential directory IS:\n *\n * - `wired` — has a usable key and the runtime config actually launches it;\n * - `superseded` — has a usable key the runtime is NOT using (still spends);\n * - `retired` — carries a `TOMBSTONE.json`, a deliberate retirement record;\n * - `orphaned` — has an `identity.json` that yields no usable API key;\n * - `parked` (#1915) — holds `rekey-pending.json` and neither of the other\n *   two tells. Not a broken agent: there is no agent here at all, only the\n *   private key a `--rekey` generated and nobody finished with. It is its own\n *   value rather than folded into `orphaned` because the two carry different\n *   instructions — `orphaned` says \"this credential set is unusable, re-run\n *   setup\", while `parked` says \"this is loose key material; take the agent\n *   id to the Haven agent page, then decide whether to delete\". Reporting the\n *   second as the first would print a verdict a reader cannot act on, which\n *   is how a report teaches people to skim.\n */\nexport type AgentClassification = 'wired' | 'superseded' | 'retired' | 'orphaned' | 'parked'\n\nexport interface AgentInventoryEntry {\n  /** Wiring slug (#1696); absent for the bare haven / haven-signer pair. */\n  slug?: string\n  agentId?: string\n  directory: string\n  classification: AgentClassification\n  /**\n   * Per-agent checks. Empty for entries that are not wired, with one\n   * exception: a directory holding a pending re-key carries that check\n   * whatever its classification (#1911) — an abandoned re-key in a superseded\n   * or retired directory is precisely the case nothing else looks at.\n   */\n  checks: DoctorCheck[]\n  /**\n   * #1911: a started-but-unfinished `--rekey` in this directory, when there is\n   * one. Populated for EVERY classification — the whole point is that the file\n   * holds live key material in a directory nothing else is looking at. Address\n   * and timing only; the private half is not in this shape (see\n   * `RekeyPendingStatus`).\n   *\n   * \"Every classification\" became literally true in #1915. As shipped, it\n   * meant every classification the ENUMERATION could reach, and a directory\n   * holding only `rekey-pending.json` matched no discovery tell at all — so\n   * the one shape whose sole content is the hazard was the one shape this\n   * field could never describe. Such a directory is now enumerated and\n   * classified `parked`.\n   *\n   * \"Populated\", not \"gates the exit code\": `report.ok` rolls up the flat\n   * `checks` array plus WIRED entries' checks only, so this field and a\n   * non-wired entry's `checks` are reporting surfaces, not gates. An abandoned\n   * parked key outside the primary directory reaches the exit code through the\n   * flat `rekey_pending_elsewhere` check instead — see its comment in\n   * `runDoctor` for why that check exists rather than a cascade rule change.\n   */\n  rekeyPending?: RekeyPendingStatus\n}\n\n/**\n * #3830: Claude Code keeps its MCP servers in `~/.claude.json` — user scope\n * `mcpServers`, and per-project `projects[<path>].mcpServers` — a file the\n * connector does not write, so `runtimeConfigPathFor` names no config for it\n * and `agentIsWired` used to fall back to \"the selected directory is wired,\n * the rest are not\". Under named pairs by default (#3737) that labelled a\n * second, deliberately connected agent `superseded` and still spend-capable.\n *\n * This reduces the file to what `agentIsWired` matches on — each server's\n * NAME, launch command and args, and URL — one line per server. `env` and\n * `headers` are never kept: they can hold secrets, and wiring evidence does\n * not need them. The text is only matched against, never printed. Returns\n * null when the file is missing, unparseable, or names no servers; the\n * caller then keeps the fallback exactly as before. Project-scope `.mcp.json`\n * files are not discoverable from here, so this is positive evidence only:\n * it can show a directory IS wired, never that it is not.\n */\nasync function readClaudeCodeWiringEvidence(homeDir: string): Promise<string | null> {\n  let parsed: unknown\n  try {\n    parsed = JSON.parse(await readFile(join(homeDir, '.claude.json'), 'utf8'))\n  } catch {\n    return null\n  }\n  if (typeof parsed !== 'object' || parsed === null) return null\n  const blocks: unknown[] = [(parsed as { mcpServers?: unknown }).mcpServers]\n  const projects = (parsed as { projects?: unknown }).projects\n  if (typeof projects === 'object' && projects !== null) {\n    for (const project of Object.values(projects as Record<string, unknown>)) {\n      if (typeof project === 'object' && project !== null) blocks.push((project as { mcpServers?: unknown }).mcpServers)\n    }\n  }\n  const lines: string[] = []\n  for (const block of blocks) {\n    if (typeof block !== 'object' || block === null) continue\n    for (const [name, server] of Object.entries(block as Record<string, unknown>)) {\n      const entry = typeof server === 'object' && server !== null ? (server as Record<string, unknown>) : {}\n      const parts = [JSON.stringify(name) + ':']\n      if (typeof entry.command === 'string') parts.push(entry.command)\n      if (Array.isArray(entry.args)) parts.push(...entry.args.filter((arg): arg is string => typeof arg === 'string'))\n      if (typeof entry.url === 'string') parts.push(entry.url)\n      lines.push(parts.join(' '))\n    }\n  }\n  return lines.length > 0 ? lines.join('\\n') : null\n}\n\n/**\n * Is this agent's MCP pair actually present in the runtime's config?\n *\n * The answer depends on whether the pair is NAMED, because only a named pair\n * has a name of its own:\n * - NAMED (#1696): its entry name is unique, so the name in the config text\n *   settles it.\n * - UNNAMED: every unnamed agent claims the same bare `haven` /\n *   `haven-signer` names, so the name proves nothing — exactly one of them\n *   can be wired, and the tell is which signer wrapper path the config\n *   actually references.\n * - No readable config at all (Claude Code is CLI-managed, or the file is\n *   missing): this module cannot tell. Guessing \"orphaned\" would accuse every\n *   agent on the most common runtime, so it falls back to the pre-#1697\n *   heuristic — the selected directory is wired, the rest are not — which is\n *   the honest degradation rather than a fabricated verdict.\n */\nfunction agentIsWired(\n  configText: string | null,\n  names: ServerNames,\n  slug: string | undefined,\n  identity: IdentityFile | undefined,\n  sidecar: SignerRuntimeSidecar | null,\n  isPrimary: boolean,\n  bareOwnerExists: boolean,\n): boolean {\n  if (configText === null) return isPrimary\n  if (slug) {\n    // Match the NAME with a boundary so `haven-ops` cannot match\n    // `haven-ops-2` and `haven` cannot match `haven-ops`.\n    for (const name of [names.hosted, names.codexHosted, names.signer, names.codexSigner]) {\n      if (new RegExp(`(^|[.\"'\\\\s\\\\[])${name}([\"'\\\\]:\\\\s]|$)`, 'm').test(configText)) return true\n    }\n    return false\n  }\n  if (sidecar?.wrapper_path && configText.includes(sidecar.wrapper_path)) return true\n  // #1697 review, finding 2: a sidecar whose wrapper is NOT referenced is not\n  // proof of the opposite. A config still on the retired npx launch form\n  // (which the runtime_config check flags separately) names no wrapper at\n  // all, and condemning that directory as superseded would tell the user to\n  // revoke their only working agent. Fall through to the same ownership\n  // reasoning the sidecar-less case uses.\n  // No proof of ownership of the bare\n  // pair. If some OTHER directory's wrapper is the one the config launches,\n  // the bare pair is already owned and this one is not wired — even when it\n  // is the newest. Only when nothing owns the bare pair does the pre-#1697\n  // heuristic apply.\n  if (bareOwnerExists) return false\n  return isPrimary && Boolean(identity?.hosted_mcp_url && configText.includes(identity.hosted_mcp_url))\n}\n\n/**\n * #1911 — the one state `doctor` could not see: a `--rekey` that was started\n * and never finished.\n *\n * `rekey-pending.json` holds a freshly generated PRIVATE key between the two\n * re-key phases (#1700). It is 0600, in the same directory, at the same mode,\n * as the live signer key it is about to replace — so it is not a new exposure.\n * What it is, is invisible: the surface whose entire job is \"tell me what\n * state this machine's Haven wiring is in\" did not read the file, so an\n * abandoned re-key left key material on disk with nothing naming it, and a\n * lost terminal left the owner with no way to re-read the address they were\n * supposed to paste except by running `--rekey` again and discarding the\n * parked keypair.\n *\n * This check reports THAT one exists, when it started, when it expires, its\n * PUBLIC address and its path. Never its contents — the accessor it reads does\n * not return them.\n *\n * ## What this can and cannot tell you about #1868\n *\n * #1868 establishes that a re-key abandoned AFTER the on-chain revoke wedges\n * the agent: the old delegations are gone, no new ones were issued, nothing\n * expires the in-flight row, and the only way back is a manual owner re-grant.\n * A re-key abandoned BEFORE the revoke costs nothing at all. Those two are\n * worth very different words, so this check says only what it can actually\n * establish:\n *\n * - **Can distinguish: the backend re-key COMPLETED.** `agents.delegate_address`\n *   is swapped at the `complete` stage, so a hosted identity already reporting\n *   the address this machine generated proves the whole owner-signed sequence\n *   ran. Nothing is wedged; only the local half is outstanding, and\n *   `--rekey-finish` closes it.\n * - **Cannot distinguish: before the revoke vs. after it,** within the\n *   not-completed case. `rekey-pending.json` is written before the owner opens\n *   the dashboard and is never touched again, so it records nothing about how\n *   far the backend got; and the identity probe this connector makes reads two\n *   fields (`id`, `delegate_address`) from `GET /machine-payments/agent`, whose\n *   response is `id`, `name`, `status`, `account_address` (`safe_address`\n *   until #2914), `delegate_address`,\n *   `delegate_account_address`, `chain_id` and `execution_rail` — **none of\n *   which is a re-key stage**. The absent field is what matters here, not the\n *   count: there is nothing on this endpoint to read the stage from, so\n *   widening the probe would not help. So \"never started on the agent page\" and \"started, revoked,\n *   abandoned — the #1868 wedge\" are the same observation from here. The check\n *   says so, and points at the agent page, rather than implying the reassuring\n *   half.\n */\nfunction rekeyPendingCheck(\n  status: RekeyPendingStatus,\n  hostedDelegateAddress: string | undefined,\n  runtime: string,\n  slug: string | undefined,\n): DoctorCheck {\n  return finalizeCheck(rekeyPendingVerdict(status, hostedDelegateAddress, runtime, slug))\n}\n\nfunction rekeyPendingVerdict(\n  status: RekeyPendingStatus,\n  hostedDelegateAddress: string | undefined,\n  runtime: string,\n  slug: string | undefined,\n): CheckVerdict {\n  const label = 'Pending re-key'\n  const nameFlag = slug ? ` --name ${slug}` : ''\n  if (status.state === 'unreadable') {\n    return {\n      id: 'rekey_pending',\n      label,\n      level: 'failed',\n      detail:\n        `A re-key was started here but ${status.path} does not parse, so neither the address it ` +\n        'generated nor when it started can be read. The file still holds what was a private key.',\n      repair: `Delete ${status.path}, then start again: ${RERUN} --rekey${nameFlag}`,\n    }\n  }\n\n  const started = status.startedAt ?? 'an unknown time'\n  const address = status.newDelegateAddress ?? 'unknown'\n  const completedOnHaven =\n    hostedDelegateAddress !== undefined &&\n    status.newDelegateAddress !== undefined &&\n    hostedDelegateAddress.toLowerCase() === status.newDelegateAddress.toLowerCase()\n\n  if (completedOnHaven) {\n    // The one branch with a definite backend answer. Haven already signs as\n    // the new address, so this machine is the only thing left behind — and\n    // `identity_match` is failing for exactly this reason, which this check\n    // explains rather than repeats.\n    return {\n      id: 'rekey_pending',\n      label,\n      level: 'failed',\n      detail:\n        `A re-key started ${started} has COMPLETED on Haven — the agent's signing address is already ` +\n        `${address}, the one this machine generated — but the local half was never finished, so the ` +\n        `credential files here still hold the old key. Parked at ${status.path}.` +\n        (status.state === 'expired'\n          ? ' The local file is also past its 24h TTL, which --rekey-finish refuses, so the finish ' +\n            'command below will not accept it any more.'\n          : ''),\n      repair:\n        status.state === 'expired'\n          ? `The parked key expired. Start again — ${RERUN} --rekey${nameFlag} — and re-run \"Replace ` +\n            'signing key\" on the Haven agent page with the new address it prints.'\n          : `Run: ${RERUN} --rekey-finish${nameFlag} --api-key <the key the agent page showed you>${runtimeFlagFor(runtime)}`,\n    }\n  }\n\n  // Not completed. What is UNKNOWN from here is how far the agent page got —\n  // and the two possibilities are free and expensive respectively (#1868).\n  const wedgeNote =\n    'Haven is NOT yet on this address, so the re-key did not complete. This machine cannot tell ' +\n    'whether the on-chain revoke on the agent page already ran: if it did not, closing this costs ' +\n    \"nothing; if it did, the agent's old delegations are revoked, no new ones were issued, and only \" +\n    'an owner re-grant restores its spend authority (#1868). Check the agent page before assuming ' +\n    'the harmless case.'\n\n  if (status.state === 'expired') {\n    return {\n      id: 'rekey_pending',\n      label,\n      level: 'failed',\n      detail:\n        `A re-key started ${started} EXPIRED ${status.expiresAt ?? ''} without being finished. Its ` +\n        `address was ${address}; the private half it generated is still on disk at ${status.path}. ` +\n        wedgeNote,\n      repair:\n        `Either delete ${status.path} to drop the parked key, or start over: ${RERUN} --rekey${nameFlag}. ` +\n        'Connect never deletes it for you — an expired TTL is a refusal to USE the key, not a licence ' +\n        'to destroy key material you may still be mid-flow on.',\n    }\n  }\n\n  return {\n    id: 'rekey_pending',\n    label,\n    level: 'ok',\n    detail:\n      `A re-key started ${started} is still open (expires ${status.expiresAt ?? 'unknown'}). Paste this ` +\n      `address into \"Replace signing key\" on the Haven agent page: ${address}. Parked at ${status.path}. ` +\n      wedgeNote,\n  }\n}\n\nasync function runtimeSpecOverrideCheck(\n  directory: string,\n  sidecar: SignerRuntimeSidecar | null,\n  env: NodeJS.ProcessEnv,\n  repairDir?: string,\n): Promise<DoctorCheck | undefined> {\n  const facts: string[] = []\n  const installed = sidecar?.runtime_spec_override\n  if (installed) {\n    facts.push(\n      `signer runtime installed under ${describeRuntimeSpecOverride(installed.specs)} ` +\n        `(resolved: ${installed.resolved_specs.join(' ')}; directory key ${installed.directory_key})`,\n    )\n  }\n  // The `--local` topology's sidecar, when this directory has one.\n  const mcpInstalled = await readMcpSidecarOverride(directory)\n  if (mcpInstalled) {\n    facts.push(\n      `local MCP runtime installed under ${describeRuntimeSpecOverride(mcpInstalled.specs)} ` +\n        `(resolved: ${mcpInstalled.resolved_specs.join(' ')}; directory key ${mcpInstalled.directory_key})`,\n    )\n  }\n  let shell: string | undefined\n  try {\n    const active = resolveRuntimeSpecOverride(env)\n    if (active) shell = `set in this shell: ${describeRuntimeSpecOverride(active)} — a --repair from here installs these, not the pin`\n  } catch (err) {\n    shell = err instanceof RuntimeSpecOverrideError\n      ? `set in this shell but REFUSED: ${err.message}`\n      : `set in this shell but unreadable: ${err instanceof Error ? err.message : String(err)}`\n  }\n  if (shell) facts.push(shell)\n  if (facts.length === 0) return undefined\n  const variables = Object.values(RUNTIME_SPEC_ENV).join(' / ')\n  return finalizeCheck({\n    id: 'runtime_spec_override',\n    label: 'Runtime spec override',\n    level: 'failed',\n    detail: `runtime spec overridden — not the pinned manifest (${MCP_RUNTIME_MANIFEST.signerPackage}@${MCP_RUNTIME_MANIFEST.signerVersion}, ${MCP_RUNTIME_MANIFEST.sdkPackage}@${MCP_RUNTIME_MANIFEST.sdkVersion}). ${facts.join('. ')}.`,\n    repair: `Developer override (#2424). To return to the pinned manifest: unset ${variables}, then run ${RERUN} --doctor --repair --runtime <runtime>${credentialsDirFlagFor(repairDir)}. If the override is intentional, this finding is the record of it.`,\n  })\n}\n\nasync function readMcpSidecarOverride(\n  directory: string,\n): Promise<{ specs: Record<string, string>; resolved_specs: string[]; directory_key: string } | undefined> {\n  try {\n    const parsed = JSON.parse(await readFile(join(directory, 'mcp-runtime.json'), 'utf8')) as {\n      runtime_spec_override?: { specs: Record<string, string>; resolved_specs: string[]; directory_key: string }\n    }\n    return parsed.runtime_spec_override\n  } catch {\n    return undefined\n  }\n}\n\nasync function readIdentity(directory: string): Promise<IdentityFile | undefined> {\n  try {\n    return JSON.parse(await readFile(join(directory, 'identity.json'), 'utf8')) as IdentityFile\n  } catch {\n    return undefined\n  }\n}\n\n/**\n * #2908: which NAME the stored files carry the account address under. Reported\n * rather than judged — both are read by every runtime this connector installs\n * (the `safe_address` fallback is permanent, #2906 decision 2a), so neither is\n * a failure; a set written before #2908 simply says so, and the next re-key or\n * setup rewrites it under the new name. Exported for tests.\n */\nexport function describeAccountAddressKey(\n  identity: IdentityFile | undefined,\n  signerFile: Record<string, unknown> | undefined,\n): string {\n  const files = [identity as Record<string, unknown> | undefined, signerFile]\n  const has = (key: 'account_address' | 'safe_address') =>\n    files.some((f) => typeof f?.[key] === 'string' && (f[key] as string).trim() !== '')\n  if (has('account_address')) return 'account address stored as account_address'\n  if (has('safe_address')) {\n    return 'account address stored under the pre-#2908 name safe_address — still read; ' +\n      'the next --rekey or setup rewrites it as account_address'\n  }\n  return 'no account address stored'\n}\n\n/** Every per-agent check for ONE credential directory. */\nasync function checksForAgent(\n  entry: { directory: string; identity?: IdentityFile; sidecar: SignerRuntimeSidecar | null },\n  input: { runtime: string; repairDir?: string },\n  deps: DoctorDeps,\n): Promise<{ checks: DoctorCheck[]; signerCapabilities?: Record<string, unknown> }> {\n  const verdicts = await verdictsForAgent(entry, input, deps)\n  return {\n    checks: verdicts.checks.map(finalizeCheck),\n    ...(verdicts.signerCapabilities ? { signerCapabilities: verdicts.signerCapabilities } : {}),\n  }\n}\n\nasync function verdictsForAgent(\n  entry: { directory: string; identity?: IdentityFile; sidecar: SignerRuntimeSidecar | null },\n  // #3412: `repairDir` is set when several agents share this machine or the\n  // caller named the directory with --credentials-dir, so each repair line\n  // names the directory it is about.\n  input: { runtime: string; repairDir?: string },\n  deps: DoctorDeps,\n): Promise<{ checks: CheckVerdict[]; signerCapabilities?: Record<string, unknown> }> {\n  const { directory, identity, sidecar } = entry\n  const checks: CheckVerdict[] = []\n  let signerCapabilities: Record<string, unknown> | undefined\n\n  // ── Credentials ───────────────────────────────────────────────────────────\n  let signerFile: Record<string, unknown> | undefined\n  try {\n    const parsed = JSON.parse(await readFile(join(directory, 'signer.json'), 'utf8')) as Record<string, unknown>\n    signerFile = typeof parsed === 'object' && parsed !== null ? parsed : undefined\n  } catch {\n    signerFile = undefined\n  }\n  const credentialsOk = Boolean(identity?.api_key) && signerFile !== undefined\n  checks.push({\n    id: 'credentials',\n    label: 'Agent credentials',\n    level: credentialsOk ? 'ok' : 'failed',\n    detail: credentialsOk\n      ? `identity.json and signer.json parse (agent ${identity?.agent_id ?? 'unknown'}; ` +\n        `${describeAccountAddressKey(identity, signerFile)})`\n      : 'identity.json or signer.json is missing or unparseable.',\n    ...(credentialsOk ? {} : { repair: `Re-run the full setup with a fresh token: ${RERUN} --setup <token>.` }),\n  })\n\n  // ── Signer runtime install ────────────────────────────────────────────────\n  if (!sidecar) {\n    checks.push({\n      id: 'signer_runtime',\n      label: 'Signer runtime (preinstalled wrapper)',\n      level: 'failed',\n      detail: 'No signer-runtime.json sidecar — the pinned signer runtime was never prepared (or a pre-#1586 npx config).',\n      repair: repairCommandFor(input.runtime, '', input.repairDir),\n    })\n  } else if (sidecar.runtime_spec_override) {\n    // #2424: an override install is compared against what the run that wrote\n    // the sidecar recorded, not against the manifest — the manifest is exactly\n    // what the developer chose not to install. The override itself is the\n    // separate `runtime_spec_override` finding below.\n    const matches = await installedRuntimeMatchesVersions(sidecar.runtime_directory, sidecar.cli_path, {\n      signerVersion: sidecar.signer_version,\n      sdkVersion: sidecar.sdk_version,\n    })\n    checks.push({\n      id: 'signer_runtime',\n      label: 'Signer runtime (preinstalled wrapper)',\n      level: matches ? 'ok' : 'failed',\n      detail: matches\n        ? `Installed ${sidecar.signer_package}@${sidecar.signer_version} at ${sidecar.runtime_directory} (override install — see runtime_spec_override)`\n        : `Override runtime directory is stale or empty (${sidecar.runtime_directory}) — the CLI or package versions are missing.`,\n      ...(matches ? {} : { repair: repairCommandFor(input.runtime, ' with the same HAVEN_*_SPEC variables set.', input.repairDir) }),\n    })\n  } else {\n    // #2963: two questions, two references. \"Is the directory intact?\" is\n    // answered against the SIDECAR — what npm actually laid down when this\n    // runtime was installed — and \"is it current?\" against the MANIFEST pin.\n    // Comparing intactness against the manifest (the pre-#2963 shape) made\n    // the drift message unreachable: an install that was merely older than\n    // the pin failed the intactness check and was reported as \"stale or\n    // empty\" while its CLI sat there, 64 kB, serving tools to the very next\n    // check.\n    const intact = await installedRuntimeMatchesVersions(sidecar.runtime_directory, sidecar.cli_path, {\n      signerVersion: sidecar.signer_version,\n      sdkVersion: sidecar.sdk_version,\n    })\n    const versionOk = sidecar.signer_version === MCP_RUNTIME_MANIFEST.signerVersion\n    const ok = intact && versionOk\n    // #3121: intact but behind the pin is an ADVISORY — nothing is broken,\n    // the CLI serves tools to the very next check — so it no longer fails the\n    // run. The detail still names both versions and the repair still says how\n    // to catch up. Not intact is a real failure, as before.\n    checks.push({\n      id: 'signer_runtime',\n      label: 'Signer runtime (preinstalled wrapper)',\n      level: ok ? 'ok' : intact ? 'advisory' : 'failed',\n      detail: ok\n        ? `Installed ${sidecar.signer_package}@${sidecar.signer_version} at ${sidecar.runtime_directory}`\n        : intact\n          ? `Installed version ${sidecar.signer_version} does not match the connector's pinned ${MCP_RUNTIME_MANIFEST.signerVersion} — intact, but outdated.`\n          : `Runtime directory is stale or empty (${sidecar.runtime_directory}) — the CLI or package versions are missing.`,\n      ...(ok ? {} : { repair: repairCommandFor(input.runtime, '', input.repairDir) }),\n    })\n  }\n\n  // ── Runtime spec override (#2424) ─────────────────────────────────────────\n  // A finding, not a note: a developer override is legitimate and it is also\n  // the one state in which \"the signer runtime check is green\" says nothing\n  // about the pinned manifest. It fires on EITHER the installed truth (the\n  // sidecar says this directory was built under an override) or the shell\n  // truth (a HAVEN_*_SPEC variable is set right now, so a `--repair` from this\n  // shell would install that instead of the pin). No override anywhere → no\n  // check at all, so a production `--doctor` reads exactly as before.\n  const overrideCheck = await runtimeSpecOverrideCheck(directory, sidecar, deps.env ?? process.env, input.repairDir)\n  if (overrideCheck) checks.push(overrideCheck)\n\n  // ── Hosted MCP ────────────────────────────────────────────────────────────\n  const hostedUrl = identity?.hosted_mcp_url ?? (identity?.api_url ? `${identity.api_url}/mcp` : undefined)\n  if (identity?.api_key && hostedUrl) {\n    const probe = await (deps.probeHosted ?? probeHostedMcpTools)(identity.api_key, hostedUrl, deps.fetch)\n    checks.push({\n      id: 'hosted_mcp',\n      label: 'Hosted Haven MCP',\n      level: probe.status === 'ok' ? 'ok' : 'failed',\n      detail: probe.status === 'ok'\n        ? `MCP tools endpoint is reachable (${hostedUrl}).`\n        : `MCP tools endpoint probe failed: ${probe.status} (${hostedUrl}).`,\n      ...(probe.status === 'ok'\n        ? {}\n        : {\n            repair: 'Check network access and runtime configuration for the hosted MCP URL, then re-run --doctor.',\n          }),\n    })\n  } else {\n    checks.push({\n      id: 'hosted_mcp',\n      label: 'Hosted Haven MCP',\n      level: 'failed',\n      detail: 'No stored API key / hosted MCP URL to probe with.',\n      repair: `Re-run the full setup: ${RERUN} --setup <token>.`,\n    })\n  }\n\n  // ── Hosted-vs-local identity (#1697) ──────────────────────────────────────\n  // The #1681 incident, made mechanical: the API key and the signing key must\n  // belong to the SAME agent. A mismatch means the runtime would quote as one\n  // agent and sign as another — the exact shape #1690 refuses at signing time.\n  // This proves the on-disk pair is self-consistent, which is the half a local\n  // tool can know; it still cannot see inside an already-running host.\n  const localDelegate = typeof signerFile?.delegate_address === 'string'\n    ? (signerFile.delegate_address as string)\n    : undefined\n  // Hoisted for the pending-re-key check below: a hosted delegate that already\n  // equals the parked address is the one thing that proves a backend re-key\n  // completed (#1911). `undefined` when the probe did not succeed, which keeps\n  // \"could not ask\" out of the \"definitely not completed\" branch.\n  let hostedDelegateAddress: string | undefined\n  if (identity?.api_key && identity.api_url) {\n    const probe = await (deps.probeHostedIdentity ?? probeHostedAgentIdentity)(\n      identity.api_key, identity.api_url, deps.fetch,\n    )\n    if (probe.status === 'ok') hostedDelegateAddress = probe.delegateAddress\n    if (probe.status !== 'ok') {\n      // #1697 review, finding 1: an unperformable comparison is NOT a pass.\n      // Saying \"skipped, not passed\" in the text while setting ok:true is the\n      // same green-check-proving-nothing defect this check exists to remove —\n      // and worse here, because a real key mismatch that coincides with a\n      // network blip would sail through. `hosted_mcp` already fails on\n      // network_error; identity_match matches it rather than contradicting it.\n      checks.push({\n        id: 'identity_match',\n        label: 'Hosted identity matches the local signing key',\n        level: 'failed',\n        detail: probe.status === 'unauthorized'\n          ? 'The stored API key was rejected, so the agent it authenticates as cannot be compared with the local signing key.'\n          : `Could not read the hosted identity (${probe.status}) — the comparison did not happen, so it cannot be reported as a match.`,\n        repair: probe.status === 'unauthorized'\n          ? `Re-run the full setup with a fresh token: ${RERUN} --setup <token>.`\n          : `Restore network access to the Haven API, then re-run: ${RERUN} --doctor${runtimeFlagFor(input.runtime)}`,\n      })\n    } else if (!localDelegate) {\n      checks.push({\n        id: 'identity_match',\n        label: 'Hosted identity matches the local signing key',\n        level: 'failed',\n        detail: 'signer.json holds no delegate_address to compare against the hosted identity.',\n        repair: `Re-run the full setup with a fresh token: ${RERUN} --setup <token>.`,\n      })\n    } else {\n      const same = probe.delegateAddress?.toLowerCase() === localDelegate.toLowerCase()\n      checks.push({\n        id: 'identity_match',\n        label: 'Hosted identity matches the local signing key',\n        level: same ? 'ok' : 'failed',\n        detail: same\n          ? `The stored API key authenticates as the agent whose signing key is in this directory (${shortAddress(localDelegate)}).`\n          : `MISMATCH: the stored API key authenticates as agent ${probe.agentId ?? 'unknown'} with delegate ` +\n            `${shortAddress(probe.delegateAddress ?? 'unknown')}, but signer.json here holds ${shortAddress(localDelegate)}. ` +\n            'This runtime would quote as one agent and sign as another.',\n        ...(same\n          ? {}\n          : {\n              repair: 'Re-run setup for this agent so its API key and signing key come from one run: ' +\n                `${RERUN} --setup <token>. Do not hand-edit either file.`,\n            }),\n      })\n    }\n  }\n\n  // ── Pending re-key (#1911) ────────────────────────────────────────────────\n  const pending = await inspectRekeyPending(directory, deps.now?.() ?? Date.now())\n  if (pending) {\n    checks.push(rekeyPendingCheck(pending, hostedDelegateAddress, input.runtime, sidecar?.server_name))\n  }\n\n  // ── Signer stdio handshake ────────────────────────────────────────────────\n  if (sidecar) {\n    const consent = await getLocalSignerConsentStatus(join(directory, 'signer.json'))\n    if (!consent.acknowledged) {\n      checks.push({\n        id: 'signer_process',\n        label: 'Signer stdio handshake',\n        level: 'failed',\n        // #3799: honest about what the mismatch does and does not prove. The\n        // stored ack covers a tool SET; a doctor bundled with a newer signer\n        // reports exactly this against an older, still-working install.\n        detail:\n          'The stored local-tools consent does not match the tool set this connector bundles — by design a signer ' +\n          'with a different tool set refuses to start. This does not prove the currently running signer is broken: ' +\n          'a doctor newer than the installed signer reports exactly this mismatch.',\n        repair:\n          `Run: ${sidecar.wrapper_path} --ack < /dev/null — re-acknowledge consent with the installed signer, no setup token needed. ` +\n          `Or re-run repair with --ack-local-tools: ${repairCommandFor(input.runtime, ' --ack-local-tools', input.repairDir)}.`,\n      })\n    } else {\n      const probe: LocalMcpProbeResult = await (deps.probeSignerTools ?? probeLocalMcpTools)(\n        sidecar.wrapper_path,\n        [],\n        MCP_RUNTIME_MANIFEST.requiredSignerTools,\n      )\n      const experimental = (probe.capabilities?.experimental ?? probe.capabilities) as\n        | Record<string, unknown>\n        | undefined\n      const compat = experimental?.['haven/signer-compatibility'] as Record<string, unknown> | undefined\n      signerCapabilities = compat ? { 'haven/signer-compatibility': compat } : undefined\n      const compatDetail = compat\n        ? ` Compat: x402 expected-context v${JSON.stringify((compat as { x402_expected_context_versions?: unknown }).x402_expected_context_versions ?? '?')}.`\n        : ''\n      checks.push({\n        id: 'signer_process',\n        label: 'Signer stdio handshake',\n        level: probe.status === 'ok' ? 'ok' : 'failed',\n        detail: probe.status === 'ok'\n          ? `Signer started, listed ${probe.toolNames?.length ?? 0} tools${probe.serverInfo?.version ? ` (v${probe.serverInfo.version})` : ''}.${compatDetail}`\n          : `Handshake failed: ${probe.status}.`,\n        ...(probe.status === 'ok' ? {} : { repair: repairCommandFor(input.runtime, '', input.repairDir) }),\n      })\n    }\n  } else {\n    checks.push({\n      id: 'signer_process',\n      label: 'Signer stdio handshake',\n      level: 'failed',\n      detail: 'Skipped — no prepared signer runtime to probe.',\n      repair: repairCommandFor(input.runtime, '', input.repairDir),\n    })\n  }\n\n  return { checks, ...(signerCapabilities ? { signerCapabilities } : {}) }\n}\n\n/**\n * #3799: resolve `--name <slug>` to the directory that records the pair,\n * BEFORE discovery. `--name` with `--credentials-dir` must agree — refuse\n * otherwise, never silently prefer one. Returns the explicit directory for\n * discovery, or undefined when no name was given.\n */\nasync function resolveNamedDirectory(\n  input: { credentialsDir?: string; serverName?: string },\n  homeDir: string,\n): Promise<string | undefined> {\n  if (!input.serverName) return input.credentialsDir\n  if (input.credentialsDir) {\n    await assertDirectoryRecordsSlug(input.credentialsDir, input.serverName)\n    return input.credentialsDir\n  }\n  return resolveAgentDirectoryBySlug(input.serverName, { root: join(homeDir, '.haven', 'agents') })\n}\n\nexport async function runDoctor(\n  input: { runtime: string; credentialsDir?: string; serverName?: string },\n  deps: DoctorDeps = {},\n): Promise<DoctorReport> {\n  const homeDir = deps.homeDir ?? homedir()\n  const checks: CheckVerdict[] = []\n  let signerCapabilities: Record<string, unknown> | undefined\n\n  const namedDir = await resolveNamedDirectory(input, homeDir)\n  const { directory, others, parkedOnly, identityDirectories } = await discoverCredentialDirectory(homeDir, namedDir)\n  // #3412: with several agents on the machine — or when the caller already\n  // named the directory with --credentials-dir — every repair line names the\n  // directory it is about, so the pasted repair cannot fall back to a scan of\n  // ~/.haven/agents and land on a different agent. See `credentialsDirFlagFor`.\n  const nameRepairDir = identityDirectories.length > 1 || Boolean(namedDir)\n\n  // ── #3120: resolve the runtime BEFORE anything judges it ──────────────────\n  // An absent flag used to flow through as '' and earn a fabricated green\n  // \"CLI-managed\" verdict. Resolve the recorded runtime from the primary\n  // directory's own outcome record instead, and let every check below see the\n  // same resolved value.\n  const resolution = await resolveDoctorRuntime(input, directory)\n  const runtime = resolution.runtime\n  const input2 = { ...input, runtime }\n\n  // ── Runtime config (read once; every agent's wiring is judged against it) ─\n  // #3145 review: `runtimeConfigPathFor` switches on the RAW string, so a\n  // documented alias (`--runtime codex`) used to resolve to no path and take\n  // the \"CLI-managed\" skip while ~/.codex/config.toml sat unread. The path is\n  // looked up by the NORMALIZED id; the report keeps the flag verbatim.\n  const normalizedRuntime = normalizeRuntimeName(input2.runtime)\n  const configPath = runtimeConfigPathFor(normalizedRuntime ?? input2.runtime, homeDir)\n  let configText: string | null = null\n  if (configPath !== null) {\n    try {\n      configText = await readFile(configPath, 'utf8')\n    } catch {\n      configText = null\n    }\n  }\n  // #3830: wiring evidence for the runtime that owns no config file the\n  // connector writes. It feeds only the `wired` decision — the runtime-config\n  // checks keep reading `configText` and stay on the CLI-managed skip. A\n  // directory it upgrades is then a wired agent like any on Codex: it runs the\n  // full per-agent check set, and a failure there now fails the run.\n  const claudeCodeWiring =\n    configText === null && normalizedRuntime === 'claude-code' ? await readClaudeCodeWiringEvidence(homeDir) : null\n\n  // ── Inventory ─────────────────────────────────────────────────────────────\n  const allDirectories = directory ? [directory, ...others] : others\n  // Which directory (if any) owns the BARE haven / haven-signer pair? The\n  // config launches exactly one signer wrapper for it, and that path is the\n  // only unambiguous tell — the bare NAMES are claimed by every unnamed\n  // agent, so they identify nobody.\n  let bareOwnerExists = false\n  for (const dir of allDirectories) {\n    const sidecar = await readRuntimeSidecar(dir)\n    if (!sidecar?.server_name && sidecar?.wrapper_path && configText?.includes(sidecar.wrapper_path)) {\n      bareOwnerExists = true\n      break\n    }\n  }\n  const inventory: AgentInventoryEntry[] = []\n  const capabilitiesByDirectory = new Map<string, Record<string, unknown> | undefined>()\n  const primaryChecksById = new Map<string, DoctorCheck>()\n  for (const dir of allDirectories) {\n    const identity = await readIdentity(dir)\n    const sidecar = await readRuntimeSidecar(dir)\n    const tombstone = await readAgentTombstone(dir)\n    const slug = sidecar?.server_name\n    const names = serverNamesFor(slug)\n    // #1911: read on EVERY directory, before the not-wired early return. A\n    // retired or orphaned directory is exactly where an abandoned re-key would\n    // go unnoticed, and the file holds key material regardless of whether the\n    // agent it belongs to is still wired.\n    const rekeyPending = await inspectRekeyPending(dir, deps.now?.() ?? Date.now())\n    if (!identity?.api_key) {\n      // #1915: fall back to the agent id recorded IN the parked file. Without\n      // it a `parked` directory renders as `unknown: parked` — and the agent\n      // id is the one thing the owner has to carry to the Haven agent page\n      // before deciding whether the key is safe to delete.\n      const agentId = tombstone?.agent_id ?? rekeyPending?.agentId\n      inventory.push({\n        ...(slug ? { slug } : {}),\n        ...(agentId ? { agentId } : {}),\n        directory: dir,\n        // A tombstone is a deliberate record and outranks the discovery tell:\n        // a retired directory that also holds a parked key stays `retired`.\n        classification: tombstone ? 'retired' : parkedOnly.has(dir) ? 'parked' : 'orphaned',\n        checks: rekeyPending ? [rekeyPendingCheck(rekeyPending, undefined, input2.runtime, slug)] : [],\n        ...(rekeyPending ? { rekeyPending } : {}),\n      })\n      continue\n    }\n    const wired =\n      agentIsWired(configText, names, slug, identity, sidecar, dir === directory, bareOwnerExists) ||\n      // Additive only: a name or wrapper path in ~/.claude.json proves this\n      // directory is wired; its absence proves nothing (#3830), so the\n      // fallback verdict above is never downgraded.\n      (claudeCodeWiring !== null && agentIsWired(claudeCodeWiring, names, slug, identity, sidecar, false, false))\n    const entry: AgentInventoryEntry = {\n      ...(slug ? { slug } : {}),\n      ...(identity.agent_id ? { agentId: identity.agent_id } : {}),\n      directory: dir,\n      classification: wired ? 'wired' : 'superseded',\n      checks: [],\n      ...(rekeyPending ? { rekeyPending } : {}),\n    }\n    if (wired) {\n      const result = await checksForAgent(\n        { directory: dir, identity, sidecar },\n        { ...input2, ...(nameRepairDir ? { repairDir: dir } : {}) },\n        deps,\n      )\n      entry.checks = result.checks\n      capabilitiesByDirectory.set(dir, result.signerCapabilities)\n    } else if (rekeyPending) {\n      // A superseded directory runs no probes (that is the point — it is not\n      // the agent in use), so the backend-completed refinement is unavailable\n      // here and the check reports the file facts alone.\n      entry.checks = [rekeyPendingCheck(rekeyPending, undefined, input2.runtime, slug)]\n    }\n    inventory.push(entry)\n  }\n\n  // Which agent does the flat `checks` array describe? An explicitly given\n  // --credentials-dir always wins. Otherwise it is the first WIRED agent —\n  // not merely the newest directory, because a newly created but unwired\n  // credential set would otherwise hijack the report and describe an agent\n  // the runtime is not even using (#1697).\n  const wiredDirectories = inventory\n    .filter((entry) => entry.classification === 'wired')\n    .map((entry) => entry.directory)\n  const primaryDirectory = input.credentialsDir\n    ? directory\n    : (wiredDirectories.includes(directory ?? '') ? directory : wiredDirectories[0] ?? directory)\n  if (primaryDirectory) {\n    const primaryEntry = inventory.find((entry) => entry.directory === primaryDirectory)\n    signerCapabilities = capabilitiesByDirectory.get(primaryDirectory)\n    for (const check of primaryEntry?.checks ?? []) primaryChecksById.set(check.id, check)\n  }\n\n  // ── The historical single-agent check list, for the PRIMARY directory ─────\n  // A single-agent install must read exactly as it did before (#1697 AC), so\n  // the flat `checks` array keeps its order and ids; `agents` is the new,\n  // additive per-agent shape.\n  if (!primaryDirectory) {\n    checks.push({\n      id: 'credentials',\n      label: 'Agent credentials',\n      level: 'failed',\n      detail: 'No agent credential directory with an identity.json under ~/.haven/agents.',\n      repair: `Run the full setup once: ${RERUN} --setup <token from the Haven dashboard>.`,\n    })\n  } else {\n    const primaryIdentity = await readIdentity(primaryDirectory)\n    const primarySidecar = await readRuntimeSidecar(primaryDirectory)\n    // Keyed on a check `checksForAgent` ALWAYS produces, not on the map being\n    // empty (#1911): an unwired primary directory that happens to hold a\n    // pending re-key now carries that one check from the inventory pass, and a\n    // bare `size === 0` would read that as \"already done\" and silently skip\n    // every real check for the directory the user pointed at.\n    if (!primaryChecksById.has('credentials')) {\n      // The primary directory is not wired (or has no key): run its checks\n      // anyway — the user pointed the doctor at this machine, and silence\n      // about the selected directory would be the old heuristic's failure.\n      const result = await checksForAgent(\n        { directory: primaryDirectory, identity: primaryIdentity, sidecar: primarySidecar },\n        { ...input2, ...(nameRepairDir ? { repairDir: primaryDirectory } : {}) },\n        deps,\n      )\n      signerCapabilities = result.signerCapabilities\n      for (const check of result.checks) primaryChecksById.set(check.id, check)\n    }\n    // #2424: `runtime_spec_override` rides directly behind `signer_runtime`\n    // so the flat list shows the override next to the install it describes.\n    for (const id of ['credentials', 'signer_runtime', 'runtime_spec_override']) {\n      const check = primaryChecksById.get(id)\n      if (check) checks.push(check)\n    }\n  }\n\n  // #3121 review, finding 2: `configPath === null` has THREE causes, not two —\n  // unknown (''), a recognised runtime that owns no config file (claude-code,\n  // other), and a runtime string the connector does not recognise at all\n  // (`--runtime codex-clii` — args.ts does not validate the value). Only the\n  // second earns the honest skip and the advisory below; the third is a\n  // failure that names the allowed values, like the unknown case.\n  const runtimeOwnsNoConfig = normalizedRuntime !== null && configPath === null\n  if (configPath === null && input2.runtime !== '' && normalizedRuntime === null) {\n    checks.push({\n      id: 'runtime_config',\n      label: 'Runtime MCP config',\n      level: 'failed',\n      detail:\n        `Runtime '${input2.runtime}' is not one the connector recognises. The runtime config was NOT checked. ` +\n        `Re-run the doctor naming the runtime — one of: ${RUNTIME_FLAG_VALUE_LIST.join(', ')}.`,\n      repair: `Re-run the doctor naming the runtime — one of: ${RUNTIME_FLAG_VALUE_LIST.join(', ')}.`,\n    })\n  } else if (configPath === null && input2.runtime === '') {\n    // #3120: the fabricated pass lived here. configPath is null for TWO\n    // indistinguishable reasons — a CLI-managed runtime that really has no\n    // file-based config (claude-code, other), and an UNKNOWN runtime (\"nobody\n    // said\"). Only the first justifies a green skip; the second must say it\n    // could not look. `level: 'failed'` — deliberately NOT #3121's advisory\n    // level, so an unknown runtime can never ride a green exit code again.\n    checks.push({\n      id: 'runtime_config',\n      label: 'Runtime MCP config',\n      level: 'failed',\n      detail:\n        `Runtime is unknown — no runtime flag was given and the connector's record in ` +\n        `${primaryDirectory ?? namedDir ?? '~/.haven/agents'} carries no resolvable ` +\n        `${CONNECT_OUTCOME_FILENAME} runtime. The runtime config was NOT checked. Re-run the doctor ` +\n        `naming the runtime — one of: ${RUNTIME_FLAG_VALUE_LIST.join(', ')}.`,\n      repair: `Re-run the doctor naming the runtime — one of: ${RUNTIME_FLAG_VALUE_LIST.join(', ')}.`,\n    })\n  } else if (configPath === null) {\n    // claude-code / other: genuinely CLI-managed or manual — the honest skip\n    // the scope boundary preserves. The detail names the RESOLVED runtime\n    // (#3120), so \"CLI-managed\" is only ever claimed about a runtime that\n    // earned it. #3799: for Claude Code the doctor also names the pair the\n    // folder RECORDS and how to confirm it — the config lives in the Claude\n    // Code registry, which this connector neither reads nor writes, so\n    // \"skipping the file check\" without naming the pair left the agent with\n    // nothing to verify against.\n    const claudePairSuffix =\n      input2.runtime === 'claude-code' && primaryDirectory\n        ? await (async () => {\n            const sidecar = await readRuntimeSidecar(primaryDirectory)\n            const names = serverNamesFor(sidecar?.server_name)\n            return ` The MCP pair recorded for this folder is ${names.hosted} / ${names.signer} — confirm with \\`claude mcp get ${names.signer}\\`.`\n          })()\n        : ''\n    checks.push({\n      id: 'runtime_config',\n      label: 'Runtime MCP config',\n      level: 'ok',\n      detail: `Runtime '${input2.runtime}' is configured through its own CLI or by hand (${input2.runtime === 'other' ? 'manual runtime' : 'CLI-managed'}) and has no file-based config the connector owns — skipping the file check.${claudePairSuffix}`,\n    })\n  } else if (configText === null) {\n    checks.push({\n      id: 'runtime_config',\n      label: 'Runtime MCP config',\n      level: 'failed',\n      detail: `No runtime config at ${configPath}.`,\n      repair: repairCommandFor(input2.runtime, '', nameRepairDir ? primaryDirectory : undefined),\n    })\n  } else {\n    const primaryIdentity = await readIdentity(primaryDirectory ?? '')\n    const primarySidecar = primaryDirectory ? await readRuntimeSidecar(primaryDirectory) : null\n    const hasHaven = primaryIdentity?.hosted_mcp_url\n      ? configText.includes(primaryIdentity.hosted_mcp_url)\n      : configText.includes('haven')\n    // The wrapper form never writes the package spec into the config; only\n    // the retired npx launch does — so the spec's presence IS the tell.\n    const signerViaNpx = configText.includes('@haven_ai/signer')\n    const wrapperReferenced = primarySidecar ? configText.includes(primarySidecar.wrapper_path) : false\n    const ok = hasHaven && !signerViaNpx && (primarySidecar ? wrapperReferenced : true)\n    checks.push({\n      id: 'runtime_config',\n      label: 'Runtime MCP config',\n      level: ok ? 'ok' : 'failed',\n      detail: ok\n        ? `Config at ${configPath} references the hosted server and the prepared signer wrapper.`\n        : signerViaNpx\n          ? `Config at ${configPath} still launches the signer via npx — the pre-#1586 shape that cannot start under a 120s startup timeout.`\n          : `Config at ${configPath} is missing the Haven entries${primarySidecar && !wrapperReferenced ? ' (or references a different signer wrapper)' : ''}.`,\n      ...(ok ? {} : { repair: repairCommandFor(input2.runtime, '', nameRepairDir ? primaryDirectory : undefined) }),\n    })\n  }\n\n  for (const id of ['hosted_mcp', 'identity_match', 'rekey_pending']) {\n    const check = primaryChecksById.get(id)\n    if (check) checks.push(check)\n  }\n\n  // ── Superseded agents (#1688, now inventory-driven) ───────────────────────\n  // A re-run mints a NEW agent and, without `--replace` (#2551), retires\n  // nothing: the connector never deletes old directories (a replace tombstones\n  // one and strips its keys, which is `retired` below), registration only\n  // collides on delegate address,\n  // and cancel deliberately refuses to auto-revoke. Net effect: an MCP host\n  // that started before the re-run keeps spending as the agent the user\n  // believes they replaced — silently, because its old key still resolves.\n  // The doctor reports; the user decides — connect never revokes or deletes.\n  const otherEntries = inventory.filter((entry) => entry.directory !== primaryDirectory)\n  if (otherEntries.length > 0) {\n    // Labels carry their SOURCE ENTRY (#1697 review, finding 3): resolving a\n    // label back to an entry by string prefix would attribute one agent's\n    // classification to another whenever one id is a prefix of the next\n    // (`agent-1` / `agent-10`), and the failure mode is telling the user to\n    // revoke the live agent.\n    const live: Array<{ label: string; entry: AgentInventoryEntry }> = []\n    const revoked: string[] = []\n    const unverifiable: string[] = []\n    const retired: string[] = []\n    for (const entry of otherEntries) {\n      const identity = await readIdentity(entry.directory)\n      const tombstone = await readAgentTombstone(entry.directory)\n      // #1915 review: use the id the inventory already resolved rather than\n      // re-deriving a narrower one. It is identical for a wired, superseded or\n      // retired directory, and strictly better for one whose only id is in the\n      // parked file — a NAMED agent's directory basename is its wiring slug,\n      // so re-deriving would label the same directory by its slug here and by\n      // its real agent id in the \"Other agents\" section, for the same entry.\n      const otherAgent = entry.agentId ?? basename(entry.directory)\n      if (!identity?.api_key || !identity.api_url) {\n        if (tombstone) retired.push(`${otherAgent} (retired ${tombstone.retired_at})`)\n        else unverifiable.push(`${otherAgent} (no stored key/API URL to probe)`)\n        continue\n      }\n      const suffix = tombstone ? ' [tombstoned — key material still present]' : ''\n      // `tools/list` is intentionally static and does not authenticate its\n      // bearer. A spend-capability verdict therefore needs the authenticated\n      // agent-identity endpoint, not merely a reachable hosted MCP URL.\n      const probe = await (deps.probeHostedIdentity ?? probeHostedAgentIdentity)(\n        identity.api_key,\n        identity.api_url,\n        deps.fetch,\n      )\n      if (probe.status === 'ok') live.push({ label: `${otherAgent}${suffix}`, entry })\n      else if (probe.status === 'unauthorized') revoked.push(`${otherAgent}${suffix}`)\n      // network_error / bad_response: neither a false \"still live\" failure\n      // nor a false clean bill — a note, never a verdict.\n      else unverifiable.push(`${otherAgent} (${probe.status})${suffix}`)\n    }\n    const parts: string[] = []\n    if (live.length > 0) parts.push(`STILL SPEND-CAPABLE: ${live.map((item) => item.label).join(', ')}`)\n    if (revoked.length > 0) parts.push(`already revoked: ${revoked.join(', ')}`)\n    if (retired.length > 0) parts.push(`tombstoned (keys removed): ${retired.join(', ')}`)\n    if (unverifiable.length > 0) parts.push(`could not verify: ${unverifiable.join(', ')}`)\n    // #<new>: mirrored tombstone records whose credential directory is GONE.\n    // A retirement flow (or a full ~/.haven/agents wipe) deleted the dir, but\n    // the mirror keeps the retirement observable. Informational only — a\n    // record with no dir holds no key and can never spend, so it never fails\n    // this check. Reads the SAME home the doctor scans (deps.homeDir), never\n    // the ambient process home — an explicit --credentials-dir run must not\n    // consult the machine-wide default root (REGRESSION B2 discipline).\n    // #3251: the writers keep a record in the ledger of the root that held\n    // the retired directory, so the reader follows the root this run scans —\n    // an explicit --credentials-dir names an agent directory, whose parent is\n    // that root. Resolved against the doctor's own homeDir.\n    const knownIds = new Set([...inventory].map((e) => e.agentId ?? basename(e.directory)))\n    const ledgerDir = input.credentialsDir\n      ? tombstonesDirForAgentDirectory(input.credentialsDir, homeDir)\n      : join(homeDir, '.haven', 'tombstones')\n    const ghostRecords = (await readTombstoneRecords(ledgerDir)).filter(\n      (rec) => !knownIds.has(rec.agent_id),\n    )\n    if (ghostRecords.length > 0) {\n      parts.push(\n        `retired records (dir removed): ${ghostRecords\n          .map((rec) => `${rec.agent_id} (${rec.reason})`)\n          .join(', ')}`,\n      )\n    }\n    // #1697: a WIRED sibling is a legitimately live agent, not a superseded\n    // one — several agents may share a runtime now. Only unwired credential\n    // dirs make the check fail.\n    const supersededLive = live\n      .filter((item) => item.entry.classification !== 'wired')\n      .map((item) => item.label)\n    // #3121: with no readable config (`configText === null` — every\n    // claude-code run, by design, or a missing file) `agentIsWired` could only\n    // fall back to \"the selected directory is wired, the rest are not\", so a\n    // second agent the user deliberately wired on this runtime is classified\n    // `superseded` here without evidence. Failing the run on that would tell\n    // the user to revoke an agent they are using; the honest verdict is an\n    // ADVISORY that names the live keys and says why the classification is\n    // unreliable. The CLASSIFICATION itself does not change (decision 5) —\n    // only the severity of the check that reads it. With a readable config\n    // the classification is evidence, and a live unwired key stays a failure\n    // for every non-wired classification.\n    // Demoted only for a RECOGNISED runtime that owns no config file; an\n    // unrecognised runtime string or an unknown runtime keeps the failure\n    // (review finding 2 — a typo must not green-wash a live key).\n    const classificationUnreliable = configText === null && runtimeOwnsNoConfig\n    const supersededLevel: DoctorLevel =\n      supersededLive.length === 0 ? 'ok' : classificationUnreliable ? 'advisory' : 'failed'\n    checks.push({\n      id: 'superseded_agents',\n      // #3830: an advisory means the connector could not tell wired from\n      // superseded, so its label must not assert \"superseded\" either. The\n      // inventory `classification` stays as is (#3121 decision 5); the label\n      // is what a person reads.\n      label: supersededLevel === 'advisory' ? 'Other agent credentials (wiring not verifiable)' : 'Superseded agent credentials',\n      level: supersededLevel,\n      detail:\n        supersededLevel === 'failed'\n          ? `${otherEntries.length} other credential dir(s) found — ${parts.join('; ')}. A host started before ` +\n            'your latest setup keeps authenticating (and spending) as the old agent.'\n          : supersededLevel === 'advisory'\n            ? `${otherEntries.length} other credential dir(s) found — ${parts.join('; ')}. Runtime ` +\n              `'${input2.runtime}' has no config file the connector writes, and none it can read names these agents, so which of them ` +\n              'are wired cannot be verified from this machine: a live key here may be an agent you use ' +\n              'deliberately, or one a host started before your latest setup is still spending as.'\n            : `${otherEntries.length} other credential dir(s) found — ${parts.join('; ')}.`,\n      ...(supersededLevel === 'failed'\n        ? {\n            repair:\n              `Use Remove agent\\u2026 on the Haven agent page for ${supersededLive.join(', ')} (it ends each one\\u2019s live budgets), then remove the old ` +\n              'director(y/ies) under ~/.haven/agents. Connect never revokes or deletes for you.',\n          }\n        : supersededLevel === 'advisory'\n          ? {\n              repair:\n                `Check ${supersededLive.join(', ')} on the Haven agent page: use Remove agent\\u2026 on the ones you no longer use, ` +\n                'then remove their director(y/ies) under ~/.haven/agents. Connect never revokes or deletes for you.',\n            }\n          : {}),\n    })\n  }\n\n  // ── Rebound MCP server names (#3122) — advisory, only when two records ──\n  // collide. Each directory's `mcp-server-binding.json` says what ITS setup\n  // bound. Two directories claiming the same hosted name means the name\n  // changed hands locally: the later binding is what a runtime launches now,\n  // the earlier agent is what a saved session or document may still mean.\n  // Locally recorded facts only — the backend's `agents.mcp_server_name` is\n  // the authority for the same backend; this check does not assert\n  // otherwise, and names a backend change explicitly because that is the case\n  // the backend cannot see.\n  // A RETIRED directory's record is not a claim (#3154 review): it launches\n  // nothing, so it cannot be what a saved session resolves to, and a\n  // by-the-book reset (--tombstone + delete the key files) leaves the record\n  // behind without releasing it — only --unwire and the --replace retirement\n  // do. Counting it would make every reset produce a false \"changed hands\".\n  const bindings = (\n    await Promise.all(\n      inventory\n        .filter((entry) => entry.classification !== 'retired')\n        .map(async (entry) => ({ entry, binding: await readMcpServerBinding(entry.directory) })),\n    )\n  ).filter((item): item is { entry: AgentInventoryEntry; binding: NonNullable<typeof item.binding> } => item.binding !== null)\n  const byName = new Map<string, typeof bindings>()\n  for (const item of bindings) {\n    const list = byName.get(item.binding.server_name) ?? []\n    list.push(item)\n    byName.set(item.binding.server_name, list)\n  }\n  const rebound = [...byName.entries()].filter(([, items]) => items.length > 1)\n  if (rebound.length > 0) {\n    const parts = rebound.map(([name, items]) => {\n      const ordered = [...items].sort((a, b) => (a.binding.bound_at < b.binding.bound_at ? -1 : a.binding.bound_at > b.binding.bound_at ? 1 : 0))\n      // Stripped on read (#3154 doc r4): a legacy record may carry userinfo.\n      const backends = new Set(ordered.map((i) => withoutUserinfo(i.binding.api_url)))\n      return (\n        `'${name}': ` +\n        ordered.map((i) => `${i.binding.agent_id} on ${withoutUserinfo(i.binding.api_url)} at ${i.binding.bound_at} [${i.entry.classification}]`).join(' → ') +\n        (backends.size > 1 ? ' (BACKEND CHANGED)' : '')\n      )\n    })\n    checks.push({\n      id: 'mcp_server_name_rebound',\n      label: 'MCP server names bound more than once',\n      level: 'advisory',\n      detail:\n        `${rebound.length} MCP server name${rebound.length === 1 ? '' : 's'} changed hands on this machine (locally recorded ` +\n        `bindings; the backend's own record is the authority for the same backend): ${parts.join('; ')}. A saved session, ` +\n        'script or document naming the server may still mean the earlier agent.',\n      repair: `Retire the earlier director(y/ies) with ${RERUN} --unwire <dir> to release the name, or keep both and address them by --name — --doctor --repair --name <slug> now selects the pair directly.`,\n    })\n  }\n\n  // ── Parked re-keys in OTHER directories (#1911) ───────────────────────────\n  //\n  // Why this is a FLAT check and not merely a nested one. `report.ok` rolls up\n  // the flat list plus every WIRED agent's checks, so a hazard found only in a\n  // non-wired entry does not reach the exit code — and `--json` + `report.ok`\n  // is the obvious way a CI health-check consumes this. Leaving an abandoned\n  // private key visible only in `agents[]` would reproduce, one layer up,\n  // exactly the invisibility #1911 exists to remove: reported, but not\n  // reported anywhere that gates anything.\n  //\n  // The precedent is `superseded_agents` directly above: it is a flat check\n  // that FAILS on a credential hazard found in a directory that is explicitly\n  // not wired. This repo already treats \"spend-capable key material in a\n  // directory you are not using\" as exit-code-worthy, and a parked private key\n  // is the same kind of fact — arguably more so, since a superseded agent is\n  // at least an agent the owner once chose to create.\n  //\n  // Severity matches the per-agent check rather than inventing a second scale:\n  // an OPEN pending re-key elsewhere is someone mid-flow on another agent and\n  // stays informational; an EXPIRED or UNREADABLE one is the abandoned case\n  // and fails. Deleting is still nobody's call but the owner's.\n  //\n  // #1915 widened what reaches this check without touching the check itself.\n  // A `parked` directory is enumerated now, so its abandoned key cascades to\n  // the exit code through this existing rule on this existing severity scale.\n  // That is deliberate: the exit-code surface already moved once when #1911\n  // made an expired parked key a failure, and moving it a second time — a new\n  // check, or a new severity for this shape — would be a second behaviour\n  // change bought for a strictly narrower case than the first. The state that\n  // fails is the same state that already failed; only the set of directories\n  // it can be found in got honest.\n  const parkedElsewhere = inventory\n    .filter((entry) => entry.directory !== primaryDirectory && entry.rekeyPending)\n    .map((entry) => ({ entry, pending: entry.rekeyPending as RekeyPendingStatus }))\n  if (parkedElsewhere.length > 0) {\n    const abandoned = parkedElsewhere.filter((item) => item.pending.state !== 'pending')\n    const describe = (item: (typeof parkedElsewhere)[number]): string =>\n      `${item.entry.slug ?? item.entry.agentId ?? basename(item.entry.directory)} (${item.pending.state}, ${item.pending.path})`\n    checks.push({\n      id: 'rekey_pending_elsewhere',\n      label: 'Parked re-keys in other credential directories',\n      level: abandoned.length === 0 ? 'ok' : 'failed',\n      detail:\n        abandoned.length > 0\n          ? `ABANDONED re-key key material outside the agent this report describes: ${abandoned.map(describe).join(', ')}. ` +\n            'Each holds a private key that was generated for a re-key nobody finished.'\n          : `${parkedElsewhere.length} other director(y/ies) hold an open pending re-key: ${parkedElsewhere.map(describe).join(', ')}.`,\n      ...(abandoned.length > 0\n        ? {\n            repair:\n              'Check the Haven agent page for each before deleting: if its on-chain revoke already ran, the agent ' +\n              'has no spend authority until you re-grant it (#1868), and that is not visible from this machine. ' +\n              'Connect never deletes key material for you.',\n          }\n        : {}),\n    })\n  }\n\n  const signerProcess = primaryChecksById.get('signer_process')\n  if (signerProcess) checks.push(signerProcess)\n\n  // ── Unused signer-runtime directories (#3123) — advisory, only when any ─\n  // A dry-run prune: directories under ~/.haven/signer-runtime that no\n  // credential directory's sidecar or wrapper names and that are not the current pin.\n  // Reported here so the doctor's own repair advice can be completed without\n  // hand-editing directories; absent when there is nothing to reclaim, so a\n  // single-agent install reads exactly as before.\n  // `measure: false`: names only. Sizing walks every file under the root —\n  // 287k files, 2.0 GB on disk, on one developer machine: 28 s cold / 34 s\n  // warm in one #3151 reviewer's run, 1059 s cold in the other reviewer's\n  // sandbox (the figure depends on the cache and the box; none is a\n  // contract) — and the doctor is the command a user runs when something is\n  // already broken.\n  const prune = await (deps.pruneSignerRuntimes ?? pruneSignerRuntimes)({ dryRun: true, measure: false }, { homeDir, credentialsDir: input.credentialsDir })\n  const unused = prune.entries.filter((entry) => entry.action === 'would_remove')\n  if (unused.length > 0) {\n    checks.push({\n      id: 'signer_runtime_unused',\n      label: 'Unused signer-runtime directories',\n      level: 'advisory',\n      detail:\n        `${unused.length} signer-runtime director${unused.length === 1 ? 'y' : 'ies'} under ${prune.root} that no credential ` +\n        `directory names: ${unused.map((entry) => entry.key).join(', ')}. ` +\n        'Nothing is broken; they are left over from earlier pins or overrides (sizes: --prune-signer-runtimes --dry-run).',\n      repair: `Run: ${RERUN} --prune-signer-runtimes (add --dry-run to list only).`,\n    })\n  }\n\n  // #3210: say where a resolved runtime came from. `runRepair` already prints\n  // it; the read-only report did not, so a reader could not tell a checked\n  // config from an inherited one — and a STALE record (the user switched\n  // editors) would otherwise read as a plain pass on a file they no longer\n  // use. Appended to the primary runtime_config verdict, whatever its level.\n  if (resolution.origin === 'record') {\n    const rc = checks.find((check) => check.id === 'runtime_config')\n    if (rc) {\n      rc.detail += ` (Resolved '${resolution.runtime}' from ${join(directory ?? '', CONNECT_OUTCOME_FILENAME)}; pass --runtime to check a different one.)`\n    }\n  }\n\n  // ── Restart still required? (informational, never fails the doctor) ───────\n  // #3210 review: `restartRequiredForRuntime` falls back to env DETECTION for\n  // an empty OR unrecognised runtime — the doctor's own shell, not the runtime\n  // the agent uses — and would answer about a runtime nobody named. The\n  // resolution above never guesses; neither does this check: unknown stays\n  // unknown, and an unrecognised value gets the \"no requirement known\" line.\n  const restart = normalizedRuntime === null ? false : restartRequiredForRuntime(input2.runtime, deps.env)\n  checks.push({\n    id: 'restart',\n    label: 'Runtime restart',\n    level: 'ok',\n    detail: restart\n      ? 'This runtime loads MCP config at startup — restart it after any repair before expecting the tools to appear.'\n      : input2.runtime === ''\n        ? 'Runtime is unknown — whether a restart is needed cannot be determined. Re-run the doctor naming the runtime for a definitive answer.'\n        : 'No restart requirement known for this runtime.',\n  })\n\n  // #1697: exit non-zero if ANY wired agent fails ANY check — not just the\n  // one the old heuristic happened to select. #3121: \"fails\" means level\n  // `failed`; a wired agent's advisory rolls up to `advisory`, never to the\n  // exit code.\n  const wiredChecks = inventory\n    .filter((entry) => entry.classification === 'wired')\n    .flatMap((entry) => entry.checks)\n  const finalChecks = checks.map(finalizeCheck)\n  const level = rollUpLevel([...finalChecks, ...wiredChecks])\n\n  return {\n    version: 1,\n    ok: level !== 'failed',\n    level,\n    runtime: input2.runtime,\n    credentialDirectory: primaryDirectory,\n    checks: finalChecks,\n    agents: inventory,\n    ...(signerCapabilities ? { signerCapabilities } : {}),\n  }\n}\n\nexport interface RepairResult {\n  ok: boolean\n  messages: string[]\n}\n\n/** Re-run the pieces setup owns; never touches credentials or tokens. */\nexport async function runRepair(\n  input: { runtime: string; credentialsDir?: string; serverName?: string; ackLocalTools?: boolean },\n  deps: DoctorDeps = {},\n): Promise<RepairResult> {\n  const homeDir = deps.homeDir ?? homedir()\n  const messages: string[] = []\n  // #3799: --name resolves the directory by its RECORDED pair before discovery\n  // (refusing on unknown slug, a rebound name, or disagreement with\n  // --credentials-dir), so naming the agent replaces the mtime guess.\n  const namedDir = await resolveNamedDirectory(input, homeDir)\n  const { directory, others, identityDirectories } = await discoverCredentialDirectory(homeDir, namedDir)\n  // #3412: repair REWRITES the runtime config from ONE agent's stored\n  // credentials. With several agents on the machine and no --credentials-dir,\n  // \"the newest directory by mtime\" is a guess — and the doctor's primary is\n  // chosen differently (first wired agent), so the two could disagree. On\n  // 2026-09-28 exactly that re-wired a prod agent when a dev one was meant.\n  // Refuse the guess and hand back one exact command per agent instead.\n  // #3799: a --name that resolved cleanly IS the naming — no refusal.\n  if (!namedDir && identityDirectories.length > 1) {\n    const lines = await Promise.all(\n      identityDirectories.map(async (dir) => {\n        const identity = await readIdentity(dir)\n        const who = identity?.agent_id ? `agent ${identity.agent_id}` : 'agent (no agent_id recorded)'\n        // A retired directory (tombstoned, or its key stripped by --unwire /\n        // --replace) still COUNTS — otherwise one live agent beside a newer\n        // retired directory would fall back to the mtime guess — but it is\n        // never offered as a target: repairing it would re-wire a retired\n        // agent's credentials over its tombstone.\n        const retired = !identity?.api_key || (await pathExists(join(dir, TOMBSTONE_FILENAME)))\n        // #3799: name the PAIR each directory owns — the sidecar records it,\n        // and the pair is what the calling agent knows itself by. Named pairs\n        // are offered a --name command; the bare pair still needs the\n        // directory spelled out.\n        const sidecar = await readRuntimeSidecar(dir)\n        const slug = sidecar?.server_name\n        const pair = slug\n          ? `${serverNamesFor(slug).hosted} / ${serverNamesFor(slug).signer}`\n          : 'the bare haven / haven-signer pair'\n        return retired\n          ? `  • ${who} — ${pair} (${dir}): retired — not a repair target`\n          : slug\n            ? `  • ${who} — owns ${pair}: ${repairCommandNamedFor(input.runtime, slug).replace(/^Run: /, '')}`\n            : `  • ${who} — owns ${pair}: ${repairCommandFor(input.runtime, '', dir).replace(/^Run: /, '')}`\n      }),\n    )\n    return {\n      ok: false,\n      messages: [\n        `${identityDirectories.length} agent credential directories exist on this machine, and a repair rewrites the ` +\n          'runtime config from ONE of them. Name the agent to repair with --name <slug> (its recorded pair) or --credentials-dir — nothing was changed:',\n        ...lines,\n        'Not sure which agent is which? Compare the agent ids against the Haven agent page, or run --doctor first.',\n      ],\n    }\n  }\n  if (others.length > 0) {\n    // Repair never touches the other directories — that is the doctor's\n    // superseded_agents check's job to REPORT and the user's to act on.\n    messages.push(`Note: ${others.length} other agent credential dir(s) exist — run --doctor for their status.`)\n  }\n  if (!directory) {\n    return {\n      ok: false,\n      messages: [`No agent credentials found to repair — run the full setup: ${RERUN} --setup <token>.`],\n    }\n  }\n\n  // #3120: repair REWRITES the runtime config, so an inherited runtime is\n  // worse here than in a read-only check. Resolve exactly like the doctor\n  // does — explicit flag verbatim, else the record the setup parked in this\n  // directory — and refuse to touch any config while the runtime is unknown.\n  const resolution = await resolveDoctorRuntime(input, directory)\n  if (resolution.origin === 'record') {\n    messages.push(`Runtime not given — resolved '${resolution.runtime}' from ${join(directory, CONNECT_OUTCOME_FILENAME)}.`)\n  }\n  const runtime = resolution.runtime\n  const input2 = { ...input, runtime }\n  if (runtime === '') {\n    return {\n      ok: false,\n      messages: [\n        'Runtime is unknown — no runtime flag was given and the connector record carries no resolvable runtime.',\n        'Repair rewrites the runtime config, so it will not guess. Re-run repair naming the runtime — ' +\n          `one of: ${RUNTIME_FLAG_VALUE_LIST.join(', ')}.`,\n      ],\n    }\n  }\n\n  let identity: IdentityFile\n  try {\n    identity = JSON.parse(await readFile(join(directory, 'identity.json'), 'utf8')) as IdentityFile\n  } catch {\n    return { ok: false, messages: ['identity.json is unreadable — re-run the full setup with a fresh token.'] }\n  }\n  if (!identity.api_key || !(identity.hosted_mcp_url || identity.api_url)) {\n    return { ok: false, messages: ['identity.json lacks the stored API key / hosted URL — re-run the full setup.'] }\n  }\n\n  // #1589 review (HIGH): a --local (local-stdio) setup writes a structurally\n  // different config (the haven entry is the LOCAL MCP wrapper, not the\n  // hosted URL). Repair only knows how to write the hosted+signer shape, so\n  // clobbering a local config would convert a working topology silently —\n  // the exact class of harm a repair tool must never cause. Detect and\n  // refuse: the local wrapper (bin/haven-mcp) and its mcp-runtime sidecar\n  // are the tell.\n  // Looked up by the normalized id for the same reason as in runDoctor: an\n  // alias must not skip this refusal and clobber a local topology.\n  const configPath = runtimeConfigPathFor(normalizeRuntimeName(input2.runtime) ?? input2.runtime, homeDir)\n  if (configPath) {\n    try {\n      const existing = await readFile(configPath, 'utf8')\n      if (existing.includes('bin/haven-mcp') || existing.includes('.haven/mcp-runtime')) {\n        return {\n          ok: false,\n          messages: [\n            `The config at ${configPath} is the LOCAL-stdio topology (--local). Repair currently rewrites only the hosted+signer shape and will not touch it.`,\n            'Re-run your original connector command (with --local) to repair a local-stdio install.',\n          ],\n        }\n      }\n    } catch {\n      // No existing config — nothing to clobber; proceed.\n    }\n  }\n\n  // #1910: WHICH MCP pair does this directory own? `serverNamesFor(undefined)`\n  // is the BARE `haven` / `haven-signer` pair, so a repair that omits the slug\n  // does not merely fail to fix the named agent it was pointed at — it\n  // overwrites a *different*, working agent's entries with this one's\n  // credentials and wrapper path. `--repair` is what people reach for when\n  // something is already broken; breaking a second agent is the worst\n  // available outcome.\n  //\n  // The slug is not a flag the user must remember to repeat: #1696 records it\n  // in this directory's own sidecar, which is already on disk. Read it before\n  // `prepareSignerRuntime` — that call REWRITES the sidecar, and passing the\n  // slug back in is what stops the rewrite from erasing it (a second, quieter\n  // half of the same defect: a repaired named agent would afterwards read as\n  // an unnamed one to every later `--doctor`).\n  const existingSidecar = await readRuntimeSidecar(directory)\n  const serverName = existingSidecar?.server_name\n\n  const signerPath = join(directory, 'signer.json')\n\n  // ── Consent gate (#3799; owner decision 2026-10-09: explicit flag, never automatic) ──\n  // The stored ack covers the signer's tool SET: a repair that installs a\n  // signer with a newer tool set would otherwise finish and leave the agent\n  // unable to start the signer (HAVEN_SIGNER_NO_CONSENT) until re-consent.\n  // Without --ack-local-tools, stop BEFORE writing anything and name the\n  // token-free re-consent — produced by the installed signer via the recorded\n  // wrapper's `--ack`, so a HAVEN_SIGNER_SPEC override cannot mint a\n  // mismatching hash. Never claim the tools \"grew\": a rekey, a chain change\n  // or the address-shape case produce the same mismatch, and the ack file\n  // holds only the hash.\n  const consent = await getLocalSignerConsentStatus(signerPath)\n  const consentMismatch =\n    !consent.acknowledged && (consent.reason === 'ack_file_missing' || consent.reason === 'ack_file_mismatch')\n  if (consentMismatch && !input.ackLocalTools) {\n    const wrapperPath = existingSidecar?.wrapper_path ?? join(directory, 'bin', 'haven-signer.mjs')\n    return {\n      ok: false,\n      messages: [\n        'Repair stopped before writing anything: the signer it installs would refuse to start until local-tools ' +\n          'consent is re-acknowledged — the stored acknowledgement does not match the tool set of the signer this connector pins.',\n        'The mismatch does not prove the currently running signer is broken; a newer tool set is enough to explain it.',\n        `Re-consent without a setup token, produced by the installed signer: ${wrapperPath} --ack < /dev/null`,\n        `Or re-run repair with --ack-local-tools to re-consent during the repair: ${repairCommandFor(input2.runtime, ' --ack-local-tools', directory)}`,\n      ],\n    }\n  }\n\n  const prepared = await prepareSignerRuntime(\n    { credentialDirectory: directory, signerPath, homeDir, serverName },\n    { runCommand: deps.runCommand, env: deps.env },\n  )\n  messages.push(...prepared.messages)\n\n  const names = serverNamesFor(serverName)\n\n  // #3799: say what the repair ACTUALLY writes. writeRuntimeConfig has no\n  // case for runtimes configured through their own CLI (claude-code) — there\n  // the write is a no-op and the old unconditional \"Rewriting MCP entries\"\n  // line was a falsehood. What really changed is the wrapper re-point (above)\n  // plus the sidecar; whichever MCP entry launches the wrapper picks up the\n  // new signer after a restart.\n  const rewritesConfig = runtimeConfigPathFor(normalizeRuntimeName(input2.runtime) ?? input2.runtime, homeDir) !== null\n  if (rewritesConfig) {\n    messages.push(`Rewriting MCP entries ${names.hosted} / ${names.signer}${serverName ? ` (agent \"${serverName}\")` : ' (unnamed pair)'} — no other pair is touched.`)\n  } else {\n    messages.push(\n      `Re-pointed ${prepared.wrapperPath} at signer ${signerPackageSpec()}. ` +\n        (input2.runtime === 'claude-code'\n          ? `Claude Code's MCP entries were not touched — the entry that launches this wrapper uses the new signer after a restart. Confirm with \\`claude mcp get ${names.signer}\\`.`\n          : `No MCP config was written — '${input2.runtime}' is configured through its own CLI or by hand; the entry that launches this wrapper uses the new signer after a restart.`),\n    )\n  }\n\n  if (consentMismatch && input.ackLocalTools) {\n    messages.push(`Re-acknowledging local-tools consent with the installed signer (${signerPackageSpec()}):`)\n    try {\n      const ack = await (deps.runSignerAck ?? runWrapperAck)(prepared.wrapperPath)\n      for (const line of ack.stdout.split('\\n')) {\n        if (line.trim()) messages.push(`  ${line}`)\n      }\n    } catch (err) {\n      return {\n        ok: false,\n        messages: [\n          ...messages,\n          `The re-acknowledgement failed: ${err instanceof Error ? err.message : String(err)} — consent was NOT written; the runtime config was not rewritten.`,\n        ],\n      }\n    }\n    const after = await getLocalSignerConsentStatus(signerPath)\n    if (!after.acknowledged) {\n      return {\n        ok: false,\n        messages: [\n          ...messages,\n          `Consent still does not match after the re-acknowledgement (${after.reason ?? after.error}). The runtime config was not rewritten.`,\n        ],\n      }\n    }\n    messages.push('Local-tools consent acknowledged for the installed signer.')\n  }\n\n  const configResult = await writeRuntimeConfig({\n    // Normalized for the WRITE too (#3145 review round 3): `writeRuntimeConfig`\n    // switches on the id, and the raw alias fell to its \"manual runtime\" arm\n    // — a repair that reported success while writing nothing.\n    runtime: (normalizeRuntimeName(input2.runtime) ?? input2.runtime) as RuntimeId,\n    hostedMcpUrl: identity.hosted_mcp_url ?? `${identity.api_url}/mcp`,\n    apiKey: identity.api_key,\n    identityPath: join(directory, 'identity.json'),\n    signerPath,\n    credentialDirectory: directory,\n    signerCommand: { command: prepared.command, args: prepared.args },\n    homeDir,\n    mode: 'hosted',\n    serverName,\n  })\n  messages.push(...configResult.messages)\n  messages.push('Repair complete — restart the runtime, then verify with --doctor.')\n  return { ok: true, messages }\n}\n","import { CONNECTOR_VERSION, type ConnectOptions } from './runtime.js'\nimport { assertValidServerSlug } from './server-names.js'\nimport { REKEY_FINISH_NEEDS_API_KEY } from './rekey-messages.js'\n\nexport interface ParsedCli {\n  options: ConnectOptions\n  help: boolean\n  json: boolean\n  /** #1589: diagnosis mode — no setup token required. */\n  doctor: boolean\n  repair: boolean\n  /** #1681: retire an agent credential directory in place — no token required. */\n  tombstone?: { directory: string; reason?: string; replacedBy?: string }\n  /**\n   * #2169: unwire one agent — tombstone it, then remove its MCP pair and\n   * Hermes dotenv key from every runtime config. No token required; refuses\n   * rather than guess when a bare pair is owned by a different agent.\n   */\n  unwire?: { reason?: string; replacedBy?: string; destroyKeyMaterial?: boolean }\n  /** Optional positional value of --unwire <dir> (else --name / --credentials-dir resolve it). */\n  unwireDir?: string\n  /** #3123: reclaim signer-runtime directories no credential directory references. */\n  pruneSignerRuntimes?: { dryRun: boolean }\n  /**\n   * #1700: replace an agent's signing key on this machine. Two phases, because\n   * the dashboard sits between them — `start` generates the key and prints its\n   * address, `finish` writes the key the owner brings back. No setup token: the\n   * re-key API is owner-authenticated and this connector never calls it.\n   */\n  rekey?: { phase: 'start' | 'finish'; newApiKey?: string }\n}\n\nexport function parseArgs(argv: string[], env: NodeJS.ProcessEnv = process.env): ParsedCli {\n  const options: Partial<ConnectOptions> = {\n    apiBaseUrl: env.HAVEN_API_URL ?? 'http://localhost:3001',\n    connectorVersion: CONNECTOR_VERSION,\n  }\n  let help = false\n  let json = false\n  let doctor = false\n  let repair = false\n  let rekeyPhase: 'start' | 'finish' | undefined\n  let newApiKey: string | undefined\n  let tombstoneDir: string | undefined\n  let tombstoneReason: string | undefined\n  let tombstoneReplacedBy: string | undefined\n  let unwire: { reason?: string; replacedBy?: string; destroyKeyMaterial?: boolean } | undefined\n  let destroyKeyMaterial = false\n  let pruneSignerRuntimes = false\n  let dryRun = false\n  let unwireDir: string | undefined\n  let replace = false\n  let bare = false\n\n  for (let i = 0; i < argv.length; i += 1) {\n    const arg = argv[i]\n    if (arg === '--help' || arg === '-h') {\n      help = true\n    } else if (arg === '--json') {\n      json = true\n    } else if (arg === '--doctor') {\n      doctor = true\n    } else if (arg === '--repair') {\n      repair = true\n    } else if (arg === '--rekey') {\n      rekeyPhase = 'start'\n    } else if (arg === '--rekey-finish') {\n      rekeyPhase = 'finish'\n    } else if (arg === '--api-key') {\n      newApiKey = requireValue(argv, ++i, arg)\n    } else if (arg === '--tombstone') {\n      tombstoneDir = requireValue(argv, ++i, arg)\n    } else if (arg === '--unwire') {\n      unwire = unwire ?? {}\n      const next = argv[i + 1]\n      // Optional positional form --unwire <dir>; a following flag (usually\n      // --name or --credentials-dir) means the directory is resolved later.\n      if (next !== undefined && !next.startsWith('--')) {\n        unwireDir = next\n        i += 1\n      }\n    } else if (arg === '--destroy-key-material') {\n      destroyKeyMaterial = true\n    } else if (arg === '--prune-signer-runtimes') {\n      pruneSignerRuntimes = true\n    } else if (arg === '--dry-run') {\n      dryRun = true\n    } else if (arg === '--reason') {\n      tombstoneReason = requireValue(argv, ++i, arg)\n    } else if (arg === '--replaced-by') {\n      tombstoneReplacedBy = requireValue(argv, ++i, arg)\n    } else if (arg === '--setup' || arg === '--setup-token') {\n      options.setupToken = requireValue(argv, ++i, arg)\n    } else if (arg === '--api' || arg === '--api-url') {\n      options.apiBaseUrl = requireValue(argv, ++i, arg)\n    } else if (arg === '--runtime') {\n      options.runtime = requireValue(argv, ++i, arg)\n    } else if (arg === '--runtime-force') {\n      options.runtimeForce = requireValue(argv, ++i, arg)\n    } else if (arg === '--credentials-dir') {\n      options.credentialsDir = requireValue(argv, ++i, arg)\n    } else if (arg === '--replace') {\n      // #2551: the unattended way to say \"yes, replace the bare pair\" — a\n      // non-interactive setup on a machine already wired to a different agent\n      // refuses without it, instead of overwriting by default (#1569) and\n      // warning afterwards (#1688).\n      replace = true\n    } else if (arg === '--bare') {\n      // #3737 owner decision 2: the bare pair is reached only EXPLICITLY now —\n      // a default setup derives its slug from the agent's display name, so\n      // `--bare` is the human opt-in to the legacy unnamed pair (and the\n      // wiring_collision relay keeps describing it). --replace implies it.\n      bare = true\n    } else if (arg === '--name') {\n      // Validated HERE, before any credential or config write can happen —\n      // the slug is immutable once wired (#1694 owner decision), so a bad one\n      // must die at the argument, not after files exist.\n      options.serverName = requireValue(argv, ++i, arg)\n      assertValidServerSlug(options.serverName)\n    } else if (arg === '--environment-label') {\n      options.environmentLabel = requireValue(argv, ++i, arg)\n    } else if (arg === '--ack-local-tools') {\n      options.ackLocalTools = true\n    } else if (arg === '--ack-signer') {\n      options.ackSigner = true\n      options.ackLocalTools = true\n    } else if (arg === '--local' || arg === '--local-mcp') {\n      options.localMcp = true\n    } else if (arg === '--version') {\n      process.stdout.write(`${CONNECTOR_VERSION}\\n`)\n      process.exit(0)\n    } else {\n      throw new Error(`Unknown option: ${arg}`)\n    }\n  }\n\n  const tombstone = tombstoneDir\n    ? { directory: tombstoneDir, reason: tombstoneReason, replacedBy: tombstoneReplacedBy }\n    : undefined\n  const rekey = rekeyPhase ? { phase: rekeyPhase, newApiKey } : undefined\n\n  if (help) {\n    return { options: options as ConnectOptions, help, json, doctor, repair, tombstone, rekey }\n  }\n\n  if (replace || bare) {\n    // #2551: refuse rather than silently discard (the #1681 finding-2 rule).\n    // --replace answers one question — \"this bare-pair setup collides with an\n    // existing agent; overwrite?\" — which only a --setup run ever asks. --bare\n    // is the same scope (#3737): it chooses a wiring for a new setup and does\n    // nothing for the stored-state subcommands.\n    if (rekeyPhase || tombstoneDir || unwire || doctor || repair || pruneSignerRuntimes) {\n      throw new Error(`${replace ? '--replace' : '--bare'} belongs to a --setup run: it says what to do when the bare haven / haven-signer pair is already wired to another agent.`)\n    }\n    // `--bare --replace` is allowed and redundant: --replace already implies\n    // the bare pair (owner decision 2), so saying both changes nothing.\n    if (bare && options.serverName) {\n      throw new Error(\n        '--bare and --name contradict each other: --bare wires the bare haven / haven-signer pair, ' +\n          '--name installs a named haven-<slug> pair. Pass one of them.',\n      )\n    }\n    if (replace) {\n      if (options.serverName) {\n        throw new Error(\n          '--replace and --name contradict each other: --replace overwrites the bare haven / haven-signer wiring, ' +\n            '--name installs alongside it under its own pair. Pass one of them.',\n        )\n      }\n      options.replaceExistingWiring = true\n    }\n  }\n\n  // #3123 review: these guards sit ABOVE the --rekey early return so the\n  // flags are refused, never silently discarded, on every path (#1681 f2).\n  if (destroyKeyMaterial && !unwire) {\n    throw new Error('--destroy-key-material only applies to --unwire.')\n  }\n  if (destroyKeyMaterial && unwire) unwire = { ...unwire, destroyKeyMaterial: true }\n  if (dryRun && !pruneSignerRuntimes) {\n    throw new Error('--dry-run only applies to --prune-signer-runtimes.')\n  }\n  if (pruneSignerRuntimes) {\n    if (unwire || tombstoneDir || rekeyPhase || doctor || repair) {\n      throw new Error('--prune-signer-runtimes is its own operation; run it alone.')\n    }\n    if (options.setupToken) {\n      throw new Error('--prune-signer-runtimes takes no --setup token; it reads stored state only.')\n    }\n    return { options: options as ConnectOptions, help, json, doctor, repair, tombstone, rekey, unwire, unwireDir, pruneSignerRuntimes: { dryRun } }\n  }\n  if (rekey) {\n    // Re-key reuses STORED credentials, like --doctor: the whole point is that\n    // the agent already exists here, so a setup token is exactly what it does\n    // not need. It refuses the two ways a caller can mean something it cannot\n    // do, rather than silently doing the other one.\n    if (options.setupToken) {\n      throw new Error('--rekey replaces an existing agent\\'s key; it does not take --setup. Drop one of them.')\n    }\n    if (rekey.phase === 'start' && newApiKey !== undefined) {\n      throw new Error(\n        '--api-key belongs to --rekey-finish. --rekey generates the new key here and prints the ' +\n          'address to paste into Haven; the API key does not exist yet.',\n      )\n    }\n    if (rekey.phase === 'finish' && !newApiKey) {\n      throw new Error(REKEY_FINISH_NEEDS_API_KEY)\n    }\n    return { options: options as ConnectOptions, help, json, doctor, repair, tombstone, rekey }\n  }\n\n  if (newApiKey !== undefined) {\n    // Refuse rather than silently discard — the caller believed it did\n    // something (the #1681 finding-2 rule, applied to the new flag).\n    throw new Error('--api-key requires --rekey-finish.')\n  }\n\n  if (!tombstoneDir && !unwire && (tombstoneReason !== undefined || tombstoneReplacedBy !== undefined)) {\n    // Refuse rather than silently discard — the caller believed these did\n    // something. (#1681 review, finding 2)\n    throw new Error('--reason and --replaced-by require --tombstone <dir> or --unwire.')\n  }\n\n  // --reason / --replaced-by ride whichever teardown mode is active.\n  if (unwire && (tombstoneReason !== undefined || tombstoneReplacedBy !== undefined)) {\n    unwire = {\n      ...(tombstoneReason !== undefined ? { reason: tombstoneReason } : {}),\n      ...(tombstoneReplacedBy !== undefined ? { replacedBy: tombstoneReplacedBy } : {}),\n      ...unwire,\n    }\n  }\n\n  if (tombstone) {\n    if (unwire) {\n      throw new Error('--unwire and --tombstone are separate operations; run one per invocation.')\n    }\n    // Retirement reuses STORED state, like --doctor — no token, no runtime.\n    return { options: options as ConnectOptions, help, json, doctor, repair, tombstone, rekey, unwire, unwireDir }\n  }\n\n  if (unwire) {\n    // Unwire reuses STORED state, like --doctor — no token, no runtime.\n    if (options.setupToken) {\n      throw new Error('--unwire removes existing wiring; it does not take --setup. Drop --setup.')\n    }\n    if (!unwireDir && !options.serverName && !options.credentialsDir) {\n      throw new Error('--unwire needs a target: --unwire <dir>, --unwire --name <slug>, or --unwire --credentials-dir <path>.')\n    }\n    return { options: options as ConnectOptions, help, json, doctor, repair, tombstone, rekey, unwire, unwireDir }\n  }\n\n  if (doctor || repair) {\n    // Diagnosis/repair reuse STORED credentials — a setup token is exactly\n    // what they exist to avoid needing.\n    //\n    // #3210: `--runtime` is required for --repair ONLY. --repair rewrites the\n    // user's editor config, so which config it rewrites is stated on the\n    // command line, never inherited from a record on disk. --doctor is\n    // read-only: it passes through with no runtime and the doctor resolves\n    // one from the setup record (`last-connect-outcome.json`, #3120) or\n    // reports the honest \"Runtime is unknown\" failure — a parser refusal\n    // here made that resolution unreachable from the CLI. `.trim()` because\n    // the doctor trims too: `--runtime \"  \"` must not slip past this guard\n    // and then resolve from the record on the write path (#3210 review).\n    if (repair && !options.runtime?.trim()) {\n      throw new Error(\n        '--repair needs --runtime <runtime>: it rewrites that runtime\\'s config, so the runtime is named ' +\n          'explicitly rather than inherited from the setup record. --doctor alone resolves it from the record.',\n      )\n    }\n    // #3799: --ack-local-tools is HONOURED by --repair (it re-consents the\n    // signer the repair installs — owner decision 2026-10-09: explicit flag,\n    // never automatic) and REFUSED with a bare --doctor, which is read-only\n    // and has nothing to acknowledge. The old behaviour silently dropped the\n    // flag, which is exactly the failure mode this refusal replaces.\n    if (options.ackLocalTools && !repair) {\n      throw new Error(\n        '--ack-local-tools does nothing with --doctor alone: the doctor is read-only. Re-consent during a ' +\n          'repair (--repair --ack-local-tools), or token-free with the recorded wrapper: <agent dir>/bin/haven-signer.mjs --ack',\n      )\n    }\n    return { options: options as ConnectOptions, help, json, doctor, repair, tombstone, rekey }\n  }\n\n  if (!options.setupToken) {\n    throw new Error('Missing --setup <hv_setup_...> setup token.')\n  }\n  if (!options.apiBaseUrl) {\n    throw new Error('Missing --api <Haven API URL>.')\n  }\n\n  // #3737: the DEFAULT setup names its pair from the agent's display name, so\n  // adding an agent never targets the bare pair and never has to ask\n  // replace-vs-alongside. Only an explicit --name, --bare or --replace\n  // bypasses the derivation. Deliberately set only on the setup path — the\n  // stored-state subcommands above returned already.\n  if (!options.serverName && !bare && !replace) {\n    options.deriveServerName = true\n  }\n\n  options.apiBaseUrl = options.apiBaseUrl.replace(/\\/+$/, '')\n  return { options: options as ConnectOptions, help, json, doctor, repair, tombstone, rekey }\n}\n\nexport function helpText(): string {\n  return [\n    'Haven Connect Agent 2 local connector',\n    '',\n    'Generates the agent signing key locally, stores it on this machine, and',\n    'sends Haven only the public signing address plus a proof signature.',\n    '',\n    'Usage:',\n    '  npx -y @haven_ai/connect --setup hv_setup_... --api https://api.haven.example --ack-local-tools',\n    '',\n    'Options:',\n    '  --setup <token>            Short-lived setup token from Haven.',\n    '  --api <url>                Haven backend API URL. Defaults to HAVEN_API_URL or http://localhost:3001.',\n    '  --runtime <name>           Agent runtime hint, such as claude-code, codex-cli, codex-desktop, cursor, vscode, claude-desktop, or hermes.',\n    '                             Usually unnecessary: the connector detects the runtime it runs inside, and a detection',\n    '                             that contradicts this hint wins (with a printed notice). When nothing is detected, an',\n    '                             interactive terminal is offered the agent clients installed on this machine; this flag is',\n    '                             how an agent, or a non-interactive run, answers instead. An unknown name is refused, never guessed.',\n    '  --runtime-force <name>     Escape hatch: use exactly this runtime, ignoring environment detection.',\n    '  --credentials-dir <path>   Credential directory fallback. Defaults to ~/.haven/agents.',\n    '  --environment-label <text> Non-sensitive label shown in Haven setup review.',\n    '  --replace                  When this machine is already wired to a different Haven agent on the bare',\n    '                             haven / haven-signer pair, re-point that pair at the new agent and retire the',\n    '                             previous agent directory locally (tombstoned, local key files removed).',\n    '                             Nothing is revoked — use Remove agent… on the Haven agent page. Implies',\n    '                             the bare pair. Without it (or --bare) a non-interactive run REFUSES such a',\n    '                             collision (wiring_collision) and an interactive terminal is asked.',\n    '  --bare                     Wire the bare haven / haven-signer pair. Without --name a setup now names',\n    '                             its pair from the agent\\'s display name (haven-<slug> /',\n    '                             haven-signer-<slug>, de-collided against this machine, ending -dev on a',\n    '                             non-production backend), so adding an agent never has to displace anyone;',\n    '                             --bare is the explicit opt-in to the unnamed pair. --name overrides it.',\n    '  --name <slug>              Wiring slug for a NAMED agent: writes haven-<slug> / haven-signer-<slug>',\n    '                             MCP entries and stores credentials at ~/.haven/agents/<slug>/, so several',\n    '                             agents can run side by side in one runtime. 1-32 lowercase letters, digits,',\n    '                             single hyphens; immutable once wired. Without it the pair is named from the',\n    '                             agent\\'s display name; --bare wires the bare haven / haven-signer pair.',\n    '  --ack-local-tools          Write the local Haven tools acknowledgement: during setup, or (with --repair)',\n    '                             re-acknowledge consent for the signer the repair installs — no setup token.',\n    '                             With a bare --doctor it is refused: --doctor is read-only.',\n    '  --ack-signer               Backward-compatible alias for --ack-local-tools.',\n    '  --local                    Advanced: install the fully-local Haven MCP (no hosted dependency).',\n    '                             Only available for Claude Code and Codex. Default is hosted MCP + local signer.',\n    '  --json                     Emit one versioned, secret-free result object on stdout; progress stays on stderr.',\n    '  --doctor                   Diagnose an existing setup (read-only, no token): config, credentials,',\n    '                             signer runtime, hosted MCP, and a live signer handshake. Exits non-zero only on a failed check; an advisory (!) exits 0.',\n    '                             --runtime is optional: without it the doctor checks the runtime the setup recorded,',\n    '                             and reports a failure (not a pass) when no record names one.',\n    '                             --name <slug> selects the agent directory by its recorded MCP pair.',\n    '  --repair                   Repair, then re-diagnose (implies --doctor): reinstall the pinned signer',\n    '                             runtime, rewrite the wrapper and runtime config from stored credentials.',\n    '                             Hosted topology only (refuses to touch a --local config). No keys, no token.',\n    '                             Requires --runtime <runtime>: it rewrites that config, so the runtime is never inherited.',\n    '                             --name <slug> selects the agent to repair by its recorded pair; --ack-local-tools',\n    '                             re-consents the installed signer (the old token-free path: <agent dir>/bin/haven-signer.mjs --ack).',\n    '  --rekey                    Replace this agent\\'s signing key (no token). Generates a fresh keypair HERE and',\n    '                             prints its public address to paste into the Haven agent page. Nothing changes',\n    '                             until you finish; the agent keeps working on its old key throughout.',\n    '                             Add --name <slug> for a named agent. Refuses a legacy-rail or revoked agent.',\n    '  --rekey-finish             Second half of --rekey: writes the new key and the API key the agent page',\n    '                             showed once, in place at the same path, and rewrites only this agent\\'s MCP',\n    '                             config pair. Server names do not change, so wired hosts need only a restart.',\n    '  --api-key <key>            The new API key, for --rekey-finish.',\n    '  --tombstone <dir>          Retire an agent credential directory in place (no token): replaces its signer',\n    '                             wrapper with a diagnostic that names the retirement in MCP stderr logs, and',\n    '                             writes TOMBSTONE.json. Touches NO key material and revokes nothing.',\n    '  --unwire [<dir>]           Remove one agent\\u2019s wiring from every runtime config it appears in (no token):',\n    '                             tombstone-first, then drops the hosted + signer MCP pair from Hermes YAML, Codex',\n    '                             TOML and the JSON configs (Cursor, VS Code, Insiders, Claude Desktop), plus the',\n    '                             Hermes dotenv API-key line (MCP_HAVEN_API_KEY / MCP_HAVEN_<SLUG>_API_KEY).',\n    '                             Target the directory directly, or add --name <slug> or --credentials-dir.',\n    '                             An UNNAMED pair is only removed when this directory\\u2019s wrapper is the one the',\n    '                             config launches (or its key is the one the Hermes env holds); otherwise the',\n    '                             command refuses rather than unwire a different agent — it never touches a',\n    '                             pair another agent owns. Tears down the target directory: its signer key and',\n    '                             API key are removed locally (record kept via the #2155 tombstone mirror) and',\n    '                             nothing is ever revoked on the backend — that stays an owner action on the',\n    '                             Haven agent page.',\n    '  --destroy-key-material     With --unwire: destroy the signer key + stored API key even when the agent',\n    '                             is still active or cannot be verified (#3123). Local sweep recovery ends.',\n    '  --prune-signer-runtimes    Remove ~/.haven/signer-runtime directories no credential directory references',\n    '                             (version- and override-keyed alike); --dry-run lists them. Exits 1 only on a',\n    '                             removal that failed (#3123).',\n    '  --dry-run                  With --prune-signer-runtimes: report, remove nothing.',\n    '  --reason <text>            Reason recorded in the tombstone (with --tombstone or --unwire).',\n    '  --replaced-by <agent-id>   Successor agent recorded in the tombstone (with --tombstone or --unwire).',\n    '  --help                     Show this help.',\n    '',\n    'The connector never prints the private key and never sends it to Haven. JSON output never includes credential contents or full credential paths.',\n  ].join('\\n')\n}\n\nfunction requireValue(argv: string[], index: number, option: string): string {\n  const value = argv[index]\n  if (!value || value.startsWith('--')) {\n    throw new Error(`Missing value for ${option}.`)\n  }\n  return value\n}\n","export { parseArgs, helpText, type ParsedCli } from './args.js'\nexport {\n  createConnectApiClient,\n  type ConnectApiClient,\n  type RegisterSetupInput,\n  type RegisterSetupResponse,\n  type ResolvedSetup,\n  type ResolveSetupInput,\n  type UpdateInstallStatusInput,\n} from './api.js'\nexport { delegateKeyFromPrivateKey, generateDelegateKey, type LocalDelegateKey } from './key.js'\nexport { redactSecrets, shortAddress } from './redact.js'\nexport {\n  runConnect,\n  completionOutcome,\n  failedConnectOutcome,\n  failureOutcomeFor,\n  CONNECTOR_VERSION,\n  CONNECT_OUTCOME_SCHEMA_VERSION,\n  type ConnectDeps,\n  type ConnectOptions,\n  type ConnectOutcome,\n  type ConnectOutcomeStatus,\n  type ConnectResult,\n} from './runtime.js'\nexport { runCli, type CliIo } from './cli.js'\nexport {\n  installRuntime,\n  runtimeInstallCapabilities,\n  type RuntimeInstallInput,\n  type RuntimeInstallResult,\n} from './runtime-install.js'\nexport {\n  prepareSignerRuntime,\n  type PreparedSignerRuntime,\n  type PrepareSignerRuntimeInput,\n} from './signer-runtime.js'\nexport {\n  normalizeRuntime,\n  resolveRuntimeSelection,\n  runtimeProfile,\n  RUNTIME_FLAG_VALUES,\n  type RuntimeId,\n  type RuntimeProfile,\n  type RuntimeResolutionOptions,\n  type RuntimeSelection,\n} from './runtime-registry.js'\nexport { ConnectError, isConnectError } from './connect-error.js'\nexport {\n  installedClientHint,\n  promptForInstalledClient,\n  resolveRuntimeByInstalledClientPrompt,\n  scanInstalledClients,\n  type InstalledClientCandidate,\n  type InstalledClientHint,\n  type PromptIo,\n  type ScanInstalledClientsOptions,\n} from './installed-clients.js'\nexport {\n  defaultAgentDirectory,\n  resolveAgentDirectoryBySlug,\n  assertDirectoryRecordsSlug,\n  writeCredentialFiles,\n  writeConnectOutcomeRecord,\n  CONNECT_OUTCOME_FILENAME,\n  type ResolveAgentDirectoryOptions,\n  type StoredCredentialPaths,\n  type WriteCredentialInput,\n} from './storage.js'\nexport { MCP_RUNTIME_MANIFEST, mcpPackageSpec, sdkPackageSpec, signerPackageSpec } from './runtime-manifest.js'\n","#!/usr/bin/env node\n\nimport type { DoctorLevel, DoctorReport } from './doctor.js'\nimport { realpathSync } from 'node:fs'\nimport { fileURLToPath, pathToFileURL } from 'node:url'\nimport { helpText, parseArgs } from './args.js'\nimport { failedConnectOutcome, failureOutcomeFor, runConnect } from './runtime.js'\nimport { redactForAutomation, redactSecrets } from './redact.js'\nimport { isConnectError } from './connect-error.js'\n\nexport interface CliIo {\n  stdout: (message: string) => void\n  stderr: (message: string) => void\n}\n\n/**\n * Report a subcommand failure on BOTH channels (#2184).\n *\n * Every subcommand but the main connect run used to write its failure to\n * stderr alone and leave stdout empty. To a `--json` caller parsing stdout\n * that is indistinguishable from a stream it stopped reading — which is\n * exactly how a field `haven-reset` reported \"the tombstone command did not\n * create TOMBSTONE.json\" with no error to show for it (#2175). One helper, so\n * the next subcommand inherits the behaviour instead of re-deciding it.\n *\n * `envelope` carries the branch's own success discriminant inverted\n * (`{ unwired: false }`, `{ rekey: 'failed' }`), so a failure record can never\n * be mistaken for a success payload — this matters most for `--doctor`, whose\n * success output IS a JSON report.\n *\n * `message` rides along ONLY for a connector-authored `ConnectError`, the same\n * gate `failedConnectOutcome` applies. A bare `Error` here is an unguarded\n * failure whose raw text can carry agent ids, local paths, or arbitrary OS\n * detail (`rekey.ts` throws several such); that text reaches stderr, where it\n * always did, and never the machine channel.\n */\nfunction failSubcommand(\n  io: CliIo,\n  json: boolean,\n  err: unknown,\n  envelope: Record<string, unknown>,\n  fallback: { code: string; nextAction: string },\n): number {\n  const message = err instanceof Error ? err.message : String(err)\n  io.stderr(`${redactSecrets(message)}\\n`)\n  if (json) {\n    io.stdout(\n      `${redactSecrets(\n        JSON.stringify({\n          ...envelope,\n          error: {\n            code: isConnectError(err) ? err.code : fallback.code,\n            next_action: isConnectError(err) ? err.nextAction : fallback.nextAction,\n            ...(isConnectError(err) && message ? { message } : {}),\n          },\n        }),\n      )}\\n`,\n    )\n  }\n  return 1\n}\n\n/** #3121: one marker per verdict level — `✓` ok, `!` advisory, `✗` failed. */\nfunction levelMarker(level: DoctorLevel): string {\n  return level === 'ok' ? '✓' : level === 'advisory' ? '!' : '✗'\n}\n\n/** Advisories across the flat list and every wired agent's checks — the same set the rolled-up level reads. */\nfunction advisoryCount(report: DoctorReport): number {\n  // The primary directory's checks ARE the flat list (doctor.ts copies them by\n  // id), so it is excluded here or the single-agent case counts itself twice\n  // (#3145 review, finding 1) — the same set the \"Other agents\" section prints.\n  const others = report.agents\n    .filter((agent) => agent.classification === 'wired' && agent.directory !== report.credentialDirectory)\n    .flatMap((agent) => agent.checks)\n  return [...report.checks, ...others].filter((check) => check.level === 'advisory').length\n}\n\nexport async function runCli(\n  argv: string[],\n  io: CliIo = {\n    stdout: (message) => process.stdout.write(message),\n    stderr: (message) => process.stderr.write(message),\n  },\n): Promise<number> {\n  const wantsJson = argv.includes('--json')\n  let parsed\n  try {\n    parsed = parseArgs(argv)\n  } catch (err) {\n    if (wantsJson) {\n      // #2091: same stderr mirror as the run-failure path below.\n      io.stderr(`${redactForAutomation(err instanceof Error ? err.message : String(err))}\\n`)\n      io.stdout(`${JSON.stringify(failedConnectOutcome(undefined, err))}\\n`)\n    } else {\n      io.stderr(`${redactSecrets(err instanceof Error ? err.message : String(err))}\\n`)\n    }\n    return 1\n  }\n  if (parsed.help) {\n    io.stdout(`${helpText()}\\n`)\n    return 0\n  }\n  if (parsed.tombstone) {\n    // #1681: retire a credential directory in place. Reads the stored\n    // identity for the agent id, replaces the wrapper with a truth-telling\n    // tombstone, touches NO key material, and tells the user what the\n    // tombstone cannot do for them: restart every long-lived host.\n    const { writeAgentTombstone, tombstonesDirForAgentDirectory } = await import('./tombstone.js')\n    const { readFile } = await import('node:fs/promises')\n    const { join } = await import('node:path')\n    try {\n      let agentId = 'unknown'\n      try {\n        const identity = JSON.parse(\n          await readFile(join(parsed.tombstone.directory, 'identity.json'), 'utf8'),\n        ) as { agent_id?: string }\n        agentId = identity.agent_id ?? 'unknown'\n      } catch {\n        // A directory whose identity no longer parses can still be retired —\n        // the tombstone then names it as unknown, which is honest.\n      }\n      const ledgerDir = tombstonesDirForAgentDirectory(parsed.tombstone.directory)\n      const info = await writeAgentTombstone({\n        directory: parsed.tombstone.directory,\n        agentId,\n        reason: parsed.tombstone.reason ?? 'retired by operator via --tombstone',\n        replacedBy: parsed.tombstone.replacedBy,\n        // #3251: the ledger of the root that holds the retired directory —\n        // ~/.haven/agents/<x> → ~/.haven/tombstones, exactly as before; a\n        // directory under any other root → <root>/.tombstones.\n        tombstonesDir: ledgerDir,\n      })\n      if (parsed.json) {\n        io.stdout(`${redactSecrets(JSON.stringify({ tombstoned: true, ...info }))}\\n`)\n      } else {\n        io.stdout(redactSecrets(`Tombstoned agent ${info.agent_id} at ${parsed.tombstone.directory}.\\n`))\n        io.stdout(\n          'Key files were NOT touched and nothing was revoked — on the Haven agent page, use ' +\n            'Remove agent\\u2026 (or Stop budget) if you have not already.\\n',\n        )\n        io.stdout(\n          info.recordPath !== null\n            ? `A surviving tombstone record was mirrored to ${redactSecrets(info.recordPath)}\\n`\n            : // #3259: the directory IS tombstoned; only the surviving copy failed.\n              redactSecrets(\n                `! The surviving tombstone record could NOT be written to ${ledgerDir} (${info.mirrorError}). The in-place ` +\n                  'TOMBSTONE.json stands, but --doctor will not list this retirement once the directory is deleted.\\n',\n              ),\n        )\n        io.stdout(\n          'Restart EVERY long-lived MCP host (gateway, TUI workers, editors): each holds the ' +\n            'wiring snapshot from its own start time, and the tombstone only speaks when a stale ' +\n            'host next probes the old path.' +\n            // #3259 review: never claim a copy that the line above says was not written.\n            (info.recordPath !== null\n              ? ' The mirrored record keeps this retirement observable even after the agent directory itself is deleted.'\n              : '') +\n            '\\n',\n        )\n      }\n      return 0\n    } catch (err) {\n      // #2175 introduced this record; #2184 moved it into `failSubcommand` so\n      // the three sibling subcommands share it rather than each re-deciding.\n      return failSubcommand(io, parsed.json, err, { tombstoned: false }, {\n        code: 'tombstone_failed',\n        nextAction: 'review_the_error_and_retry_with_a_valid_agent_directory',\n      })\n    }\n  }\n  if (parsed.unwire) {\n    // #2169: tombstone-first removal of ONE agent's wiring from every runtime\n    // config it appears in + the Hermes dotenv key. Refuses — never guesses —\n    // when the bare pair is provably another agent's.\n    const { unwireAgent } = await import('./unwire.js')\n    const { tombstonesDirForAgentDirectory } = await import('./tombstone.js')\n    // #3799: --name resolves through the shared pair-record rule — the folder\n    // need not be named after the slug, and a retired directory stays\n    // reachable (unwire must reach a retired agent to release its name).\n    const { resolveAgentDirectoryBySlug } = await import('./storage.js')\n    const { homedir } = await import('node:os')\n    const { join } = await import('node:path')\n    const homeDir = homedir()\n    const root = parsed.options.credentialsDir ?? join(homeDir, '.haven', 'agents')\n    const directory =\n      parsed.unwireDir ??\n      (parsed.options.serverName\n        ? await resolveAgentDirectoryBySlug(parsed.options.serverName, { root, allowRetired: true })\n        : root)\n    const ledgerDir = tombstonesDirForAgentDirectory(directory, homeDir)\n    try {\n      const result = await unwireAgent({\n        directory,\n        slug: parsed.options.serverName,\n        reason: parsed.unwire.reason,\n        replacedBy: parsed.unwire.replacedBy,\n        destroyKeyMaterial: parsed.unwire.destroyKeyMaterial,\n        homeDir,\n        // #3251: the ledger of the root that holds the directory being\n        // retired. Derived from the RESOLVED directory, not from\n        // --credentials-dir: `--unwire --credentials-dir <path>` names the agent\n        // directory itself, not a root. ~/.haven/agents/<slug> →\n        // ~/.haven/tombstones, exactly as before; any other root →\n        // <root>/.tombstones.\n        tombstonesDir: ledgerDir,\n      })\n      const failures = result.runtimes.filter((r) => r.status === 'refused' || r.status === 'unreadable')\n      // #3123: a retained teardown is a refusal too — the wiring is gone, the\n      // key material deliberately is not, and the exit code says so.\n      const retained = result.teardown.status === 'retained'\n      if (parsed.json) {\n        io.stdout(\n          `${redactSecrets(\n            JSON.stringify({\n              unwired: true,\n              agent_id: result.agentId,\n              slug: result.slug ?? null,\n              directory: result.directory,\n              tombstoned: result.tombstoned,\n              // #3259: additive — present only when the surviving ledger record failed.\n              ...(result.mirrorError !== undefined ? { mirror_error: result.mirrorError } : {}),\n              runtimes: result.runtimes.map((r) => ({\n                runtime: r.runtime,\n                label: r.label,\n                status: r.status,\n                ...(r.detail ? { detail: r.detail } : {}),\n              })),\n              // #3122: additive — whether the local server-name binding record was released.\n              binding_released: result.bindingReleased,\n              // #3123: additive — what happened to the key material and why.\n              teardown: {\n                status: result.teardown.status,\n                probe: result.teardown.probe,\n                detail: result.teardown.detail,\n                ...(result.teardown.remedy ? { remedy: result.teardown.remedy } : {}),\n              },\n            }),\n          )}\\n`,\n        )\n      } else {\n        io.stdout(redactSecrets(`Unwired agent ${result.agentId} at ${result.directory}.\\n`))\n        io.stdout(\n          result.tombstoned\n            ? '  · Tombstoned first: any long-lived host still resolving the old wrapper gets the HAVEN-TOMBSTONE diagnosis.\\n'\n            : '  · Directory was already tombstoned.\\n',\n        )\n        if (result.mirrorError !== undefined) {\n          io.stdout(redactSecrets(\n            `  ! Surviving tombstone record: NOT written to ${ledgerDir} (${result.mirrorError}) — the in-place tombstone stands; ` +\n              '--doctor will not list this retirement once the directory is deleted.\\n',\n          ))\n        }\n        for (const r of result.runtimes) {\n          const mark = r.status === 'removed' ? '✓' : r.status === 'clean' ? '–' : '✗'\n          io.stdout(redactSecrets(`  ${mark} ${r.label}: ${r.status}${r.detail ? ` — ${r.detail}` : ''}\\n`))\n        }\n        io.stdout(result.bindingReleased\n          ? '  ✓ MCP server-name binding: released (the name is free for the next setup).\\n'\n          : '  – MCP server-name binding: none recorded for this directory.\\n')\n        const t = result.teardown\n        io.stdout(redactSecrets(`  ${t.status === 'retained' ? '✗' : t.status === 'forced' ? '!' : '✓'} Key material: ${t.status} (probe: ${t.probe}) — ${t.detail}\\n`))\n        if (t.remedy) io.stdout(redactSecrets(`    ↳ ${t.remedy}\\n`))\n        io.stdout(\n          failures.length > 0\n            ? '  Some entries were NOT removed (✗ above). Re-run `--unwire` after resolving each refusal —\\n' +\n              '  it is idempotent.\\n'\n            : retained\n              ? '  The wiring is gone; the key material is not (✗ above). `--doctor` will keep reporting this directory\\n' +\n                '  as `superseded` until the key is revoked or destroyed — that is the honest state.\\n'\n              : '  Verify: `--doctor --runtime <runtime>` per host should report this agent as `retired` with a\\n' +\n                '  clean runtime-config check.\\n',\n        )\n        io.stdout(\n          'Restart EVERY long-lived MCP host (gateway, TUI workers, editors): each holds the wiring snapshot\\n' +\n            'from its own start time. ' +\n            (retained\n              ? 'This directory\\u2019s local key material was KEPT (see above); the tombstone\\n'\n              : 'This directory\\u2019s local key material was removed and the tombstone\\n') +\n            'record + #2155 mirror survive — but nothing was REVOKED on the backend. If you have not\\n' +\n            'already, use Remove agent\\u2026 on the Haven agent page to end its budgets on-chain and stop it spending.\\n',\n        )\n      }\n      return failures.length > 0 || retained ? 1 : 0\n    } catch (err) {\n      return failSubcommand(io, parsed.json, err, { unwired: false }, {\n        code: 'unwire_failed',\n        nextAction: 'review_the_error_and_rerun_unwire_which_is_idempotent',\n      })\n    }\n  }\n  if (parsed.pruneSignerRuntimes) {\n    // #3123: reclaim signer-runtime directories no credential directory\n    // references. Its own flag — not part of --repair (which installs) and\n    // never automatic. Exit 1 only when a removal FAILED.\n    const { pruneSignerRuntimes } = await import('./prune-runtimes.js')\n    try {\n      const report = await pruneSignerRuntimes(\n        { dryRun: parsed.pruneSignerRuntimes.dryRun },\n        { credentialsDir: parsed.options.credentialsDir },\n      )\n      if (parsed.json) {\n        io.stdout(`${redactSecrets(JSON.stringify({\n          pruned: true,\n          version: report.version,\n          dry_run: report.dryRun,\n          level: report.level,\n          root: report.root,\n          removed: report.removed,\n          reclaimed_bytes: report.reclaimedBytes,\n          entries: report.entries.map((e) => ({\n            key: e.key, kind: e.kind, bytes: e.bytes, action: e.action, level: e.level,\n            referenced_by: e.referencedBy, detail: e.detail,\n          })),\n        }))}\\n`)\n      } else {\n        io.stdout(`Signer runtimes under ${report.root}${report.dryRun ? ' (dry run — nothing removed)' : ''}:\\n`)\n        if (report.entries.length === 0) io.stdout('  (none)\\n')\n        for (const e of report.entries) {\n          const mark = e.level === 'failed' ? '✗' : e.level === 'advisory' ? '!' : e.action === 'removed' ? '✓' : '•'\n          // A kept directory is never sized (#3151 review): say so instead of printing a false 0 MB.\n          const size = e.bytes > 0 ? `${Math.round(e.bytes / 1024 / 1024)} MB` : e.action === 'kept' ? 'not sized' : '0 MB'\n          io.stdout(redactSecrets(`  ${mark} ${e.key} (${e.kind}, ${size}): ${e.detail}\\n`))\n        }\n        io.stdout(\n          report.dryRun\n            ? `Would remove ${report.entries.filter((e) => e.action === 'would_remove').length} director(y/ies); re-run without --dry-run to reclaim.\\n`\n            : `Removed ${report.removed} director(y/ies), reclaimed ${Math.round(report.reclaimedBytes / 1024 / 1024)} MB.\\n`,\n        )\n      }\n      return report.level === 'failed' ? 1 : 0\n    } catch (err) {\n      return failSubcommand(io, parsed.json, err, { pruned: false }, {\n        code: 'prune_failed',\n        nextAction: 'review_the_error_and_rerun_prune_which_is_idempotent',\n      })\n    }\n  }\n  if (parsed.rekey) {\n    // #1700: replace an agent's signing key on this machine. Two phases with\n    // the owner's dashboard between them — this connector never calls the\n    // re-key API, which is owner-authenticated by design.\n    const { startRekey, finishRekey } = await import('./rekey.js')\n    const { restartGuidance } = await import('./rekey-restart.js')\n    const common = {\n      serverName: parsed.options.serverName,\n      credentialsDir: parsed.options.credentialsDir,\n      runtime: parsed.options.runtime,\n    }\n    try {\n      if (parsed.rekey.phase === 'start') {\n        const result = await startRekey(common)\n        if (parsed.json) {\n          // The address is public; the private half never appears here or\n          // anywhere else this process writes to a stream.\n          io.stdout(\n            `${redactSecrets(\n              JSON.stringify({\n                rekey: 'started',\n                agent_id: result.agentId,\n                new_delegate_address: result.newDelegateAddress,\n                expires_at: result.expiresAt,\n              }),\n            )}\\n`,\n          )\n        } else {\n          for (const line of result.messages) io.stdout(redactSecrets(`${line}\\n`))\n        }\n        return 0\n      }\n\n      const result = await finishRekey({ ...common, newApiKey: parsed.rekey.newApiKey })\n      const restart = restartGuidance(parsed.options.runtime)\n      if (parsed.json) {\n        io.stdout(\n          `${redactSecrets(\n            JSON.stringify({\n              rekey: 'finished',\n              agent_id: result.agentId,\n              new_delegate_address: result.newDelegateAddress,\n              mcp_servers: result.serverNames,\n              restart_commands: restart.commands,\n            }),\n          )}\\n`,\n        )\n      } else {\n        for (const line of result.messages) io.stdout(redactSecrets(`${line}\\n`))\n        io.stdout('\\n')\n        for (const line of restart.lines) io.stdout(redactSecrets(`${line}\\n`))\n      }\n      return 0\n    } catch (err) {\n      return failSubcommand(io, parsed.json, err, { rekey: 'failed' }, {\n        code: 'rekey_failed',\n        nextAction: 'review_the_error_and_rerun_the_rekey_phase',\n      })\n    }\n  }\n  if (parsed.doctor || parsed.repair) {\n    const { runDoctor, runRepair } = await import('./doctor.js')\n    // '' is the doctor's \"no flag given\" input: it resolves the runtime from\n    // the setup record, else reports it unknown (#3120). Reachable for\n    // --doctor since #3210; --repair never gets here without a flag (args.ts).\n    const runtime = parsed.options.runtime ?? ''\n    const credentialsDir = parsed.options.credentialsDir\n    // #3799: --name selects the agent directory by its recorded pair;\n    // --ack-local-tools on a repair re-consents the installed signer\n    // (explicit flag only — never automatic).\n    const serverName = parsed.options.serverName\n    const ackLocalTools = parsed.options.ackLocalTools === true\n    try {\n      if (parsed.repair) {\n        const repair = await runRepair({ runtime, credentialsDir, serverName, ackLocalTools })\n        for (const message of repair.messages) io.stderr(`${redactSecrets(message)}\\n`)\n        if (!repair.ok) return 1\n      }\n      const report = await runDoctor({ runtime, credentialsDir, serverName })\n      // Defensively redacted like every other output path — the report is\n      // secret-free by construction, but signerCapabilities is untrusted\n      // process output and belts are cheap (#1589 review).\n      if (parsed.json) {\n        io.stdout(`${redactSecrets(JSON.stringify(report))}\\n`)\n      } else {\n        // #3121: three markers for three levels. `!` is an advisory — worth\n        // reading, nothing broken, and it never reaches the exit code.\n        for (const check of report.checks) {\n          io.stdout(redactSecrets(`${levelMarker(check.level)} ${check.label}: ${check.detail}\\n`))\n          if (check.repair) io.stdout(redactSecrets(`    ↳ repair: ${check.repair}\\n`))\n        }\n        // #1697: the other agents on this machine. The flat list above\n        // describes ONE agent; multi-agent means the rest still have to be\n        // accounted for, by name and by verdict, never silently dropped.\n        const otherAgents = report.agents.filter((agent) => agent.directory !== report.credentialDirectory)\n        // #3830: when the superseded check is an advisory, the connector could\n        // not tell wired from superseded, so the row must not assert it either.\n        // The `--json` classification is unchanged (#3121 decision 5).\n        const wiringUnverifiable = report.checks.some(\n          (check) => check.id === 'superseded_agents' && check.level === 'advisory',\n        )\n        if (otherAgents.length > 0) {\n          io.stdout('\\nOther agents on this machine:\\n')\n          for (const agent of otherAgents) {\n            const name = agent.slug ? `${agent.slug} (${agent.agentId ?? 'unknown'})` : agent.agentId ?? 'unknown'\n            const failed = agent.checks.filter((check) => check.level === 'failed')\n            const advised = agent.checks.filter((check) => check.level === 'advisory')\n            const verdict = agent.classification === 'wired'\n              ? failed.length > 0\n                ? `wired, ${failed.length} check(s) FAILED`\n                : advised.length > 0\n                  ? `wired, ${advised.length} advisory finding(s)`\n                  : 'wired, all checks passed'\n              // #1915: `parked` is the one classification whose bare name says\n              // nothing a reader can act on — it is not a broken agent, it is\n              // a directory with no agent in it and a private key still in it.\n              // Spell that out here; the path and state are on the parked\n              // re-key check above.\n              : agent.classification === 'parked'\n                ? 'parked re-key only — no identity.json in this directory, but key material is still there'\n                : agent.classification === 'superseded' && wiringUnverifiable\n                  ? 'not verified as wired — no config the connector can read names it'\n                  : agent.classification\n            io.stdout(redactSecrets(`  ${failed.length > 0 ? '✗' : advised.length > 0 ? '!' : '•'} ${name}: ${verdict}\\n`))\n            for (const check of [...failed, ...advised]) {\n              io.stdout(redactSecrets(`      ${levelMarker(check.level)} ${check.label}: ${check.detail}\\n`))\n              if (check.repair) io.stdout(redactSecrets(`        ↳ repair: ${check.repair}\\n`))\n            }\n          }\n        }\n        io.stdout(\n          report.level === 'failed'\n            ? 'One or more checks FAILED — see repairs above.\\n'\n            : report.level === 'advisory'\n              ? `No failures. ${advisoryCount(report)} advisory finding(s) — see the ! line(s) above.\\n`\n              : 'All checks passed.\\n',\n        )\n      }\n      // #3121: the exit code counts only real failures. `report.ok` is the\n      // same predicate (`level !== 'failed'`), kept for --json consumers.\n      return report.level === 'failed' ? 1 : 0\n    } catch (err) {\n      return failSubcommand(io, parsed.json, err, { doctor: 'failed' }, {\n        code: 'doctor_failed',\n        nextAction: 'review_the_error_and_rerun_doctor',\n      })\n    }\n  }\n  try {\n    // --json is the automation contract: emit the outcome promptly instead of\n    // blocking up to the approval-wait bound (#1377 D).\n    const result = await runConnect(\n      {\n        ...parsed.options,\n        // #1377 D / #2484: leave prose runs UNSPECIFIED (undefined) so\n        // runConnect's stdout-TTY narration gate decides whether there is a\n        // watching human to narrate to — an agent invoking prose as a tool\n        // call has none and must not sit opaque in the wait. --json stays an\n        // explicit false (skip, emit promptly).\n        waitForApproval: parsed.json ? false : undefined,\n        // #1719: only a human-facing run may be asked which installed client to\n        // configure. --json is the automation contract — it must fail with a\n        // machine-readable code, never block on stdin. runConnect additionally\n        // requires a real TTY before it prompts.\n        interactive: !parsed.json,\n        // #2528: reported to the backend at register, so the funnel can tell a\n        // machine-readable run from a narrated one. Read from the SAME\n        // `parsed.json` the three flags above use, rather than inferred later\n        // from `waitForApproval` — that flag is already false for a prose run\n        // with no TTY (#2484), so inferring would mislabel real prose runs.\n        runMode: parsed.json ? 'json' : 'prose',\n      },\n      {\n        log: (message) => (parsed.json ? io.stderr : io.stdout)(`${message}\\n`),\n        redactPaths: parsed.json,\n      },\n    )\n    if (parsed.json) io.stdout(`${JSON.stringify(result.outcome)}\\n`)\n    return 0\n  } catch (err) {\n    if (parsed.json) {\n      // #2091: mirror the redacted message to stderr as well — stdout stays\n      // pure JSON for the automation contract, but the prose channel must\n      // never be silently discarded (progress lines already go to stderr in\n      // --json mode; the failure that ends the run belongs there too). Same\n      // redaction bar as those progress lines and the JSON message field:\n      // redactForAutomation, which also masks credential-file paths.\n      io.stderr(`${redactForAutomation(err instanceof Error ? err.message : String(err))}\\n`)\n      // #2173: the run's OWN record when it built one, so the object printed\n      // here is byte-identical to the one persisted to `last-connect-outcome.json`.\n      // Re-deriving it from the raw `--runtime` hint would report the hint,\n      // not the runtime detection actually resolved (#1672).\n      io.stdout(`${JSON.stringify(failureOutcomeFor(parsed.options.runtime, err))}\\n`)\n    } else {\n      io.stderr(`${redactSecrets(err instanceof Error ? err.message : String(err))}\\n`)\n    }\n    return 1\n  }\n}\n\nasync function main(): Promise<void> {\n  const exitCode = await runCli(process.argv.slice(2))\n  if (exitCode !== 0) process.exitCode = exitCode\n}\n\n/**\n * npm executes package bins through a `node_modules/.bin` symlink. Node keeps\n * that symlink in `process.argv[1]`, whereas `import.meta.url` identifies the\n * real module path. Resolve both sides before comparing so a published\n * `haven-connect` bin starts, while an ordinary `runCli` import remains inert.\n */\nexport function isCliEntrypoint(\n  argvPath: string | undefined = process.argv[1],\n  moduleUrl: string = import.meta.url,\n): boolean {\n  if (!argvPath) return false\n  try {\n    return realpathSync(argvPath) === realpathSync(fileURLToPath(moduleUrl))\n  } catch {\n    // Keep the direct-file behavior when a loader provides an unresolvable\n    // path. A missing path cannot be a safe reason to run imported CLI code.\n    return pathToFileURL(argvPath).href === moduleUrl\n  }\n}\n\nif (isCliEntrypoint()) void main()\n"]}