@haven_ai/connect 0.4.0-alpha.0 → 0.6.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -24,10 +24,11 @@ var __export = (target, all) => {
24
24
  };
25
25
 
26
26
  // src/api.ts
27
- function createConnectApiClient(baseUrl, fetchImpl = fetch) {
27
+ function createConnectApiClient(baseUrl, fetchImpl = fetch, clientIdentity) {
28
28
  const root = baseUrl.replace(/\/+$/, "");
29
+ const send = (url, init) => request(fetchImpl, url, clientIdentity ? { ...init, headers: { ...init.headers, "X-Haven-Client": clientIdentity } } : init);
29
30
  return {
30
- resolveSetup: (input) => request(fetchImpl, `${root}/agent-connection-setups/resolve`, {
31
+ resolveSetup: (input) => send(`${root}/agent-connection-setups/resolve`, {
31
32
  method: "POST",
32
33
  body: JSON.stringify({
33
34
  setup_token: input.setupToken,
@@ -35,7 +36,7 @@ function createConnectApiClient(baseUrl, fetchImpl = fetch) {
35
36
  runtime: input.runtime
36
37
  })
37
38
  }),
38
- registerSetup: (input) => request(fetchImpl, `${root}/agent-connection-setups/register`, {
39
+ registerSetup: (input) => send(`${root}/agent-connection-setups/register`, {
39
40
  method: "POST",
40
41
  body: JSON.stringify({
41
42
  setup_token: input.setupToken,
@@ -55,16 +56,16 @@ function createConnectApiClient(baseUrl, fetchImpl = fetch) {
55
56
  }
56
57
  })
57
58
  }),
58
- getAgentIdentity: (apiKey) => request(fetchImpl, `${root}/machine-payments/agent`, {
59
+ getAgentIdentity: (apiKey) => send(`${root}/machine-payments/agent`, {
59
60
  method: "GET",
60
61
  headers: { Authorization: `Bearer ${apiKey}` }
61
62
  }),
62
- getConnectorStatus: (setupId, apiKey) => request(fetchImpl, `${root}/agent-connection-setups/${encodeURIComponent(setupId)}/connector-status`, {
63
+ getConnectorStatus: (setupId, apiKey) => send(`${root}/agent-connection-setups/${encodeURIComponent(setupId)}/connector-status`, {
63
64
  method: "GET",
64
65
  headers: { Authorization: `Bearer ${apiKey}` }
65
66
  }),
66
67
  updateInstallStatus: async (setupId, apiKey, input) => {
67
- await request(fetchImpl, `${root}/agent-connection-setups/${encodeURIComponent(setupId)}/install-status`, {
68
+ await send(`${root}/agent-connection-setups/${encodeURIComponent(setupId)}/install-status`, {
68
69
  method: "POST",
69
70
  headers: { Authorization: `Bearer ${apiKey}` },
70
71
  body: JSON.stringify({
@@ -611,9 +612,9 @@ var init_runtime_manifest = __esm({
611
612
  mcpPackage: "@haven_ai/mcp",
612
613
  mcpVersion: MCP_VERSION,
613
614
  sdkPackage: "@haven_ai/sdk",
614
- sdkVersion: "0.4.0-alpha.0",
615
+ sdkVersion: "0.6.0-alpha.0",
615
616
  signerPackage: "@haven_ai/signer",
616
- signerVersion: "0.4.0-alpha.0",
617
+ signerVersion: "0.6.0-alpha.0",
617
618
  // Sourced from the SDK, never a literal (#1161). This field read '20.0.0'
618
619
  // while every package's `engines` said `>=24` and the docs said `>=24.0.0`,
619
620
  // so the guard that was supposed to enforce the floor waved Node v23 through
@@ -1582,7 +1583,7 @@ async function probeLocalSignerCredential(signerPath) {
1582
1583
  }
1583
1584
  }
1584
1585
  async function probeLocalMcpTools(command, args, requiredTools, timeoutMs = 1e4) {
1585
- return new Promise((resolve10) => {
1586
+ return new Promise((resolve11) => {
1586
1587
  const child = spawn(command, args, { stdio: ["pipe", "pipe", "ignore"] });
1587
1588
  let stdout = "";
1588
1589
  let settled = false;
@@ -1594,7 +1595,7 @@ async function probeLocalMcpTools(command, args, requiredTools, timeoutMs = 1e4)
1594
1595
  settled = true;
1595
1596
  clearTimeout(timeout);
1596
1597
  child.kill();
1597
- resolve10(result);
1598
+ resolve11(result);
1598
1599
  };
1599
1600
  const timeout = setTimeout(() => finish({ status: "timeout" }), timeoutMs);
1600
1601
  child.on("error", () => finish({ status: "process_error" }));
@@ -2988,20 +2989,211 @@ var init_runtime_install = __esm({
2988
2989
  execFileAsync3 = promisify(execFile);
2989
2990
  }
2990
2991
  });
2992
+ function installedClientTargets(homeDir = homedir(), cwd = process.cwd(), env = process.env) {
2993
+ const targets = [
2994
+ {
2995
+ runtime: "claude-code",
2996
+ label: "Claude Code",
2997
+ // Claude Code is configured through its own CLI (`claude mcp add-json`),
2998
+ // not by writing a file this module owns — so its evidence is the
2999
+ // client directory, never a config path.
3000
+ configPath: null,
3001
+ markers: [join(homeDir, ".claude"), join(homeDir, ".claude.json")]
3002
+ },
3003
+ {
3004
+ runtime: "codex-cli",
3005
+ // Both Codex surfaces write the same ~/.codex/config.toml, so they are
3006
+ // ONE candidate. Splitting them would ask the user to answer a question
3007
+ // whose answers are the same write.
3008
+ label: "Codex (CLI or Desktop)",
3009
+ configPath: runtimeConfigPathFor("codex-cli", homeDir),
3010
+ markers: [join(homeDir, ".codex")]
3011
+ },
3012
+ {
3013
+ runtime: "cursor",
3014
+ label: "Cursor",
3015
+ configPath: runtimeConfigPathFor("cursor", homeDir),
3016
+ markers: [join(homeDir, ".cursor")]
3017
+ },
3018
+ {
3019
+ runtime: "vscode",
3020
+ label: "VS Code",
3021
+ configPath: runtimeConfigPathFor("vscode", homeDir),
3022
+ markers: [resolve(cwd, ".vscode")]
3023
+ },
3024
+ {
3025
+ runtime: "vscode-insiders",
3026
+ label: "VS Code Insiders",
3027
+ configPath: runtimeConfigPathFor("vscode-insiders", homeDir),
3028
+ markers: []
3029
+ },
3030
+ {
3031
+ runtime: "claude-desktop",
3032
+ label: "Claude Desktop",
3033
+ configPath: runtimeConfigPathFor("claude-desktop", homeDir),
3034
+ markers: []
3035
+ },
3036
+ {
3037
+ runtime: "hermes",
3038
+ label: "Hermes Agent",
3039
+ configPath: runtimeConfigPathFor("hermes", homeDir),
3040
+ markers: [env.HERMES_HOME ?? join(homeDir, ".hermes")]
3041
+ }
3042
+ ];
3043
+ return targets.filter((target) => runtimeProfile(target.runtime, {}).canWriteRuntimeConfig);
3044
+ }
3045
+ async function scanInstalledClients(options = {}) {
3046
+ const exists = options.exists ?? pathExists;
3047
+ const targets = installedClientTargets(options.homeDir, options.cwd, options.env ?? process.env);
3048
+ const found = [];
3049
+ for (const target of targets) {
3050
+ if (target.configPath && await exists(target.configPath)) {
3051
+ found.push({
3052
+ runtime: target.runtime,
3053
+ label: target.label,
3054
+ detail: `MCP config found at ${target.configPath}`,
3055
+ configPath: target.configPath,
3056
+ evidence: "config-file"
3057
+ });
3058
+ continue;
3059
+ }
3060
+ for (const marker of target.markers) {
3061
+ if (!await exists(marker)) continue;
3062
+ found.push({
3063
+ runtime: target.runtime,
3064
+ label: target.label,
3065
+ detail: `installed (${marker})`,
3066
+ configPath: target.configPath,
3067
+ evidence: "client-directory"
3068
+ });
3069
+ break;
3070
+ }
3071
+ }
3072
+ return found.sort((a, b) => {
3073
+ if (a.evidence !== b.evidence) return a.evidence === "config-file" ? -1 : 1;
3074
+ return SCAN_ORDER.indexOf(a.runtime) - SCAN_ORDER.indexOf(b.runtime);
3075
+ });
3076
+ }
3077
+ function installedClientHint(candidates) {
3078
+ const installedClients = candidates.map((candidate) => candidate.runtime);
3079
+ if (candidates.length === 1) {
3080
+ return { installedClients, suggestedRuntime: candidates[0].runtime };
3081
+ }
3082
+ const configured = candidates.filter((candidate) => candidate.evidence === "config-file");
3083
+ return configured.length === 1 ? { installedClients, suggestedRuntime: configured[0].runtime } : { installedClients };
3084
+ }
3085
+ async function promptForInstalledClient(candidates, io = defaultPromptIo()) {
3086
+ if (candidates.length === 0) throw noInstalledClientsError();
3087
+ io.write("Haven could not detect which agent runtime this is.\n");
3088
+ io.write("These agent clients are installed on this machine:\n");
3089
+ candidates.forEach((candidate, index) => {
3090
+ io.write(` ${index + 1}) ${candidate.label} \u2014 ${candidate.detail}
3091
+ `);
3092
+ });
3093
+ 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");
3094
+ for (let attempt = 0; attempt < MAX_PROMPT_ATTEMPTS; attempt += 1) {
3095
+ const answer = await io.question(`Which one? [1-${candidates.length}] (default 1 \u2014 ${candidates[0].label}): `);
3096
+ if (answer === null) throw promptAbortedError("the prompt was cancelled");
3097
+ const trimmed = answer.trim();
3098
+ if (trimmed === "") return candidates[0].runtime;
3099
+ const picked = Number.parseInt(trimmed, 10);
3100
+ if (Number.isInteger(picked) && picked >= 1 && picked <= candidates.length) {
3101
+ return candidates[picked - 1].runtime;
3102
+ }
3103
+ io.write(`"${trimmed}" is not one of 1-${candidates.length}.
3104
+ `);
3105
+ }
3106
+ throw promptAbortedError(`no valid choice after ${MAX_PROMPT_ATTEMPTS} attempts`);
3107
+ }
3108
+ async function resolveRuntimeByInstalledClientPrompt(options = {}) {
3109
+ const candidates = await scanInstalledClients(options);
3110
+ if (candidates.length === 0) throw noInstalledClientsError();
3111
+ return promptForInstalledClient(candidates, options.io ?? defaultPromptIo());
3112
+ }
3113
+ function noInstalledClientsError() {
3114
+ return new ConnectError(
3115
+ "runtime_no_installed_clients",
3116
+ "Could not determine the agent runtime: nothing was detected in this environment, and no agent client Haven can configure is installed on this machine. Re-run with --runtime <name> naming the client you want configured, or --runtime other to store credentials and finish the MCP setup by hand.",
3117
+ "rerun_connect_with_explicit_runtime"
3118
+ );
3119
+ }
3120
+ function promptAbortedError(reason) {
3121
+ return new ConnectError(
3122
+ "runtime_prompt_aborted",
3123
+ `Runtime not chosen (${reason}). Nothing was written: no agent was created, no credentials were stored, and the Haven setup token is still unused. Run the connector command again, or pass --runtime <name> to skip the prompt.`,
3124
+ "rerun_connect_and_choose_a_runtime"
3125
+ );
3126
+ }
3127
+ async function pathExists(path) {
3128
+ try {
3129
+ await access(path);
3130
+ return true;
3131
+ } catch {
3132
+ return false;
3133
+ }
3134
+ }
3135
+ function defaultPromptIo() {
3136
+ return {
3137
+ write: (text) => process.stdout.write(text),
3138
+ question: (query) => new Promise((resolvePromise) => {
3139
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
3140
+ let settled = false;
3141
+ const settle = (value) => {
3142
+ if (settled) return;
3143
+ settled = true;
3144
+ rl.close();
3145
+ resolvePromise(value);
3146
+ };
3147
+ rl.once("SIGINT", () => settle(null));
3148
+ rl.once("close", () => settle(null));
3149
+ rl.question(query, (answer) => settle(answer));
3150
+ })
3151
+ };
3152
+ }
3153
+ var SCAN_ORDER, MAX_PROMPT_ATTEMPTS;
3154
+ var init_installed_clients = __esm({
3155
+ "src/installed-clients.ts"() {
3156
+ init_connect_error();
3157
+ init_config_writers();
3158
+ init_runtime_registry();
3159
+ SCAN_ORDER = [
3160
+ "claude-code",
3161
+ "codex-cli",
3162
+ "cursor",
3163
+ "vscode",
3164
+ "vscode-insiders",
3165
+ "claude-desktop",
3166
+ "hermes"
3167
+ ];
3168
+ MAX_PROMPT_ATTEMPTS = 3;
3169
+ }
3170
+ });
2991
3171
 
2992
3172
  // src/tombstone.ts
2993
3173
  var tombstone_exports = {};
2994
3174
  __export(tombstone_exports, {
3175
+ ROOT_TOMBSTONES_DIRNAME: () => ROOT_TOMBSTONES_DIRNAME,
2995
3176
  TOMBSTONE_FILENAME: () => TOMBSTONE_FILENAME,
2996
3177
  TOMBSTONE_MARKER: () => TOMBSTONE_MARKER,
2997
3178
  defaultTombstonesDir: () => defaultTombstonesDir,
2998
3179
  readAgentTombstone: () => readAgentTombstone,
2999
3180
  readTombstoneRecords: () => readTombstoneRecords,
3181
+ tombstonesDirForAgentDirectory: () => tombstonesDirForAgentDirectory,
3182
+ tombstonesDirForCredentialRoot: () => tombstonesDirForCredentialRoot,
3000
3183
  writeAgentTombstone: () => writeAgentTombstone
3001
3184
  });
3002
3185
  function defaultTombstonesDir(baseDir) {
3003
3186
  return join(baseDir ?? join(homedir(), ".haven"), "tombstones");
3004
3187
  }
3188
+ function tombstonesDirForCredentialRoot(credentialRoot, homeDir = homedir()) {
3189
+ if (!credentialRoot) return defaultTombstonesDir(join(homeDir, ".haven"));
3190
+ const root = resolve(credentialRoot);
3191
+ if (root === resolve(homeDir, ".haven", "agents")) return defaultTombstonesDir(join(homeDir, ".haven"));
3192
+ return join(root, ROOT_TOMBSTONES_DIRNAME);
3193
+ }
3194
+ function tombstonesDirForAgentDirectory(directory, homeDir = homedir()) {
3195
+ return tombstonesDirForCredentialRoot(dirname(resolve(directory)), homeDir);
3196
+ }
3005
3197
  async function readTombstoneRecords(tombstonesDir) {
3006
3198
  const root = tombstonesDir ?? defaultTombstonesDir();
3007
3199
  let entries = [];
@@ -3078,9 +3270,14 @@ async function writeAgentTombstone(input) {
3078
3270
  const record = JSON.stringify(info, null, 2) + "\n";
3079
3271
  await writeFile(join(input.directory, TOMBSTONE_FILENAME), record, "utf8");
3080
3272
  const root = input.tombstonesDir ?? defaultTombstonesDir();
3081
- await mkdir(root, { recursive: true, mode: 448 });
3082
3273
  const recordPath = join(root, `${info.agent_id}.json`);
3083
- await writeFile(recordPath, record, { mode: MIRROR_MODE });
3274
+ try {
3275
+ await mkdir(root, { recursive: true, mode: 448 });
3276
+ await writeFile(recordPath, record, { mode: MIRROR_MODE });
3277
+ } catch (err) {
3278
+ const code = err?.code;
3279
+ return { ...info, recordPath: null, mirrorError: typeof code === "string" && /^E[A-Z]+$/.test(code) ? code : "mirror_write_failed" };
3280
+ }
3084
3281
  return { ...info, recordPath };
3085
3282
  }
3086
3283
  async function readAgentTombstone(directory) {
@@ -3092,53 +3289,165 @@ async function readAgentTombstone(directory) {
3092
3289
  return null;
3093
3290
  }
3094
3291
  }
3095
- var TOMBSTONE_FILENAME, MIRROR_MODE, TOMBSTONE_MARKER;
3292
+ var TOMBSTONE_FILENAME, ROOT_TOMBSTONES_DIRNAME, MIRROR_MODE, TOMBSTONE_MARKER;
3096
3293
  var init_tombstone = __esm({
3097
3294
  "src/tombstone.ts"() {
3098
3295
  init_redact();
3099
3296
  init_connect_error();
3100
3297
  TOMBSTONE_FILENAME = "TOMBSTONE.json";
3298
+ ROOT_TOMBSTONES_DIRNAME = ".tombstones";
3101
3299
  MIRROR_MODE = 384;
3102
3300
  TOMBSTONE_MARKER = "HAVEN-TOMBSTONE";
3103
3301
  }
3104
3302
  });
3105
-
3106
- // src/unwire.ts
3107
- var unwire_exports = {};
3108
- __export(unwire_exports, {
3109
- readIdentityFile: () => readIdentityFile,
3110
- teardownLocalKeyMaterial: () => teardownLocalKeyMaterial,
3111
- tombstoneDirectoryIfAbsent: () => tombstoneDirectoryIfAbsent,
3112
- unwireAgent: () => unwireAgent
3113
- });
3114
- function identityAt(directory) {
3115
- return readFile(join(directory, "identity.json"), "utf8").then((raw) => JSON.parse(raw)).catch(() => null);
3116
- }
3117
- function removeForModel(text, model, names, path) {
3118
- switch (model.kind) {
3119
- case "yaml":
3120
- return removeHermesYaml(text, names, path);
3121
- case "toml":
3122
- return removeCodexToml(text, names);
3123
- case "json":
3124
- return removeJsonMcpConfig(text, model.serverRoot ?? "mcpServers", names, path);
3303
+ async function detectWiringCollision(input) {
3304
+ const root = defaultCredentialRoot(input.credentialsDir);
3305
+ let entries = [];
3306
+ try {
3307
+ entries = await readdir(root);
3308
+ } catch {
3309
+ return null;
3310
+ }
3311
+ const superseded = [];
3312
+ const taken = /* @__PURE__ */ new Set();
3313
+ for (const entry of entries) {
3314
+ const directory = join(root, entry);
3315
+ let identityRaw;
3316
+ try {
3317
+ identityRaw = await readFile(join(directory, "identity.json"), "utf8");
3318
+ } catch {
3319
+ continue;
3320
+ }
3321
+ taken.add(entry);
3322
+ let identity;
3323
+ try {
3324
+ identity = JSON.parse(identityRaw);
3325
+ } catch {
3326
+ identity = void 0;
3327
+ }
3328
+ if (!identity?.api_key) continue;
3329
+ if (await pathExists2(join(directory, TOMBSTONE_FILENAME))) continue;
3330
+ const sidecar = await readRuntimeSidecar(directory);
3331
+ if (sidecar?.server_name) continue;
3332
+ superseded.push({ directory, agentId: identity.agent_id ?? entry });
3125
3333
  }
3334
+ if (superseded.length === 0) return null;
3335
+ return {
3336
+ superseded,
3337
+ suggestedServerName: proposeServerSlug(input.agentName, taken)
3338
+ };
3126
3339
  }
3127
- function envLineValue(envText, envKey) {
3128
- const line = envText.split(/\r?\n/).find((candidate) => new RegExp(`^\\s*(?:export[ \\t]+)?${envKey}[ \\t]*=`).test(candidate));
3129
- if (!line) return void 0;
3130
- let value = line.slice(line.indexOf("=") + 1);
3131
- value = value.trim();
3132
- if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
3133
- value = value.slice(1, -1);
3340
+ function proposeServerSlug(agentName, taken) {
3341
+ let base = agentName.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").replace(/-{2,}/g, "-").slice(0, 32).replace(/-+$/g, "");
3342
+ if (!slugIsValid(base)) base = "agent";
3343
+ if (!taken.has(base)) return base;
3344
+ for (let n = 2; n < 1e3; n += 1) {
3345
+ const suffix = `-${n}`;
3346
+ const candidate = `${base.slice(0, 32 - suffix.length).replace(/-+$/g, "")}${suffix}`;
3347
+ if (slugIsValid(candidate) && !taken.has(candidate)) return candidate;
3134
3348
  }
3135
- return value;
3349
+ throw new Error(`Could not propose an unused server name for ${JSON.stringify(agentName)}.`);
3136
3350
  }
3137
- async function readOptionalText(path) {
3351
+ function slugIsValid(slug) {
3138
3352
  try {
3139
- return await readFile(path, "utf8");
3353
+ assertValidServerSlug(slug);
3354
+ return true;
3140
3355
  } catch {
3141
- return null;
3356
+ return false;
3357
+ }
3358
+ }
3359
+ async function promptWiringCollisionResolution(collision, agentName, io) {
3360
+ const ids = collision.superseded.map((entry) => entry.agentId).join(", ");
3361
+ io.write(`This machine is already wired to a Haven agent with a live key: ${ids}.
3362
+ `);
3363
+ io.write(`Setting up "${agentName}" on the bare haven / haven-signer pair would replace that wiring.
3364
+ `);
3365
+ io.write(" r) replace \u2014 re-point haven / haven-signer at the new agent and retire the previous directory locally\n");
3366
+ io.write(" (tombstoned, local key files removed; you still revoke it on the Haven agent page)\n");
3367
+ io.write(` a) alongside \u2014 install as a named agent (suggested: ${collision.suggestedServerName}) with its own
3368
+ `);
3369
+ io.write(` haven-<name> / haven-signer-<name> pair, leaving the current wiring untouched
3370
+ `);
3371
+ io.write(" q) quit \u2014 nothing is written and the setup token stays unused\n");
3372
+ for (let attempt = 0; attempt < MAX_PROMPT_ATTEMPTS2; attempt += 1) {
3373
+ const answer = await io.question("Replace, install alongside, or quit? [r/a/q]: ");
3374
+ if (answer === null) return { action: "abort" };
3375
+ const trimmed = answer.trim().toLowerCase();
3376
+ if (trimmed === "r" || trimmed === "replace") return { action: "replace" };
3377
+ if (trimmed === "q" || trimmed === "quit") return { action: "abort" };
3378
+ if (trimmed === "a" || trimmed === "alongside") {
3379
+ const typed = await io.question(`Server name [${collision.suggestedServerName}]: `);
3380
+ if (typed === null) return { action: "abort" };
3381
+ const serverName = typed.trim() === "" ? collision.suggestedServerName : typed.trim();
3382
+ try {
3383
+ assertValidServerSlug(serverName);
3384
+ } catch (err) {
3385
+ io.write(`${err instanceof Error ? err.message : String(err)}
3386
+ `);
3387
+ continue;
3388
+ }
3389
+ return { action: "alongside", serverName };
3390
+ }
3391
+ io.write(`"${trimmed}" is not one of r, a, q.
3392
+ `);
3393
+ }
3394
+ return { action: "abort" };
3395
+ }
3396
+ async function pathExists2(path) {
3397
+ try {
3398
+ await stat(path);
3399
+ return true;
3400
+ } catch {
3401
+ return false;
3402
+ }
3403
+ }
3404
+ var MAX_PROMPT_ATTEMPTS2;
3405
+ var init_wiring_collision = __esm({
3406
+ "src/wiring-collision.ts"() {
3407
+ init_server_names();
3408
+ init_signer_runtime();
3409
+ init_storage();
3410
+ init_tombstone();
3411
+ MAX_PROMPT_ATTEMPTS2 = 3;
3412
+ }
3413
+ });
3414
+
3415
+ // src/unwire.ts
3416
+ var unwire_exports = {};
3417
+ __export(unwire_exports, {
3418
+ readIdentityFile: () => readIdentityFile,
3419
+ teardownLocalKeyMaterial: () => teardownLocalKeyMaterial,
3420
+ tombstoneDirectoryIfAbsent: () => tombstoneDirectoryIfAbsent,
3421
+ unwireAgent: () => unwireAgent
3422
+ });
3423
+ function identityAt(directory) {
3424
+ return readFile(join(directory, "identity.json"), "utf8").then((raw) => JSON.parse(raw)).catch(() => null);
3425
+ }
3426
+ function removeForModel(text, model, names, path) {
3427
+ switch (model.kind) {
3428
+ case "yaml":
3429
+ return removeHermesYaml(text, names, path);
3430
+ case "toml":
3431
+ return removeCodexToml(text, names);
3432
+ case "json":
3433
+ return removeJsonMcpConfig(text, model.serverRoot ?? "mcpServers", names, path);
3434
+ }
3435
+ }
3436
+ function envLineValue(envText, envKey) {
3437
+ const line = envText.split(/\r?\n/).find((candidate) => new RegExp(`^\\s*(?:export[ \\t]+)?${envKey}[ \\t]*=`).test(candidate));
3438
+ if (!line) return void 0;
3439
+ let value = line.slice(line.indexOf("=") + 1);
3440
+ value = value.trim();
3441
+ if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
3442
+ value = value.slice(1, -1);
3443
+ }
3444
+ return value;
3445
+ }
3446
+ async function readOptionalText(path) {
3447
+ try {
3448
+ return await readFile(path, "utf8");
3449
+ } catch {
3450
+ return null;
3142
3451
  }
3143
3452
  }
3144
3453
  async function unwireAgent(input) {
@@ -3148,7 +3457,7 @@ async function unwireAgent(input) {
3148
3457
  const slug = input.slug ?? sidecar?.server_name;
3149
3458
  const names = serverNamesFor(slug);
3150
3459
  const runtimes = [];
3151
- const tombstoned = await tombstoneDirectoryIfAbsent({
3460
+ const { written: tombstoned, mirrorError } = await tombstoneDirectoryIfAbsent({
3152
3461
  directory: input.directory,
3153
3462
  agentId,
3154
3463
  reason: input.reason ?? "unwired via --unwire",
@@ -3242,7 +3551,16 @@ async function unwireAgent(input) {
3242
3551
  const bindingReleased = await clearMcpServerBinding(input.directory);
3243
3552
  const teardown = await decideTeardown(identity, input);
3244
3553
  if (teardown.status !== "retained") await teardownLocalKeyMaterial(input.directory, identity);
3245
- return { directory: input.directory, agentId, slug, tombstoned, runtimes, teardown, bindingReleased };
3554
+ return {
3555
+ directory: input.directory,
3556
+ agentId,
3557
+ slug,
3558
+ tombstoned,
3559
+ runtimes,
3560
+ teardown,
3561
+ bindingReleased,
3562
+ ...mirrorError === void 0 ? {} : { mirrorError }
3563
+ };
3246
3564
  }
3247
3565
  async function decideTeardown(identity, input) {
3248
3566
  const ended = "Local recovery of a stranded delegate balance ends with it: the sweep-recovery routes accept only this agent's API key and delegate signature, and neither exists on this machine any more.";
@@ -3287,9 +3605,9 @@ async function decideTeardown(identity, input) {
3287
3605
  }
3288
3606
  }
3289
3607
  async function tombstoneDirectoryIfAbsent(input) {
3290
- if (await readOptionalText(join(input.directory, TOMBSTONE_FILENAME)) !== null) return false;
3291
- await writeAgentTombstone(input);
3292
- return true;
3608
+ if (await readOptionalText(join(input.directory, TOMBSTONE_FILENAME)) !== null) return { written: false };
3609
+ const { mirrorError } = await writeAgentTombstone(input);
3610
+ return mirrorError === void 0 ? { written: true } : { written: true, mirrorError };
3293
3611
  }
3294
3612
  async function teardownLocalKeyMaterial(directory, identity) {
3295
3613
  await Promise.all([
@@ -3325,2270 +3643,2016 @@ var init_unwire = __esm({
3325
3643
  DESTROY_FLAG = "--destroy-key-material";
3326
3644
  }
3327
3645
  });
3328
-
3329
- // src/rekey-messages.ts
3330
- var REKEY_FINISH_NEEDS_API_KEY;
3331
- var init_rekey_messages = __esm({
3332
- "src/rekey-messages.ts"() {
3333
- REKEY_FINISH_NEEDS_API_KEY = "--rekey-finish needs --api-key <key> \u2014 the one the Haven agent page showed once.";
3646
+ function failureOutcomeFor(runtimeHint, error) {
3647
+ if (error !== null && typeof error === "object") {
3648
+ const recorded = failureOutcomesByError.get(error);
3649
+ if (recorded) return recorded;
3334
3650
  }
3335
- });
3336
-
3337
- // src/prune-runtimes.ts
3338
- var prune_runtimes_exports = {};
3339
- __export(prune_runtimes_exports, {
3340
- normalizeRuntimePath: () => normalizeRuntimePath,
3341
- pruneSignerRuntimes: () => pruneSignerRuntimes,
3342
- referencedRuntimeDirectories: () => referencedRuntimeDirectories,
3343
- rollUpPruneLevel: () => rollUpPruneLevel,
3344
- signerRuntimeRoot: () => signerRuntimeRoot
3345
- });
3346
- function signerRuntimeRoot(homeDir) {
3347
- return join(homeDir, ".haven", "signer-runtime");
3348
- }
3349
- function classifyKey(key) {
3350
- if (key.startsWith("override-")) return "override";
3351
- if (key === MCP_RUNTIME_MANIFEST.signerVersion || /^\d+\.\d+\.\d+/.test(key)) return "version";
3352
- return "unknown";
3651
+ return failedConnectOutcome(runtimeHint, error);
3353
3652
  }
3354
- async function directoryBytes(directory) {
3355
- let total = 0;
3356
- const walk = async (dir) => {
3357
- let entries = [];
3358
- try {
3359
- entries = await readdir(dir, { withFileTypes: true });
3360
- } catch {
3361
- return;
3362
- }
3363
- for (const entry of entries) {
3364
- const path = join(dir, entry.name);
3365
- if (entry.isDirectory()) await walk(path);
3366
- else if (entry.isFile()) {
3367
- try {
3368
- total += (await stat(path)).size;
3369
- } catch {
3370
- }
3371
- }
3372
- }
3373
- };
3374
- await walk(directory);
3375
- return total;
3653
+ async function runConnect(options, deps = {}) {
3654
+ const trace = {};
3655
+ try {
3656
+ return await executeConnect(options, deps, trace);
3657
+ } catch (err) {
3658
+ const outcome = failedConnectOutcome(trace.runtime ?? options.runtime, err);
3659
+ if (err !== null && typeof err === "object") failureOutcomesByError.set(err, outcome);
3660
+ if (trace.directory) await recordConnectOutcome(deps, trace.directory, outcome);
3661
+ throw err;
3662
+ }
3376
3663
  }
3377
- async function normalizeRuntimePath(path) {
3378
- const resolved = resolve(path).replace(/[\\/]+$/, "");
3664
+ async function recordConnectOutcome(deps, directory, outcome) {
3379
3665
  try {
3380
- return await realpath(resolved);
3666
+ return await (deps.writeOutcomeRecord ?? writeConnectOutcomeRecord)(directory, outcome);
3381
3667
  } catch {
3382
- return resolved;
3668
+ return void 0;
3383
3669
  }
3384
3670
  }
3385
- function escapeRegExp(text) {
3386
- return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3387
- }
3388
- async function referencedRuntimeDirectories(homeDir, credentialsDir) {
3389
- const roots = /* @__PURE__ */ new Set([join(homeDir, ".haven", "agents")]);
3390
- if (credentialsDir) roots.add(dirname(resolve(credentialsDir)));
3391
- const referenced = /* @__PURE__ */ new Map();
3392
- const runtimeRoot = await normalizeRuntimePath(signerRuntimeRoot(homeDir));
3393
- const rootSpellings = [.../* @__PURE__ */ new Set([resolve(signerRuntimeRoot(homeDir)), runtimeRoot])];
3394
- const wrapperRe = new RegExp(`(?:${rootSpellings.map(escapeRegExp).join("|")})[\\/]+([^\\/'"\\s]+)`, "g");
3395
- const add = async (runtimeDirectory, by) => {
3396
- const key = await normalizeRuntimePath(runtimeDirectory);
3397
- const list = referenced.get(key) ?? [];
3398
- if (!list.includes(by)) list.push(by);
3399
- referenced.set(key, list);
3400
- };
3401
- for (const root of roots) {
3402
- let entries = [];
3403
- try {
3404
- entries = await readdir(root);
3405
- } catch {
3406
- continue;
3407
- }
3408
- for (const entry of entries) {
3409
- const directory = join(root, entry);
3410
- try {
3411
- const sidecar = JSON.parse(await readFile(join(directory, "signer-runtime.json"), "utf8"));
3412
- if (typeof sidecar.runtime_directory === "string" && sidecar.runtime_directory.length > 0) {
3413
- await add(sidecar.runtime_directory, directory);
3414
- }
3415
- } catch {
3416
- }
3417
- try {
3418
- const wrapper = await readFile(join(directory, "bin", "haven-signer.mjs"), "utf8");
3419
- for (const match of wrapper.matchAll(wrapperRe)) await add(join(runtimeRoot, match[1]), directory);
3420
- } catch {
3421
- }
3671
+ async function executeConnect(options, deps, trace) {
3672
+ assertSupportedNodeVersion(deps.nodeVersion, MCP_RUNTIME_MANIFEST.minimumNodeVersion);
3673
+ const connectorVersion = options.connectorVersion ?? CONNECTOR_VERSION;
3674
+ const api = deps.api ?? createConnectApiClient(options.apiBaseUrl, void 0, CONNECTOR_CLIENT_IDENTITY);
3675
+ const log = secureLogger(
3676
+ deps.log ?? ((message) => process.stdout.write(`${message}
3677
+ `)),
3678
+ deps.redactPaths === true
3679
+ );
3680
+ const writeCredentials = deps.writeCredentials ?? writeCredentialFiles;
3681
+ const preflightStorage = deps.preflightStorage ?? preflightCredentialStorage;
3682
+ const runRuntimeInstall = deps.installRuntime ?? installRuntime;
3683
+ const generateKey = deps.generateKey ?? generateDelegateKey;
3684
+ const generateLocalApiKey = deps.generateApiKey ?? generateAgentApiKey;
3685
+ const selection = await resolveRuntimeSelection(options.runtime, options.runtimeForce, {
3686
+ env: deps.env ?? process.env,
3687
+ selfReported: options.runtimeSelfReport,
3688
+ promptForRuntime: runtimeSelectionPrompt(options, deps)
3689
+ });
3690
+ if (!selection.runtime) {
3691
+ const hint = await installedClientHintFor(deps);
3692
+ throw new ConnectError(
3693
+ "runtime_undetermined",
3694
+ `Could not determine the agent runtime: nothing was detected in this environment and no --runtime was given. If you are an AI agent running this command: re-run it once, unchanged except for adding --runtime <name>, naming the harness you are running in \u2014 one of: ${RUNTIME_FLAG_VALUES} (the aliases cowork, codex and openclaw are accepted too). Do not guess: if your harness is not one of those, use --runtime other, which stores the credentials and prints the manual MCP steps. ` + installedClientProse(hint) + "Nothing was written and the Haven setup token is still unused.",
3695
+ "rerun_connect_with_explicit_runtime",
3696
+ // #2091: the values must ride structurally too. The backend's setup
3697
+ // prompt permits a retry only with "one of the values that refusal
3698
+ // lists" — and --json discards prose, so a prose-only list deadlocked
3699
+ // every automation run in an undetected runtime (Codex in the field:
3700
+ // npx needs network, Codex runs network commands unsandboxed, and the
3701
+ // unsandboxed path carries none of the CODEX_* detection vars).
3702
+ //
3703
+ // #2174: the list alone still leaves the retry a nine-value guess. The
3704
+ // scan below narrows it to what is actually on this machine — as a
3705
+ // HINT. It does not select, and this stays a refusal: see
3706
+ // `installedClientHint`.
3707
+ { allowedRuntimes: RUNTIME_FLAG_VALUE_LIST, ...hint }
3708
+ );
3709
+ }
3710
+ const runtime = selection.runtime;
3711
+ trace.runtime = runtime;
3712
+ const installCapabilities = runtimeInstallCapabilities(runtime);
3713
+ if (options.localMcp) {
3714
+ if (!supportsLocalMcp(runtime)) {
3715
+ throw new Error(
3716
+ `--local (fully-local Haven MCP) is only available for Claude Code and Codex. The detected runtime is ${runtimeProfile(runtime).label}. Re-run without --local to use the default hosted MCP + local signer setup.`
3717
+ );
3422
3718
  }
3423
3719
  }
3424
- return referenced;
3425
- }
3426
- function rollUpPruneLevel(entries) {
3427
- if (entries.some((e) => e.level === "failed")) return "failed";
3428
- if (entries.some((e) => e.level === "advisory")) return "advisory";
3429
- return "ok";
3430
- }
3431
- async function pruneSignerRuntimes(input, deps = {}) {
3432
- const homeDir = deps.homeDir ?? homedir();
3433
- const root = signerRuntimeRoot(homeDir);
3434
- const measure = input.measure ?? true;
3435
- const referenced = await referencedRuntimeDirectories(homeDir, deps.credentialsDir);
3436
- const pin = await normalizeRuntimePath(join(root, MCP_RUNTIME_MANIFEST.signerVersion));
3437
- const remove = deps.rm ?? (async (directory) => rm(directory, { recursive: true, force: false }));
3438
- const entries = [];
3439
- let keys = [];
3440
- try {
3441
- keys = (await readdir(root, { withFileTypes: true })).filter((d) => d.isDirectory()).map((d) => d.name).sort();
3442
- } catch {
3443
- return { version: 1, root, dryRun: input.dryRun, entries, removed: 0, reclaimedBytes: 0, level: "ok" };
3720
+ if (selection.overrodeHint) {
3721
+ log(`runtime: ${runtime} (detected; ignoring the ${selection.overrodeHint} hint \u2014 pass --runtime-force ${selection.overrodeHint} to override)`);
3444
3722
  }
3445
- let removed = 0;
3446
- let reclaimedBytes = 0;
3447
- for (const key of keys) {
3448
- const directory = join(root, key);
3449
- const normalized = await normalizeRuntimePath(directory);
3450
- const referencedBy = referenced.get(normalized) ?? [];
3451
- const kind = classifyKey(key);
3452
- if (referencedBy.length > 0 || normalized === pin) {
3453
- entries.push({
3454
- directory,
3455
- key,
3456
- kind,
3457
- bytes: 0,
3458
- referencedBy,
3459
- action: "kept",
3460
- level: "ok",
3461
- detail: referencedBy.length > 0 ? `kept \u2014 named by ${referencedBy.length} credential director${referencedBy.length === 1 ? "y" : "ies"} (sidecar or wrapper)` : "kept \u2014 the connector's current pinned version (what --repair installs)"
3462
- });
3463
- continue;
3464
- }
3465
- const bytes = measure ? await directoryBytes(directory) : 0;
3466
- if (input.dryRun) {
3467
- entries.push({
3468
- directory,
3469
- key,
3470
- kind,
3471
- bytes,
3472
- referencedBy,
3473
- action: "would_remove",
3474
- level: "advisory",
3475
- detail: `would remove \u2014 no credential directory names it (${kind}-keyed)`
3476
- });
3477
- continue;
3478
- }
3479
- try {
3480
- await remove(directory);
3481
- removed += 1;
3482
- reclaimedBytes += bytes;
3483
- entries.push({ directory, key, kind, bytes, referencedBy, action: "removed", level: "ok", detail: `removed \u2014 no credential directory named it (${kind}-keyed)` });
3484
- } catch (err) {
3485
- entries.push({
3486
- directory,
3487
- key,
3488
- kind,
3489
- bytes,
3490
- referencedBy,
3491
- action: "failed",
3492
- level: "failed",
3493
- detail: `removal failed: ${err instanceof Error ? err.message : String(err)} \u2014 a signer process may still hold it open; stop it and re-run`
3494
- });
3495
- }
3723
+ if (selection.discardedHint) {
3724
+ log(`runtime: ${runtime} (detected; "${selection.discardedHint}" is not a runtime Haven knows \u2014 valid values: ${RUNTIME_FLAG_VALUES})`);
3496
3725
  }
3497
- return { version: 1, root, dryRun: input.dryRun, entries, removed, reclaimedBytes, level: rollUpPruneLevel(entries) };
3498
- }
3499
- var init_prune_runtimes = __esm({
3500
- "src/prune-runtimes.ts"() {
3501
- init_runtime_manifest();
3726
+ if (selection.source === "prompted") {
3727
+ log(`runtime: ${runtime} (chosen at the prompt \u2014 nothing was detected in this environment)`);
3502
3728
  }
3503
- });
3504
-
3505
- // src/rekey.ts
3506
- var rekey_exports = {};
3507
- __export(rekey_exports, {
3508
- finishRekey: () => finishRekey,
3509
- startRekey: () => startRekey
3510
- });
3511
- async function startRekey(options, deps = {}) {
3512
- const now = deps.now ?? (() => Date.now());
3513
- const stored = await readStoredCredentials(
3514
- options.serverName,
3515
- options.agentId,
3516
- options.credentialsDir
3517
- );
3518
- const api = (deps.createApi ?? ((url) => createConnectApiClient(url)))(stored.apiUrl);
3519
- const identity = await probeIdentity(api, stored.apiKey, "current");
3520
- assertRekeyable(identity, stored);
3521
- const key = (deps.generateKey ?? generateDelegateKey)();
3522
- const startedAt = new Date(now()).toISOString();
3523
- const expiresAt = new Date(now() + REKEY_PENDING_TTL_MS).toISOString();
3524
- await writeRekeyPending(stored.directory, {
3525
- agent_id: stored.agentId,
3526
- new_delegate_address: key.address,
3527
- new_delegate_key: key.privateKey,
3528
- started_at: startedAt,
3529
- expires_at: expiresAt
3530
- });
3531
- const finishCommand = [
3532
- connectorRerunCommand("--rekey-finish"),
3533
- options.serverName ? `--name ${options.serverName}` : void 0,
3534
- "--api-key <the key the dashboard showed you>",
3535
- options.runtime ? `--runtime ${options.runtime}` : "--runtime <your runtime>"
3536
- ].filter(Boolean).join(" ");
3537
- return {
3538
- started: true,
3539
- agentId: stored.agentId,
3540
- directory: stored.directory,
3541
- newDelegateAddress: key.address,
3542
- expiresAt,
3543
- messages: [
3544
- `New signing key generated on this machine for agent ${identity.name || stored.agentId}.`,
3545
- "",
3546
- ` New signing address: ${key.address}`,
3547
- "",
3548
- "The private half stays here \u2014 Haven never receives it, and there is no way to move it",
3549
- "between machines. That is what keeps the account non-custodial.",
3550
- "",
3551
- 'Next, on the Haven agent page: choose "Replace signing key" and paste that address.',
3552
- "When it finishes it shows a new API key ONCE. Come back here and run:",
3553
- "",
3554
- ` ${finishCommand}`,
3555
- "",
3556
- `Nothing has changed yet \u2014 the agent keeps working on its old key until you finish.`,
3557
- `This pending re-key expires ${expiresAt}.`
3558
- ]
3559
- };
3560
- }
3561
- async function finishRekey(options, deps = {}) {
3562
- const now = deps.now ?? (() => Date.now());
3563
- if (!options.newApiKey) {
3564
- throw new Error(REKEY_FINISH_NEEDS_API_KEY);
3729
+ log("Warming up your connection to Haven\u2026");
3730
+ let setup;
3731
+ try {
3732
+ setup = await api.resolveSetup({
3733
+ setupToken: options.setupToken,
3734
+ connectorVersion,
3735
+ runtime
3736
+ });
3737
+ } catch (err) {
3738
+ throw deadSetupTokenError(err) ?? err;
3565
3739
  }
3566
- const stored = await readStoredCredentials(
3567
- options.serverName,
3568
- options.agentId,
3569
- options.credentialsDir
3570
- );
3571
- const pending = await readRekeyPending(stored.directory, now());
3572
- if (pending.agent_id !== stored.agentId) {
3573
- throw new Error(
3574
- `The pending re-key at ${stored.directory} belongs to agent ${pending.agent_id}, but that directory now holds ${stored.agentId}. Refusing to write a key into the wrong agent.`
3575
- );
3740
+ assertSetupChallengeIsUsable(setup.challenge.expires_at);
3741
+ printSetupSummary(setup, log);
3742
+ await preflightStorage({ baseDir: options.credentialsDir, warn: log });
3743
+ if (options.serverName) {
3744
+ assertValidServerSlug(options.serverName);
3745
+ await assertServerSlugAvailable(options.serverName, options.credentialsDir);
3576
3746
  }
3577
- const api = (deps.createApi ?? ((url) => createConnectApiClient(url)))(stored.apiUrl);
3578
- const identity = await probeIdentity(api, options.newApiKey, "new");
3579
- if (identity.id !== stored.agentId) {
3580
- throw new Error(
3581
- `That API key belongs to agent ${identity.id}, not ${stored.agentId}. Nothing was changed.`
3747
+ log("Checked local credential storage \u2014 all clear.");
3748
+ let serverName = options.serverName;
3749
+ let replacing;
3750
+ if (!serverName) {
3751
+ const collision = await detectWiringCollision({
3752
+ credentialsDir: options.credentialsDir,
3753
+ agentName: setup.agent.name
3754
+ });
3755
+ if (collision) {
3756
+ const resolution = await resolveWiringCollision(collision, setup.agent.name, options, deps);
3757
+ if (resolution.action === "replace") {
3758
+ replacing = collision;
3759
+ log(
3760
+ `Replacing the existing haven / haven-signer wiring (previous agent(s): ${supersededIds(collision)}). The previous directory is retired locally once the new wiring is written; nothing is revoked.`
3761
+ );
3762
+ } else {
3763
+ serverName = resolution.serverName;
3764
+ assertValidServerSlug(serverName);
3765
+ await assertServerSlugAvailable(serverName, options.credentialsDir);
3766
+ log(`Installing alongside the existing wiring as a named agent: ${serverNamesFor(serverName).hosted} / ${serverNamesFor(serverName).signer}.`);
3767
+ }
3768
+ }
3769
+ }
3770
+ const existingAgents = await listExistingKeyedAgents(options.credentialsDir);
3771
+ if (existingAgents.length > 0) {
3772
+ log("");
3773
+ log(
3774
+ `Heads-up (before anything is written to this machine): it already carries ${existingAgents.length} agent director${existingAgents.length === 1 ? "y" : "ies"} with stored keys \u2014 ` + existingAgents.map((a) => `${a.agentId}${a.accountAddress ? ` (spends from ${shortAddress(a.accountAddress)})` : ""}`).join(", ") + ". This setup creates a NEW agent alongside them and revokes nothing."
3582
3775
  );
3583
3776
  }
3584
- const onChain = (identity.delegate_address ?? "").toLowerCase();
3585
- const expected = pending.new_delegate_address.toLowerCase();
3586
- if (onChain !== expected) {
3587
- throw new Error(
3588
- `Haven says this agent's signing address is ${identity.delegate_address ?? "unset"}, but this machine generated ${pending.new_delegate_address}. Nothing was changed. Either the re-key on the agent page used a different address, or it has not finished yet.`
3777
+ const hostedNameForRun = serverNamesFor(serverName).hosted;
3778
+ let reboundFrom;
3779
+ const holders = (await listMcpServerBindings(options.credentialsDir)).filter(({ binding }) => binding.server_name === hostedNameForRun).sort((a, b) => a.binding.bound_at < b.binding.bound_at ? 1 : a.binding.bound_at > b.binding.bound_at ? -1 : 0);
3780
+ const newest = holders[0];
3781
+ if (newest) {
3782
+ const { binding, directory } = newest;
3783
+ const backendChanged = withoutUserinfo(binding.api_url) !== withoutUserinfo(options.apiBaseUrl);
3784
+ const previousApiUrl = withoutUserinfo(binding.api_url);
3785
+ reboundFrom = { server_name: binding.server_name, agent_id: binding.agent_id, api_url: previousApiUrl, bound_at: binding.bound_at, backend_changed: backendChanged };
3786
+ const beingReplaced = replacing?.superseded.some((entry) => entry.directory === directory) ?? false;
3787
+ log(
3788
+ `Heads-up: the MCP server name '${binding.server_name}' was bound to agent ${binding.agent_id} on ${previousApiUrl} 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` : ""}). ` + (beingReplaced ? `This run replaces that wiring, as you chose, with a new agent on ${withoutUserinfo(options.apiBaseUrl)}` : `This run rebinds it to a new agent on ${withoutUserinfo(options.apiBaseUrl)}`) + (backendChanged ? " \u2014 a DIFFERENT backend: any saved session, script or document naming this MCP server now resolves to a different backend and agent." : ".")
3589
3789
  );
3590
3790
  }
3591
- await rewriteCredentialFiles({
3791
+ const localKey = generateKey();
3792
+ const localApiKey = generateLocalApiKey();
3793
+ log("Minting a fresh signing key and API key \u2014 both stay on this machine.");
3794
+ const proofSignature = await localKey.signChallenge(setup.challenge.message);
3795
+ log("Introducing your agent to Haven\u2026");
3796
+ let registration;
3797
+ try {
3798
+ registration = await api.registerSetup({
3799
+ setupToken: options.setupToken,
3800
+ connectorVersion,
3801
+ runtime,
3802
+ challengeId: setup.challenge.id,
3803
+ delegateAddress: localKey.address,
3804
+ proofSignature,
3805
+ apiKeyHash: hashAgentApiKey(localApiKey),
3806
+ apiKeyPrefix: agentApiKeyPrefix(localApiKey),
3807
+ // #1878: report the pair we are ACTUALLY wiring, bare pair included, so
3808
+ // the dashboard can name it. Derived here rather than sent as the raw
3809
+ // slug — `serverNamesFor` is the one place the naming rule lives, and
3810
+ // the hosted name is what a user pastes into an MCP config.
3811
+ mcpServerName: serverNamesFor(serverName).hosted,
3812
+ // #2528: 'prose' is the default because it is what a caller who says
3813
+ // nothing is doing — the library entry point is not a --json run.
3814
+ runMode: options.runMode ?? "prose",
3815
+ connectorContext: {
3816
+ environment_label: options.environmentLabel ?? "Local workspace",
3817
+ config_target: installCapabilities.canWriteRuntimeConfig ? "agent runtime MCP config" : "local credential files"
3818
+ },
3819
+ installCapabilities
3820
+ });
3821
+ } catch (err) {
3822
+ const dead = deadSetupTokenError(err);
3823
+ if (dead) throw dead;
3824
+ if (isExpiredSetupChallenge(err)) {
3825
+ throw new Error(
3826
+ "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."
3827
+ );
3828
+ }
3829
+ throw err;
3830
+ }
3831
+ log(`Registered signing address with Haven: ${shortAddress(registration.delegate_address)}.`);
3832
+ log("Tucking your credentials away safely on disk\u2026");
3833
+ const credentialPaths = await writeCredentials({
3592
3834
  baseDir: options.credentialsDir,
3593
- agentId: stored.agentId,
3594
- serverName: options.serverName,
3595
- apiKey: options.newApiKey,
3596
- delegateKey: pending.new_delegate_key,
3597
- delegateAddress: pending.new_delegate_address,
3598
- // The stored value (already new-name-first, from the credential-FILE
3599
- // permanent fallback) wins; the hosted identity's `account_address` is a
3600
- // LIVE server read, which as of #2914 emits only that name.
3601
- accountAddress: stored.accountAddress ?? identity.account_address ?? void 0,
3602
- chainId: stored.chainId ?? identity.chain_id ?? void 0,
3603
- network: stored.network,
3604
- agentBudget: stored.agentBudget,
3605
- apiUrl: stored.apiUrl,
3606
- hostedMcpUrl: stored.hostedMcpUrl,
3607
- x402BindingSigner: stored.x402BindingSigner,
3608
- warn: deps.log
3835
+ agentId: registration.agent_id,
3836
+ serverName,
3837
+ apiKey: localApiKey,
3838
+ delegateKey: localKey.privateKey,
3839
+ delegateAddress: localKey.address,
3840
+ accountAddress: setup.haven_wallet.address,
3841
+ chainId: setup.haven_wallet.chain_id,
3842
+ network: setup.haven_wallet.network,
3843
+ agentBudget: setup.agent_budget.map((budget) => ({
3844
+ token_symbol: budget.token_symbol,
3845
+ allowance_amount: budget.allowance_amount,
3846
+ reset_period_min: budget.reset_period_min
3847
+ })),
3848
+ apiUrl: options.apiBaseUrl,
3849
+ hostedMcpUrl: registration.hosted_mcp_url,
3850
+ x402BindingSigner: setup.x402_binding_signer ?? void 0,
3851
+ warn: log
3609
3852
  });
3610
- await clearRekeyPending(stored.directory);
3611
- const names = serverNamesFor(options.serverName);
3612
- const messages = [
3613
- `Agent ${identity.name || stored.agentId} is now on its new signing key.`,
3614
- ` Signing address: ${pending.new_delegate_address}`,
3615
- ` Credentials: ${stored.directory} (rewritten in place)`,
3616
- ` MCP servers: ${names.hosted} / ${names.signer} (unchanged names)`
3617
- ];
3618
- let configRewritten = false;
3619
- if (options.runtime) {
3620
- const prepared = await (deps.prepareSigner ?? prepareSignerRuntime)(
3621
- {
3622
- credentialDirectory: stored.directory,
3623
- signerPath: `${stored.directory}/signer.json`,
3624
- homeDir: options.homeDir
3625
- },
3626
- { runCommand: deps.runCommand, env: deps.env }
3627
- );
3628
- const result = await (deps.writeConfig ?? writeHostedRuntimeConfig)(
3629
- { runCommand: deps.runCommand, homeDir: options.homeDir },
3630
- {
3631
- runtime: options.runtime,
3632
- hostedMcpUrl: stored.hostedMcpUrl,
3633
- apiKey: options.newApiKey,
3634
- identityPath: `${stored.directory}/identity.json`,
3635
- signerPath: `${stored.directory}/signer.json`,
3636
- credentialDirectory: stored.directory,
3637
- serverName: options.serverName
3638
- },
3639
- { command: prepared.command, args: prepared.args }
3853
+ trace.directory = credentialPaths.directory;
3854
+ try {
3855
+ const bindingRecord = {
3856
+ version: 1,
3857
+ server_name: hostedNameForRun,
3858
+ signer_name: serverNamesFor(serverName).signer,
3859
+ agent_id: registration.agent_id,
3860
+ api_url: withoutUserinfo(options.apiBaseUrl),
3861
+ // never persist `user:pass@` (#3154 doc review r2)
3862
+ ...registration.hosted_mcp_url ? { hosted_mcp_url: registration.hosted_mcp_url } : {},
3863
+ bound_at: (/* @__PURE__ */ new Date()).toISOString()
3864
+ };
3865
+ await writeMcpServerBinding(credentialPaths.directory, bindingRecord);
3866
+ } catch {
3867
+ log("Could not record the MCP server-name binding locally (non-fatal; the next setup cannot see this binding).");
3868
+ }
3869
+ log(`Stored Haven identity credential locally: ${credentialPaths.identityPath}`);
3870
+ log(`Stored local signer credential locally: ${credentialPaths.signerPath}`);
3871
+ log(`Stored non-secret agent orientation locally: ${credentialPaths.agentPath}`);
3872
+ if (setup.x402_binding_signer) {
3873
+ log("Configured x402 binding signer for the local signer.");
3874
+ } else {
3875
+ log(
3876
+ "Warning: Haven did not provide an x402 binding signer, so x402 payments will not sign until HAVEN_X402_BINDING_SIGNER is set for the signer. Non-x402 payments are unaffected."
3640
3877
  );
3641
- configRewritten = result.hostedConfigured;
3642
- if (prepared.runtimeSpecOverride) {
3643
- messages.push(
3644
- ` Signer runtime: RUNTIME SPEC OVERRIDE ACTIVE \u2014 ${describeRuntimeSpecOverride(prepared.runtimeSpecOverride.specs)} (NOT the pinned manifest; installed into ${prepared.runtimeDirectory})`
3645
- );
3878
+ }
3879
+ const runtimeInstall = await runRuntimeInstall({
3880
+ runtime,
3881
+ hostedMcpUrl: registration.hosted_mcp_url,
3882
+ apiKey: localApiKey,
3883
+ signerPath: credentialPaths.signerPath,
3884
+ identityPath: credentialPaths.identityPath,
3885
+ credentialDirectory: credentialPaths.directory,
3886
+ environmentLabel: options.environmentLabel ?? "Local workspace",
3887
+ ackSigner: options.ackSigner,
3888
+ ackLocalTools: options.ackLocalTools,
3889
+ localMcp: options.localMcp,
3890
+ serverName
3891
+ }, {
3892
+ onProgress: log,
3893
+ // #1543: report "runtime configured" the moment the config write settles,
3894
+ // so the dashboard can expose its budget-approval controls without
3895
+ // waiting on the probes and skill install — a tail that approval does not
3896
+ // depend on. Silent and best-effort: the complete report below remains
3897
+ // authoritative (it overwrites these keys, adding the probe verdicts and
3898
+ // skill state), so an early failure costs nothing but the head start.
3899
+ onRuntimeConfigured: async (early) => {
3900
+ try {
3901
+ await api.updateInstallStatus(registration.setup_id, localApiKey, {
3902
+ runtime: early.runtime,
3903
+ connectorVersion,
3904
+ runtimeMcpMode: early.runtimeMcpMode,
3905
+ hostedMcpConfigured: early.hostedMcpConfigured,
3906
+ localSignerConfigured: early.localSignerConfigured,
3907
+ localMcpConfigured: early.localMcpConfigured,
3908
+ credentialFilesWritten: true,
3909
+ signerAcknowledged: early.signerAcknowledged,
3910
+ localMcpAcknowledged: early.localMcpAcknowledged,
3911
+ restartRequired: early.restartRequired,
3912
+ nextUserAction: early.nextUserAction,
3913
+ errorCode: early.errorCode ?? null,
3914
+ environmentLabel: options.environmentLabel ?? "Local workspace"
3915
+ });
3916
+ if (!early.errorCode || early.errorCode === "manual_runtime_setup_required") {
3917
+ log(approveBudgetCta(setup, registration.approval_url));
3918
+ }
3919
+ } catch {
3920
+ }
3646
3921
  }
3647
- messages.push(` Config: ${result.target}`);
3648
- messages.push(...result.messages.map((line) => ` ${line}`));
3649
- if (!configRewritten) {
3650
- messages.push(
3651
- "",
3652
- "WARNING: the MCP config was NOT updated, so it still carries the OLD API key and every",
3653
- `wired host will fail with 401. Fix the cause above and re-run with --runtime ${options.runtime},`,
3654
- "or update the config by hand. The credential files on disk are already on the new key."
3922
+ });
3923
+ printRuntimeInstall(runtimeInstall, log);
3924
+ if (runtimeInstall.errorCode) {
3925
+ log("Haven setup needs a couple more steps on this machine \u2014 see the notes above.");
3926
+ } else {
3927
+ log("Haven setup on this machine is complete.");
3928
+ }
3929
+ let supersededAgentsRetiredLocally;
3930
+ const retiredAgentIds = [];
3931
+ const retirementMirrorErrors = {};
3932
+ if (replacing) {
3933
+ if (runtimeInstall.errorCode) {
3934
+ supersededAgentsRetiredLocally = false;
3935
+ log(
3936
+ `Previous agent(s) ${supersededIds(replacing)} were NOT retired: the runtime install did not complete, so their wiring may still be the only working one. Resolve the install, then retire them with ${RERUN_HINT} --unwire <dir>.`
3655
3937
  );
3938
+ } else {
3939
+ supersededAgentsRetiredLocally = true;
3940
+ for (const entry of replacing.superseded) {
3941
+ try {
3942
+ const { mirrorError } = await tombstoneDirectoryIfAbsent({
3943
+ directory: entry.directory,
3944
+ agentId: entry.agentId,
3945
+ reason: "replaced by a new setup (--replace)",
3946
+ replacedBy: registration.agent_id,
3947
+ // #3251: the ledger follows this run's credential root (default
3948
+ // root → ~/.haven/tombstones, as before; any other → <root>/.tombstones).
3949
+ tombstonesDir: tombstonesDirForCredentialRoot(options.credentialsDir)
3950
+ });
3951
+ if (mirrorError !== void 0) {
3952
+ retirementMirrorErrors[entry.agentId] = mirrorError;
3953
+ log(
3954
+ `Warning: the surviving tombstone record for ${entry.agentId} could not be written to ${tombstonesDirForCredentialRoot(options.credentialsDir)} (${mirrorError}). The in-place TOMBSTONE.json stands; --doctor will not list this retirement once the directory is deleted.`
3955
+ );
3956
+ }
3957
+ await teardownLocalKeyMaterial(entry.directory, await readIdentityFile(entry.directory));
3958
+ await clearMcpServerBinding(entry.directory);
3959
+ retiredAgentIds.push(entry.agentId);
3960
+ log(`Retired previous agent ${entry.agentId} locally: tombstoned, local key files removed.`);
3961
+ } catch (err) {
3962
+ supersededAgentsRetiredLocally = false;
3963
+ log(`Could not retire previous agent ${entry.agentId} locally: ${err instanceof Error ? err.message : String(err)}`);
3964
+ }
3965
+ }
3656
3966
  }
3657
- } else {
3658
- messages.push(
3659
- "",
3660
- "NOTE: no --runtime was given, so the MCP config still carries the OLD API key and every",
3661
- "wired host will fail with 401. Re-run with --runtime <name> to rewrite it."
3662
- );
3663
3967
  }
3664
- return {
3665
- finished: true,
3666
- agentId: stored.agentId,
3667
- directory: stored.directory,
3668
- newDelegateAddress: pending.new_delegate_address,
3669
- serverNames: { hosted: names.hosted, signer: names.signer },
3670
- configRewritten,
3671
- messages
3672
- };
3673
- }
3674
- async function probeIdentity(api, apiKey, which) {
3968
+ let supersededScan = null;
3969
+ let supersededAgentIds = [];
3675
3970
  try {
3676
- return await api.getAgentIdentity(apiKey);
3677
- } catch (err) {
3678
- const status = err?.status;
3679
- if (status === 401 || status === 403) {
3680
- throw new Error(
3681
- which === "current" ? "This machine's Haven API key is no longer accepted. If a re-key already finished elsewhere, run --rekey-finish with the key that re-key produced instead of starting a new one." : "Haven rejected that API key. Check you pasted the whole key from the agent page \u2014 nothing was changed."
3971
+ supersededScan = await listOtherAgentIds(options.credentialsDir, credentialPaths.directory);
3972
+ supersededAgentIds = supersededScan ?? [];
3973
+ if (supersededAgentsRetiredLocally === true) {
3974
+ log("");
3975
+ log(
3976
+ `Replaced: previous agent(s) ${supersededIds(replacing)} are retired on this machine but NOT revoked \u2014 revoke them on the Haven agent page, then restart EVERY long-lived host (gateways, TUI workers, editors): each holds the MCP wiring snapshot from its own start time, and the tombstone speaks only when a stale host next probes the old path.`
3977
+ );
3978
+ } else if (supersededAgentIds.length > 0) {
3979
+ log("");
3980
+ log(
3981
+ `Heads-up: this setup created a NEW agent. Your previous agent(s) \u2014 ${supersededAgentIds.join(", ")} \u2014 still exist with their own keys, and any host that was already running keeps acting as them.`
3982
+ );
3983
+ log(
3984
+ `If you meant to replace them: revoke them on the Haven agent page, then restart EVERY long-lived host (gateways, TUI workers, editors) \u2014 each holds the MCP wiring snapshot from its own start time, so after repeated setups each can be stuck on a DIFFERENT old agent. Then remove their directories under ~/.haven/agents (or ${RERUN_HINT} --tombstone <dir> to leave a diagnostic in their place). Run ${RERUN_HINT} --doctor to check whether their keys are still live.`
3682
3985
  );
3683
3986
  }
3684
- throw new Error(
3685
- `Could not reach Haven to check this agent (${redactSecrets(
3686
- err instanceof Error ? err.message : String(err)
3687
- )}). Nothing was changed.`
3688
- );
3987
+ } catch {
3689
3988
  }
3690
- }
3691
- function assertRekeyable(identity, stored) {
3692
- if (identity.id !== stored.agentId) {
3693
- throw new Error(
3694
- `The credentials at ${stored.directory} say agent ${stored.agentId}, but Haven says that key belongs to ${identity.id}. Refusing to re-key an agent this directory does not own.`
3695
- );
3989
+ try {
3990
+ await api.updateInstallStatus(registration.setup_id, localApiKey, {
3991
+ runtime: runtimeInstall.runtime,
3992
+ connectorVersion,
3993
+ runtimeMcpMode: runtimeInstall.runtimeMcpMode,
3994
+ hostedMcpConfigured: runtimeInstall.hostedMcpConfigured,
3995
+ localSignerConfigured: runtimeInstall.localSignerConfigured,
3996
+ localMcpConfigured: runtimeInstall.localMcpConfigured,
3997
+ credentialFilesWritten: true,
3998
+ signerAcknowledged: runtimeInstall.signerAcknowledged,
3999
+ localMcpAcknowledged: runtimeInstall.localMcpAcknowledged,
4000
+ activationCommandAvailable: Boolean(runtimeInstall.activationCommand),
4001
+ skillInstalled: runtimeInstall.skillInstalled,
4002
+ probeResult: runtimeInstall.probeResult,
4003
+ restartRequired: runtimeInstall.restartRequired,
4004
+ nextUserAction: runtimeInstall.nextUserAction,
4005
+ errorCode: runtimeInstall.errorCode,
4006
+ environmentLabel: options.environmentLabel ?? "Local workspace",
4007
+ // The raw scan result, `null` and all — NOT the flattened
4008
+ // `supersededAgentIds` the outcome carries. Flattening here would hand
4009
+ // the dashboard the same ambiguity this field exists to remove (#2561).
4010
+ supersededAgentIds: supersededScan
4011
+ });
4012
+ } catch (err) {
4013
+ log(`Could not report install status to Haven: ${err instanceof Error ? err.message : String(err)}`);
3696
4014
  }
3697
- if (identity.execution_rail === "legacy") {
3698
- throw new Error(
3699
- `Agent ${identity.name || identity.id} is on the legacy rail, which cannot be re-keyed \u2014 its authority is per-token Safe allowances, not a signed delegation there is anything to re-issue. Re-onboard the agent on the delegation rail instead.`
3700
- );
4015
+ let approval;
4016
+ const narrateApprovalWait = options.waitForApproval === true || options.waitForApproval === void 0 && (deps.isStdoutTty ?? Boolean(process.stdout.isTTY));
4017
+ if (narrateApprovalWait && !runtimeInstall.errorCode) {
4018
+ approval = await waitForBudgetApproval(api, registration.setup_id, localApiKey, log, options.approvalWait);
3701
4019
  }
3702
- if (identity.status === "revoked") {
3703
- throw new Error(
3704
- `Agent ${identity.name || identity.id} is revoked. Re-keying would hand a revoked agent fresh credentials \u2014 create a new agent instead.`
3705
- );
4020
+ printNextSteps(runtimeInstall, log, approval, registration.approval_url);
4021
+ const outcome = completionOutcome({
4022
+ runtimeInstall,
4023
+ delegateAddress: registration.delegate_address,
4024
+ hostedMcpUrl: registration.hosted_mcp_url,
4025
+ supersededAgentIds,
4026
+ supersededAgentsRetiredLocally,
4027
+ ...replacing ? { retiredAgentIds } : {},
4028
+ ...Object.keys(retirementMirrorErrors).length > 0 ? { retirementMirrorErrors } : {},
4029
+ existingAgentsBeforeWrite: existingAgents.map((a) => ({ agent_id: a.agentId, account_address: a.accountAddress })),
4030
+ ...reboundFrom ? { serverNameReboundFrom: reboundFrom } : {},
4031
+ setupChallengeExpiresAt: setup.challenge.expires_at,
4032
+ approvalRequired: registration.agent_status === "pending_approval",
4033
+ approvalUrl: registration.approval_url
4034
+ });
4035
+ if (await recordConnectOutcome(deps, credentialPaths.directory, outcome)) {
4036
+ log(`Saved this run's outcome to ${CONNECT_OUTCOME_FILENAME} in the agent's credential directory.`);
3706
4037
  }
4038
+ return {
4039
+ setupId: registration.setup_id,
4040
+ agentId: registration.agent_id,
4041
+ delegateAddress: registration.delegate_address,
4042
+ credentialPaths,
4043
+ outcome
4044
+ };
3707
4045
  }
3708
- var init_rekey = __esm({
3709
- "src/rekey.ts"() {
3710
- init_api();
3711
- init_runtime_install();
3712
- init_signer_runtime();
3713
- init_runtime_spec_override();
3714
- init_key();
3715
- init_redact();
3716
- init_rekey_messages();
3717
- init_server_names();
3718
- init_storage();
3719
- }
3720
- });
3721
-
3722
- // src/rekey-restart.ts
3723
- var rekey_restart_exports = {};
3724
- __export(rekey_restart_exports, {
3725
- restartGuidance: () => restartGuidance
3726
- });
3727
- function restartGuidance(runtime) {
3728
- const profile = runtime ? BY_RUNTIME[runtime] : void 0;
3729
- const lines = ["The new key is only live in a process that started after now.", ""];
3730
- if (profile) {
3731
- lines.push(profile.how);
3732
- for (const command of profile.commands) lines.push(` ${command}`);
3733
- if (profile.commands.length > 0) lines.push("");
3734
- } else {
3735
- lines.push(
3736
- runtime ? `No standard restart command is known for "${runtime}" \u2014 restart it the way you start it.` : "Pass --runtime <name> to get the restart command for a specific host."
3737
- );
3738
- lines.push("");
3739
- }
3740
- lines.push(SWEEP);
3741
- return { commands: profile?.commands ?? [], lines };
4046
+ function completionOutcome(input) {
4047
+ const { runtimeInstall } = input;
4048
+ const manualSetup = runtimeInstall.errorCode === "manual_runtime_setup_required";
4049
+ const nextAction2 = runtimeInstall.nextUserAction;
4050
+ const outcome = {
4051
+ schema_version: CONNECT_OUTCOME_SCHEMA_VERSION,
4052
+ outcome: runtimeInstall.errorCode ? "action_required" : "complete",
4053
+ runtime: runtimeInstall.runtime,
4054
+ topology: runtimeInstall.runtimeMcpMode,
4055
+ configuration: {
4056
+ hosted_mcp: runtimeInstall.hostedMcpConfigured,
4057
+ local_signer: runtimeInstall.localSignerConfigured,
4058
+ local_mcp: runtimeInstall.localMcpConfigured
4059
+ },
4060
+ probe: { result: runtimeInstall.probeResult },
4061
+ activation: {
4062
+ restart_required: runtimeInstall.restartRequired,
4063
+ instruction: manualSetup ? "Finish the manual MCP setup using the secret-free references shown in normal Connect output, then start a fresh session." : runtimeProfile(runtimeInstall.runtime).activationInstruction
4064
+ },
4065
+ next_action: nextAction2,
4066
+ approval: {
4067
+ required: input.approvalRequired,
4068
+ expires_at: null,
4069
+ // Only when there is something to approve AND the backend supplied a
4070
+ // link. Never synthesised here: the connector does not know the
4071
+ // dashboard's origin, and a guessed URL is worse than none — it is the
4072
+ // "do not invent one" rule the agent runbook states, applied to the
4073
+ // tool rather than the agent.
4074
+ ...input.approvalRequired && input.approvalUrl ? { url: input.approvalUrl } : {}
4075
+ },
4076
+ verification: {
4077
+ tools: ["haven_get_agent", "haven_get_allowances"],
4078
+ instruction: runtimeVerificationInstruction(runtimeInstall.runtime)
4079
+ },
4080
+ // The backend contract supplies a 20-byte address. If an unexpected
4081
+ // malformed value arrives, do not echo it into an automation-facing
4082
+ // record; the human log has already been redacted separately.
4083
+ delegate_address: /^0x[0-9a-fA-F]{40}$/.test(input.delegateAddress) ? shortAddress(input.delegateAddress) : "[delegate-address-redacted]",
4084
+ // The endpoint Connect wrote into the runtime's MCP config, verbatim — the
4085
+ // same string that already sits in the user's own config file. Passed
4086
+ // through the secret filter anyway: this is the automation contract, the
4087
+ // value is server-supplied, and belts are cheap (the #1589 stance).
4088
+ ...input.hostedMcpUrl ? { hosted_mcp_url: redactSecrets(input.hostedMcpUrl) } : {},
4089
+ // Always emitted on a completed run, empty list included: "no superseded
4090
+ // agents" is a fact a caller needs, and an omitted key would be
4091
+ // indistinguishable from an older connector that never reported it.
4092
+ superseded_agent_ids: input.supersededAgentIds ?? [],
4093
+ ...input.supersededAgentsRetiredLocally !== void 0 ? { superseded_agents_retired_locally: input.supersededAgentsRetiredLocally } : {},
4094
+ ...input.retiredAgentIds ? { retired_agent_ids: input.retiredAgentIds } : {},
4095
+ ...input.retirementMirrorErrors ? { retirement_mirror_errors: input.retirementMirrorErrors } : {},
4096
+ // #3122: always emitted on a completed run (empty list included), for the
4097
+ // same reason as superseded_agent_ids above.
4098
+ existing_agents_before_write: input.existingAgentsBeforeWrite ?? [],
4099
+ ...input.serverNameReboundFrom ? { server_name_rebound_from: input.serverNameReboundFrom } : {},
4100
+ ...input.setupChallengeExpiresAt ? { setup_challenge_expires_at: input.setupChallengeExpiresAt } : {},
4101
+ ...runtimeInstall.errorCode ? { error: { code: runtimeInstall.errorCode, next_action: nextAction2 } } : {}
4102
+ };
4103
+ return outcome;
3742
4104
  }
3743
- var SWEEP, BY_RUNTIME;
3744
- var init_rekey_restart = __esm({
3745
- "src/rekey-restart.ts"() {
3746
- SWEEP = "Then restart EVERY other long-lived MCP host on this machine \u2014 gateways, TUI workers, editors. Each holds the wiring snapshot from its own start time, so after a re-key each one is still presenting the OLD API key and will fail with 401 until it restarts.";
3747
- BY_RUNTIME = {
3748
- "claude-code": {
3749
- commands: ["claude --continue"],
3750
- how: "Exit this Claude Code session and start a new one:"
3751
- },
3752
- "codex-cli": {
3753
- commands: ["codex resume --last"],
3754
- how: "Start a fresh Codex CLI session:"
3755
- },
3756
- "codex-desktop": {
3757
- commands: [],
3758
- how: "Quit Codex Desktop completely (not just the window) and reopen it."
3759
- },
3760
- "claude-desktop": {
3761
- commands: [],
3762
- how: "Quit Claude Desktop completely (not just the window) and reopen it."
3763
- },
3764
- hermes: {
3765
- commands: ["systemctl --user restart hermes-gateway", "/restart"],
3766
- how: "Restart the Hermes gateway, or run /restart inside a Hermes session. The first form is the one that matters if you run it as a user service:"
3767
- },
3768
- cursor: {
3769
- commands: [],
3770
- how: 'Cursor hot-reloads MCP config, so it will pick the new key up on its own. If a tool call still fails with 401, reload the window (Cmd/Ctrl+Shift+P \u2192 "Reload Window").'
3771
- },
3772
- vscode: {
3773
- commands: [],
3774
- how: 'VS Code hot-reloads MCP config. If a tool call still fails with 401, reload the window (Cmd/Ctrl+Shift+P \u2192 "Reload Window").'
3775
- },
3776
- "vscode-insiders": {
3777
- commands: [],
3778
- how: 'VS Code Insiders hot-reloads MCP config. If a tool call still fails with 401, reload the window (Cmd/Ctrl+Shift+P \u2192 "Reload Window").'
3779
- }
3780
- };
4105
+ async function installedClientHintFor(deps) {
4106
+ try {
4107
+ const candidates = await (deps.scanInstalledClients ?? scanInstalledClients)({ env: deps.env });
4108
+ const hint = installedClientHint(candidates);
4109
+ return hint.installedClients.length > 0 ? hint : {};
4110
+ } catch {
4111
+ return {};
3781
4112
  }
3782
- });
3783
-
3784
- // src/doctor.ts
3785
- var doctor_exports = {};
3786
- __export(doctor_exports, {
3787
- describeAccountAddressKey: () => describeAccountAddressKey,
3788
- rollUpLevel: () => rollUpLevel,
3789
- runDoctor: () => runDoctor,
3790
- runRepair: () => runRepair
3791
- });
3792
- function finalizeCheck(check) {
3793
- return { ...check, ok: check.level !== "failed" };
3794
4113
  }
3795
- function rollUpLevel(checks) {
3796
- if (checks.some((check) => check.level === "failed")) return "failed";
3797
- if (checks.some((check) => check.level === "advisory")) return "advisory";
3798
- return "ok";
4114
+ function installedClientProse(hint) {
4115
+ const found = hint.installedClients ?? [];
4116
+ if (found.length === 0) return "";
4117
+ const suggestion = hint.suggestedRuntime ? ` The likeliest is ${hint.suggestedRuntime}, but Haven will not choose for you \u2014 pass it yourself if it is right.` : " Haven will not choose between them for you.";
4118
+ return `Haven can see these agent clients installed here, likeliest first: ${found.join(", ")}.${suggestion} `;
3799
4119
  }
3800
- function runtimeFlagFor(runtime) {
3801
- return normalizeRuntimeName(runtime) ? ` --runtime ${runtime}` : "";
4120
+ function runtimeSelectionPrompt(options, deps) {
4121
+ if (!interactivePromptAllowed(options, deps)) return void 0;
4122
+ return deps.promptRuntime ?? (() => resolveRuntimeByInstalledClientPrompt());
3802
4123
  }
3803
- async function resolveDoctorRuntime(input, directory) {
3804
- const explicit = input.runtime.trim();
3805
- if (explicit) return { runtime: explicit, origin: "flag" };
3806
- if (directory) {
3807
- const recorded = await readConnectOutcomeRuntime(directory);
3808
- if (recorded !== null && normalizeRuntimeName(recorded)) {
3809
- return { runtime: recorded, origin: "record" };
3810
- }
3811
- }
3812
- return { runtime: "", origin: "unknown" };
4124
+ function interactivePromptAllowed(options, deps) {
4125
+ if (options.interactive !== true) return false;
4126
+ return deps.isTty ?? Boolean(process.stdin.isTTY);
3813
4127
  }
3814
- async function discoverCredentialDirectory(homeDir, explicit) {
3815
- const root = explicit ? dirname(explicit) : join(homeDir, ".haven", "agents");
3816
- let entries = [];
3817
- try {
3818
- entries = await readdir(root);
3819
- } catch {
3820
- return explicit ? { directory: explicit, others: [], parkedOnly: /* @__PURE__ */ new Set() } : { others: [], parkedOnly: /* @__PURE__ */ new Set() };
3821
- }
3822
- const candidates = [];
3823
- const tombstonedOnly = [];
3824
- const parkedOnly = [];
3825
- for (const entry of entries) {
3826
- const directory = join(root, entry);
3827
- try {
3828
- const s = await stat(join(directory, "identity.json"));
3829
- candidates.push({ directory, mtimeMs: s.mtimeMs });
3830
- } catch {
3831
- try {
3832
- await stat(join(directory, TOMBSTONE_FILENAME));
3833
- tombstonedOnly.push(directory);
3834
- } catch {
3835
- try {
3836
- await stat(join(directory, REKEY_PENDING_FILENAME));
3837
- parkedOnly.push(directory);
3838
- } catch {
3839
- }
3840
- }
4128
+ function supersededIds(collision) {
4129
+ return collision.superseded.map((entry) => entry.agentId).join(", ");
4130
+ }
4131
+ async function resolveWiringCollision(collision, agentName, options, deps) {
4132
+ if (options.replaceExistingWiring) return { action: "replace" };
4133
+ if (interactivePromptAllowed(options, deps)) {
4134
+ const prompt = deps.promptWiringCollision ?? ((c, name) => promptWiringCollisionResolution(c, name, defaultPromptIo()));
4135
+ const resolution = await prompt(collision, agentName);
4136
+ if (resolution.action === "abort") {
4137
+ throw new ConnectError(
4138
+ "wiring_collision_declined",
4139
+ `Setup stopped at your request: this machine is already wired to ${supersededIds(collision)} and you chose neither to replace that wiring nor to install alongside it. Nothing was written: no agent was created, no credentials were stored, and the Haven setup token is still unused. Run the connector command again with --replace to re-point haven / haven-signer at the new agent, or with --name <slug> (e.g. --name ${collision.suggestedServerName}) to install alongside.`,
4140
+ "rerun_connect_with_replace_or_name",
4141
+ { supersededAgentIds: collision.superseded.map((e) => e.agentId), suggestedServerName: collision.suggestedServerName }
4142
+ );
3841
4143
  }
4144
+ return resolution;
3842
4145
  }
3843
- const parkedOnlySet = new Set(parkedOnly);
3844
- candidates.sort((a, b) => b.mtimeMs - a.mtimeMs);
3845
- if (explicit) {
3846
- return {
3847
- directory: explicit,
3848
- others: [...candidates.map((c) => c.directory), ...tombstonedOnly, ...parkedOnly].filter((d) => d !== explicit),
3849
- parkedOnly: parkedOnlySet
3850
- };
3851
- }
3852
- if (candidates.length === 0 && tombstonedOnly.length === 0 && parkedOnly.length === 0) {
3853
- return { others: [], parkedOnly: parkedOnlySet };
3854
- }
4146
+ throw new ConnectError(
4147
+ "wiring_collision",
4148
+ `This machine is already wired to a Haven agent with a live key (${supersededIds(collision)}), and setting up "${agentName}" on the bare haven / haven-signer pair would replace that wiring. Nothing was written and the Haven setup token is still unused. If you are an AI agent running this command: do NOT add a flag yourself \u2014 relay this to your user and stop. Your user decides: REPLACE the existing wiring (re-run the same command with --replace added, which re-points the pair at the new agent and retires the previous directory locally \u2014 they still revoke the old agent on the Haven agent page), or install ALONGSIDE it (re-run with --name <slug> added, e.g. --name ${collision.suggestedServerName}, which gives the new agent its own haven-<slug> / haven-signer-<slug> pair). Re-run only with the flag your user chooses.`,
4149
+ "relay_wiring_collision_to_user",
4150
+ { supersededAgentIds: collision.superseded.map((e) => e.agentId), suggestedServerName: collision.suggestedServerName }
4151
+ );
4152
+ }
4153
+ function failedConnectOutcome(runtimeHint, error) {
4154
+ const message = error instanceof Error ? error.message : "";
4155
+ const code = error instanceof ConnectError ? error.code : /Node\.js >=/i.test(message) ? "unsupported_node_version" : /setup challenge.*expired|expired or invalid/i.test(message) ? "setup_challenge_expired_or_invalid" : /only available for Claude Code and Codex/i.test(message) ? "local_mcp_unsupported_runtime" : "connect_failed";
4156
+ const runtime = normalizeRuntime(runtimeHint);
4157
+ const nextAction2 = error instanceof ConnectError ? error.nextAction : code === "setup_challenge_expired_or_invalid" ? "return_to_haven_for_fresh_setup" : code === "unsupported_node_version" ? "install_supported_node_and_rerun_connect" : code === "local_mcp_unsupported_runtime" ? "rerun_without_local_mcp" : "review_the_safe_error_output_and_start_a_fresh_haven_setup_if_needed";
3855
4158
  return {
3856
- directory: candidates[0]?.directory,
3857
- others: [...candidates.slice(1).map((c) => c.directory), ...tombstonedOnly, ...parkedOnly],
3858
- parkedOnly: parkedOnlySet
4159
+ schema_version: CONNECT_OUTCOME_SCHEMA_VERSION,
4160
+ outcome: "failed",
4161
+ runtime,
4162
+ topology: "unknown",
4163
+ configuration: { hosted_mcp: false, local_signer: false, local_mcp: false },
4164
+ probe: { result: "not_run" },
4165
+ activation: { restart_required: false, instruction: "Resolve the reported problem before activating Haven tools." },
4166
+ next_action: nextAction2,
4167
+ approval: { required: false, expires_at: null },
4168
+ verification: {
4169
+ tools: ["haven_get_agent", "haven_get_allowances"],
4170
+ instruction: "After a successful setup and activation, verify only with haven_get_agent and haven_get_allowances."
4171
+ },
4172
+ error: {
4173
+ code,
4174
+ next_action: nextAction2,
4175
+ // Only a ConnectError's message enters the JSON record: the vocabulary's
4176
+ // prose is connector-authored and safe to serialize, while a plain
4177
+ // Error can carry arbitrary server or filesystem detail (that stance is
4178
+ // pinned by test). Redaction stays on as belt-and-braces; plain-Error
4179
+ // runs still get their redacted message on stderr via the CLI mirror.
4180
+ ...error instanceof ConnectError && message ? { message: redactForAutomation(message) } : {},
4181
+ ...error instanceof ConnectError && error.details.allowedRuntimes ? { allowed_runtimes: error.details.allowedRuntimes } : {},
4182
+ ...error instanceof ConnectError && error.details.installedClients?.length ? { installed_clients: error.details.installedClients } : {},
4183
+ ...error instanceof ConnectError && error.details.suggestedRuntime ? { suggested_runtime: error.details.suggestedRuntime } : {},
4184
+ ...error instanceof ConnectError && error.details.supersededAgentIds ? { superseded_agent_ids: error.details.supersededAgentIds } : {},
4185
+ ...error instanceof ConnectError && error.details.suggestedServerName ? { suggested_name: error.details.suggestedServerName } : {}
4186
+ }
3859
4187
  };
3860
4188
  }
3861
- function agentIsWired(configText, names, slug, identity, sidecar, isPrimary, bareOwnerExists) {
3862
- if (configText === null) return isPrimary;
3863
- if (slug) {
3864
- for (const name of [names.hosted, names.codexHosted, names.signer, names.codexSigner]) {
3865
- if (new RegExp(`(^|[."'\\s\\[])${name}(["'\\]:\\s]|$)`, "m").test(configText)) return true;
4189
+ function printSetupSummary(setup, log) {
4190
+ log(`Fetched Haven setup for ${setup.agent.name}.`);
4191
+ log(`Haven wallet: ${setup.haven_wallet.name} on ${setup.haven_wallet.network}.`);
4192
+ if (setup.agent_budget.length > 0) {
4193
+ for (const budget of setup.agent_budget) {
4194
+ log(
4195
+ `Agent budget: ${budget.allowance_amount} atomic ${budget.token_symbol} / ${budget.reset_period_min} minute reset.`
4196
+ );
3866
4197
  }
3867
- return false;
3868
4198
  }
3869
- if (sidecar?.wrapper_path && configText.includes(sidecar.wrapper_path)) return true;
3870
- if (bareOwnerExists) return false;
3871
- return isPrimary && Boolean(identity?.hosted_mcp_url && configText.includes(identity.hosted_mcp_url));
3872
- }
3873
- function rekeyPendingCheck(status, hostedDelegateAddress, runtime, slug) {
3874
- return finalizeCheck(rekeyPendingVerdict(status, hostedDelegateAddress, runtime, slug));
4199
+ log(`Setup challenge expires at ${setup.challenge.expires_at}. If it expires, return to Haven for a fresh setup and rerun Connect \u2014 do not reuse or paste credentials.`);
3875
4200
  }
3876
- function rekeyPendingVerdict(status, hostedDelegateAddress, runtime, slug) {
3877
- const label = "Pending re-key";
3878
- const nameFlag = slug ? ` --name ${slug}` : "";
3879
- if (status.state === "unreadable") {
3880
- return {
3881
- id: "rekey_pending",
3882
- label,
3883
- level: "failed",
3884
- detail: `A re-key was started here but ${status.path} does not parse, so neither the address it generated nor when it started can be read. The file still holds what was a private key.`,
3885
- repair: `Delete ${status.path}, then start again: ${RERUN} --rekey${nameFlag}`
3886
- };
3887
- }
3888
- const started = status.startedAt ?? "an unknown time";
3889
- const address = status.newDelegateAddress ?? "unknown";
3890
- const completedOnHaven = hostedDelegateAddress !== void 0 && status.newDelegateAddress !== void 0 && hostedDelegateAddress.toLowerCase() === status.newDelegateAddress.toLowerCase();
3891
- if (completedOnHaven) {
3892
- return {
3893
- id: "rekey_pending",
3894
- label,
3895
- level: "failed",
3896
- detail: `A re-key started ${started} has COMPLETED on Haven \u2014 the agent's signing address is already ${address}, the one this machine generated \u2014 but the local half was never finished, so the credential files here still hold the old key. Parked at ${status.path}.` + (status.state === "expired" ? " The local file is also past its 24h TTL, which --rekey-finish refuses, so the finish command below will not accept it any more." : ""),
3897
- repair: status.state === "expired" ? `The parked key expired. Start again \u2014 ${RERUN} --rekey${nameFlag} \u2014 and re-run "Replace signing key" on the Haven agent page with the new address it prints.` : `Run: ${RERUN} --rekey-finish${nameFlag} --api-key <the key the agent page showed you>${runtimeFlagFor(runtime)}`
3898
- };
3899
- }
3900
- const wedgeNote = "Haven is NOT yet on this address, so the re-key did not complete. This machine cannot tell whether the on-chain revoke on the agent page already ran: if it did not, closing this costs nothing; if it did, the agent's old delegations are revoked, no new ones were issued, and only an owner re-grant restores its spend authority (#1868). Check the agent page before assuming the harmless case.";
3901
- if (status.state === "expired") {
3902
- return {
3903
- id: "rekey_pending",
3904
- label,
3905
- level: "failed",
3906
- detail: `A re-key started ${started} EXPIRED ${status.expiresAt ?? ""} without being finished. Its address was ${address}; the private half it generated is still on disk at ${status.path}. ` + wedgeNote,
3907
- repair: `Either delete ${status.path} to drop the parked key, or start over: ${RERUN} --rekey${nameFlag}. Connect never deletes it for you \u2014 an expired TTL is a refusal to USE the key, not a licence to destroy key material you may still be mid-flow on.`
3908
- };
4201
+ function approveBudgetCta(setup, approvalUrl) {
4202
+ const where = approvalUrl ? `at ${approvalUrl}` : "in the Haven dashboard";
4203
+ const budgetPhrase = setup.agent_budget.length > 0 ? setup.agent_budget.map((budget) => `up to ${describeSetupBudget(budget)}`).join(", ") : void 0;
4204
+ if (budgetPhrase) {
4205
+ return `\u2192 Action needed: approve this agent's budget \u2014 ${budgetPhrase} from ${setup.haven_wallet.name} on ${setup.haven_wallet.network} \u2014 ${where}. The approval button is live now; setup continues here in the meantime.`;
3909
4206
  }
3910
- return {
3911
- id: "rekey_pending",
3912
- label,
3913
- level: "ok",
3914
- detail: `A re-key started ${started} is still open (expires ${status.expiresAt ?? "unknown"}). Paste this address into "Replace signing key" on the Haven agent page: ${address}. Parked at ${status.path}. ` + wedgeNote
3915
- };
4207
+ return `\u2192 Action needed: approve this agent's budget ${where} \u2014 the approval button is live now. Setup continues here in the meantime.`;
3916
4208
  }
3917
- async function runtimeSpecOverrideCheck(directory, sidecar, env) {
3918
- const facts = [];
3919
- const installed = sidecar?.runtime_spec_override;
3920
- if (installed) {
3921
- facts.push(
3922
- `signer runtime installed under ${describeRuntimeSpecOverride(installed.specs)} (resolved: ${installed.resolved_specs.join(" ")}; directory key ${installed.directory_key})`
3923
- );
3924
- }
3925
- const mcpInstalled = await readMcpSidecarOverride(directory);
3926
- if (mcpInstalled) {
3927
- facts.push(
3928
- `local MCP runtime installed under ${describeRuntimeSpecOverride(mcpInstalled.specs)} (resolved: ${mcpInstalled.resolved_specs.join(" ")}; directory key ${mcpInstalled.directory_key})`
3929
- );
3930
- }
3931
- let shell;
3932
- try {
3933
- const active = resolveRuntimeSpecOverride(env);
3934
- if (active) shell = `set in this shell: ${describeRuntimeSpecOverride(active)} \u2014 a --repair from here installs these, not the pin`;
3935
- } catch (err) {
3936
- shell = err instanceof RuntimeSpecOverrideError ? `set in this shell but REFUSED: ${err.message}` : `set in this shell but unreadable: ${err instanceof Error ? err.message : String(err)}`;
3937
- }
3938
- if (shell) facts.push(shell);
3939
- if (facts.length === 0) return void 0;
3940
- const variables = Object.values(RUNTIME_SPEC_ENV).join(" / ");
3941
- return finalizeCheck({
3942
- id: "runtime_spec_override",
3943
- label: "Runtime spec override",
3944
- level: "failed",
3945
- detail: `runtime spec overridden \u2014 not the pinned manifest (${MCP_RUNTIME_MANIFEST.signerPackage}@${MCP_RUNTIME_MANIFEST.signerVersion}, ${MCP_RUNTIME_MANIFEST.sdkPackage}@${MCP_RUNTIME_MANIFEST.sdkVersion}). ${facts.join(". ")}.`,
3946
- repair: `Developer override (#2424). To return to the pinned manifest: unset ${variables}, then run ${RERUN} --doctor --repair --runtime <runtime>. If the override is intentional, this finding is the record of it.`
4209
+ function describeSetupBudget(budget) {
4210
+ return describeApprovedBudget({
4211
+ token_symbol: budget.token_symbol,
4212
+ token_address: budget.token_address,
4213
+ amount: budget.allowance_amount,
4214
+ reset_period_min: budget.reset_period_min
3947
4215
  });
3948
4216
  }
3949
- async function readMcpSidecarOverride(directory) {
3950
- try {
3951
- const parsed = JSON.parse(await readFile(join(directory, "mcp-runtime.json"), "utf8"));
3952
- return parsed.runtime_spec_override;
3953
- } catch {
3954
- return void 0;
3955
- }
4217
+ function assertSetupChallengeIsUsable(expiresAt) {
4218
+ const expiresAtMs = Date.parse(expiresAt);
4219
+ if (!Number.isNaN(expiresAtMs) && expiresAtMs > Date.now()) return;
4220
+ throw new Error(
4221
+ "This Haven setup challenge is expired or invalid. Return to Haven, start a fresh connection, and rerun Connect. No local credentials were written."
4222
+ );
3956
4223
  }
3957
- async function readIdentity(directory) {
3958
- try {
3959
- return JSON.parse(await readFile(join(directory, "identity.json"), "utf8"));
3960
- } catch {
3961
- return void 0;
3962
- }
4224
+ function deadSetupTokenError(err) {
4225
+ if (!(err instanceof ConnectRequestError) || err.status !== 410 && err.status !== 401) return null;
4226
+ return new ConnectError(
4227
+ "setup_challenge_expired_or_invalid",
4228
+ "This Haven setup token is expired or invalid \u2014 tokens are single-use and expire 30 minutes after the dashboard issues them, and a mistyped token reads the same way. Return to Haven, start a fresh connection, and run its new connector command. No local credentials were written.",
4229
+ "return_to_haven_for_fresh_setup"
4230
+ );
3963
4231
  }
3964
- function describeAccountAddressKey(identity, signerFile) {
3965
- const files = [identity, signerFile];
3966
- const has = (key) => files.some((f) => typeof f?.[key] === "string" && f[key].trim() !== "");
3967
- if (has("account_address")) return "account address stored as account_address";
3968
- if (has("safe_address")) {
3969
- return "account address stored under the pre-#2908 name safe_address \u2014 still read; the next --rekey or setup rewrites it as account_address";
3970
- }
3971
- return "no account address stored";
4232
+ function isExpiredSetupChallenge(err) {
4233
+ return err instanceof Error && /(?:setup )?challenge.*expir|expir.*(?:setup )?challenge/i.test(err.message);
3972
4234
  }
3973
- async function checksForAgent(entry, input, deps) {
3974
- const verdicts = await verdictsForAgent(entry, input, deps);
3975
- return {
3976
- checks: verdicts.checks.map(finalizeCheck),
3977
- ...verdicts.signerCapabilities ? { signerCapabilities: verdicts.signerCapabilities } : {}
4235
+ function secureLogger(log, redactPaths = false) {
4236
+ return (message) => {
4237
+ log(redactPaths ? redactForAutomation(message) : redactSecrets(message));
3978
4238
  };
3979
4239
  }
3980
- async function verdictsForAgent(entry, input, deps) {
3981
- const { directory, identity, sidecar } = entry;
3982
- const checks = [];
3983
- let signerCapabilities;
3984
- let signerFile;
3985
- try {
3986
- const parsed = JSON.parse(await readFile(join(directory, "signer.json"), "utf8"));
3987
- signerFile = typeof parsed === "object" && parsed !== null ? parsed : void 0;
3988
- } catch {
3989
- signerFile = void 0;
4240
+ function printRuntimeInstall(result, log) {
4241
+ for (const message of result.messages) log(message);
4242
+ if (result.localMcpConfigured) {
4243
+ log("Configured local Haven MCP tools.");
4244
+ } else if (result.hostedMcpConfigured) {
4245
+ log("Configured hosted Haven MCP identity.");
4246
+ } else {
4247
+ log("Haven MCP tools still need runtime setup.");
3990
4248
  }
3991
- const credentialsOk = Boolean(identity?.api_key) && signerFile !== void 0;
3992
- checks.push({
3993
- id: "credentials",
3994
- label: "Agent credentials",
3995
- level: credentialsOk ? "ok" : "failed",
3996
- detail: credentialsOk ? `identity.json and signer.json parse (agent ${identity?.agent_id ?? "unknown"}; ${describeAccountAddressKey(identity, signerFile)})` : "identity.json or signer.json is missing or unparseable.",
3997
- ...credentialsOk ? {} : { repair: `Re-run the full setup with a fresh token: ${RERUN} --setup <token>.` }
3998
- });
3999
- if (!sidecar) {
4000
- checks.push({
4001
- id: "signer_runtime",
4002
- label: "Signer runtime (preinstalled wrapper)",
4003
- level: "failed",
4004
- detail: "No signer-runtime.json sidecar \u2014 the pinned signer runtime was never prepared (or a pre-#1586 npx config).",
4005
- repair: `Run: ${RERUN} --doctor --repair${runtimeFlagFor(input.runtime)}`
4006
- });
4007
- } else if (sidecar.runtime_spec_override) {
4008
- const matches = await installedRuntimeMatchesVersions(sidecar.runtime_directory, sidecar.cli_path, {
4009
- signerVersion: sidecar.signer_version,
4010
- sdkVersion: sidecar.sdk_version
4011
- });
4012
- checks.push({
4013
- id: "signer_runtime",
4014
- label: "Signer runtime (preinstalled wrapper)",
4015
- level: matches ? "ok" : "failed",
4016
- detail: matches ? `Installed ${sidecar.signer_package}@${sidecar.signer_version} at ${sidecar.runtime_directory} (override install \u2014 see runtime_spec_override)` : `Override runtime directory is stale or empty (${sidecar.runtime_directory}) \u2014 the CLI or package versions are missing.`,
4017
- ...matches ? {} : { repair: `Run: ${RERUN} --doctor --repair${runtimeFlagFor(input.runtime)} with the same HAVEN_*_SPEC variables set.` }
4018
- });
4249
+ if (result.localSignerConfigured) {
4250
+ log("Configured local Haven signer.");
4019
4251
  } else {
4020
- const intact = await installedRuntimeMatchesVersions(sidecar.runtime_directory, sidecar.cli_path, {
4021
- signerVersion: sidecar.signer_version,
4022
- sdkVersion: sidecar.sdk_version
4023
- });
4024
- const versionOk = sidecar.signer_version === MCP_RUNTIME_MANIFEST.signerVersion;
4025
- const ok = intact && versionOk;
4026
- checks.push({
4027
- id: "signer_runtime",
4028
- label: "Signer runtime (preinstalled wrapper)",
4029
- level: ok ? "ok" : intact ? "advisory" : "failed",
4030
- detail: ok ? `Installed ${sidecar.signer_package}@${sidecar.signer_version} at ${sidecar.runtime_directory}` : intact ? `Installed version ${sidecar.signer_version} does not match the connector's pinned ${MCP_RUNTIME_MANIFEST.signerVersion} \u2014 intact, but outdated.` : `Runtime directory is stale or empty (${sidecar.runtime_directory}) \u2014 the CLI or package versions are missing.`,
4031
- ...ok ? {} : { repair: `Run: ${RERUN} --doctor --repair${runtimeFlagFor(input.runtime)}` }
4032
- });
4252
+ log("Local Haven signer still needs runtime setup.");
4033
4253
  }
4034
- const overrideCheck = await runtimeSpecOverrideCheck(directory, sidecar, deps.env ?? process.env);
4035
- if (overrideCheck) checks.push(overrideCheck);
4036
- const hostedUrl = identity?.hosted_mcp_url ?? (identity?.api_url ? `${identity.api_url}/mcp` : void 0);
4037
- if (identity?.api_key && hostedUrl) {
4038
- const probe = await (deps.probeHosted ?? probeHostedMcpTools)(identity.api_key, hostedUrl, deps.fetch);
4039
- checks.push({
4040
- id: "hosted_mcp",
4041
- label: "Hosted Haven MCP",
4042
- level: probe.status === "ok" ? "ok" : "failed",
4043
- detail: probe.status === "ok" ? `MCP tools endpoint is reachable (${hostedUrl}).` : `MCP tools endpoint probe failed: ${probe.status} (${hostedUrl}).`,
4044
- ...probe.status === "ok" ? {} : {
4045
- repair: "Check network access and runtime configuration for the hosted MCP URL, then re-run --doctor."
4046
- }
4047
- });
4048
- } else {
4049
- checks.push({
4050
- id: "hosted_mcp",
4051
- label: "Hosted Haven MCP",
4052
- level: "failed",
4053
- detail: "No stored API key / hosted MCP URL to probe with.",
4054
- repair: `Re-run the full setup: ${RERUN} --setup <token>.`
4055
- });
4254
+ }
4255
+ function formatAtomicAmount(atomic, decimals) {
4256
+ const s = atomic.toString().padStart(decimals + 1, "0");
4257
+ const intPart = s.slice(0, s.length - decimals) || "0";
4258
+ const fracPart = s.slice(s.length - decimals).replace(/0+$/, "");
4259
+ return fracPart ? `${intPart}.${fracPart}` : intPart;
4260
+ }
4261
+ function describeResetPeriod(resetPeriodMin) {
4262
+ if (resetPeriodMin === 1440) return "per day";
4263
+ if (resetPeriodMin === 10080) return "per week";
4264
+ if (resetPeriodMin === 43200) return "per month";
4265
+ if (resetPeriodMin === 60) return "per hour";
4266
+ if (resetPeriodMin === 0) return "in total";
4267
+ return `every ${resetPeriodMin} minutes`;
4268
+ }
4269
+ function describeApprovedBudget(budget) {
4270
+ const token = resolveTokenFromAddress(budget.token_address);
4271
+ const amount = token ? `${formatAtomicAmount(BigInt(budget.amount), token.decimals)} ${budget.token_symbol}` : `${budget.amount} ${budget.token_symbol} (atomic units)`;
4272
+ return `${amount} ${describeResetPeriod(budget.reset_period_min)}`;
4273
+ }
4274
+ function describeWaitBound(timeoutMs) {
4275
+ if (timeoutMs >= 12e4) {
4276
+ const minutes = Math.round(timeoutMs / 6e4);
4277
+ return `${minutes} minutes`;
4056
4278
  }
4057
- const localDelegate = typeof signerFile?.delegate_address === "string" ? signerFile.delegate_address : void 0;
4058
- let hostedDelegateAddress;
4059
- if (identity?.api_key && identity.api_url) {
4060
- const probe = await (deps.probeHostedIdentity ?? probeHostedAgentIdentity)(
4061
- identity.api_key,
4062
- identity.api_url,
4063
- deps.fetch
4064
- );
4065
- if (probe.status === "ok") hostedDelegateAddress = probe.delegateAddress;
4066
- if (probe.status !== "ok") {
4067
- checks.push({
4068
- id: "identity_match",
4069
- label: "Hosted identity matches the local signing key",
4070
- level: "failed",
4071
- detail: probe.status === "unauthorized" ? "The stored API key was rejected, so the agent it authenticates as cannot be compared with the local signing key." : `Could not read the hosted identity (${probe.status}) \u2014 the comparison did not happen, so it cannot be reported as a match.`,
4072
- repair: probe.status === "unauthorized" ? `Re-run the full setup with a fresh token: ${RERUN} --setup <token>.` : `Restore network access to the Haven API, then re-run: ${RERUN} --doctor${runtimeFlagFor(input.runtime)}`
4073
- });
4074
- } else if (!localDelegate) {
4075
- checks.push({
4076
- id: "identity_match",
4077
- label: "Hosted identity matches the local signing key",
4078
- level: "failed",
4079
- detail: "signer.json holds no delegate_address to compare against the hosted identity.",
4080
- repair: `Re-run the full setup with a fresh token: ${RERUN} --setup <token>.`
4081
- });
4082
- } else {
4083
- const same = probe.delegateAddress?.toLowerCase() === localDelegate.toLowerCase();
4084
- checks.push({
4085
- id: "identity_match",
4086
- label: "Hosted identity matches the local signing key",
4087
- level: same ? "ok" : "failed",
4088
- detail: same ? `The stored API key authenticates as the agent whose signing key is in this directory (${shortAddress(localDelegate)}).` : `MISMATCH: the stored API key authenticates as agent ${probe.agentId ?? "unknown"} with delegate ${shortAddress(probe.delegateAddress ?? "unknown")}, but signer.json here holds ${shortAddress(localDelegate)}. This runtime would quote as one agent and sign as another.`,
4089
- ...same ? {} : {
4090
- repair: `Re-run setup for this agent so its API key and signing key come from one run: ${RERUN} --setup <token>. Do not hand-edit either file.`
4091
- }
4092
- });
4279
+ return `${Math.round(timeoutMs / 1e3)}s`;
4280
+ }
4281
+ async function waitForBudgetApproval(api, setupId, apiKey, log, options = {}) {
4282
+ const intervalMs = options.intervalMs ?? 5e3;
4283
+ const timeoutMs = options.timeoutMs ?? 18e4;
4284
+ const sleep = options.sleep ?? ((ms) => new Promise((resolve11) => setTimeout(resolve11, ms)));
4285
+ const maxPolls = Math.max(1, Math.floor(timeoutMs / intervalMs));
4286
+ const remindEvery = Math.max(1, Math.floor(3e4 / intervalMs));
4287
+ let waitingAnnounced = false;
4288
+ const announceWaiting = () => {
4289
+ if (waitingAnnounced) return;
4290
+ waitingAnnounced = true;
4291
+ log("Now waiting for you to approve the budget in the Haven dashboard \u2014 approval is what unlocks the agent's Haven tools\u2026");
4292
+ };
4293
+ for (let i = 0; i < maxPolls; i++) {
4294
+ if (i > 0) await sleep(intervalMs);
4295
+ let status;
4296
+ try {
4297
+ status = await api.getConnectorStatus(setupId, apiKey);
4298
+ } catch (err) {
4299
+ if (err instanceof ConnectRequestError && (err.status === 401 || err.status === 404)) {
4300
+ log("This setup ended in Haven \u2014 start a fresh connection from the dashboard when ready.");
4301
+ return "ended";
4302
+ }
4303
+ announceWaiting();
4304
+ continue;
4093
4305
  }
4094
- }
4095
- const pending = await inspectRekeyPending(directory, deps.now?.() ?? Date.now());
4096
- if (pending) {
4097
- checks.push(rekeyPendingCheck(pending, hostedDelegateAddress, input.runtime, sidecar?.server_name));
4098
- }
4099
- if (sidecar) {
4100
- const consent = await getLocalSignerConsentStatus(join(directory, "signer.json"));
4101
- if (!consent.acknowledged) {
4102
- checks.push({
4103
- id: "signer_process",
4104
- label: "Signer stdio handshake",
4105
- level: "failed",
4106
- detail: "The local-tools consent is not acknowledged, so the signer refuses to start (by design).",
4107
- repair: `Run: ${RERUN} --ack-local-tools --setup <token> (or re-run your original connector command with --ack-local-tools).`
4108
- });
4109
- } else {
4110
- const probe = await (deps.probeSignerTools ?? probeLocalMcpTools)(
4111
- sidecar.wrapper_path,
4112
- [],
4113
- MCP_RUNTIME_MANIFEST.requiredSignerTools
4306
+ if (status.status === "active") {
4307
+ log(
4308
+ status.approved_budget ? `Budget approved \u{1F389} \u2014 I can now spend up to ${describeApprovedBudget(status.approved_budget)} from your Haven wallet.` : "Budget approved \u{1F389} \u2014 the agent can now spend within its Haven rules."
4309
+ );
4310
+ return "approved";
4311
+ }
4312
+ if (status.status === "cancelled" || status.status === "expired" || status.status === "failed") {
4313
+ log(`This setup ended in Haven (${status.status}) \u2014 start a fresh connection from the dashboard when ready.`);
4314
+ return "ended";
4315
+ }
4316
+ announceWaiting();
4317
+ if (i > 0 && i % remindEvery === 0) {
4318
+ const elapsedSeconds = Math.round(i * intervalMs / 1e3);
4319
+ log(
4320
+ `Still waiting for budget approval in Haven \u2014 ${elapsedSeconds}s elapsed, checking every ${Math.round(intervalMs / 1e3)}s. I'll stop waiting after ${describeWaitBound(timeoutMs)}; you can approve later and the tools unlock then.`
4114
4321
  );
4115
- const experimental = probe.capabilities?.experimental ?? probe.capabilities;
4116
- const compat = experimental?.["haven/signer-compatibility"];
4117
- signerCapabilities = compat ? { "haven/signer-compatibility": compat } : void 0;
4118
- const compatDetail = compat ? ` Compat: x402 expected-context v${JSON.stringify(compat.x402_expected_context_versions ?? "?")}.` : "";
4119
- checks.push({
4120
- id: "signer_process",
4121
- label: "Signer stdio handshake",
4122
- level: probe.status === "ok" ? "ok" : "failed",
4123
- detail: probe.status === "ok" ? `Signer started, listed ${probe.toolNames?.length ?? 0} tools${probe.serverInfo?.version ? ` (v${probe.serverInfo.version})` : ""}.${compatDetail}` : `Handshake failed: ${probe.status}.`,
4124
- ...probe.status === "ok" ? {} : { repair: `Run: ${RERUN} --doctor --repair${runtimeFlagFor(input.runtime)}` }
4125
- });
4126
4322
  }
4127
- } else {
4128
- checks.push({
4129
- id: "signer_process",
4130
- label: "Signer stdio handshake",
4131
- level: "failed",
4132
- detail: "Skipped \u2014 no prepared signer runtime to probe.",
4133
- repair: `Run: ${RERUN} --doctor --repair${runtimeFlagFor(input.runtime)}`
4134
- });
4135
4323
  }
4136
- return { checks, ...signerCapabilities ? { signerCapabilities } : {} };
4324
+ log(
4325
+ "Budget approval is still pending in Haven. Approve it in the dashboard whenever you are ready \u2014 the agent tools unlock the moment you do. Verify later with the read-only haven_get_agent tool."
4326
+ );
4327
+ return "pending";
4137
4328
  }
4138
- async function runDoctor(input, deps = {}) {
4139
- const homeDir = deps.homeDir ?? homedir();
4140
- const checks = [];
4141
- let signerCapabilities;
4142
- const { directory, others, parkedOnly } = await discoverCredentialDirectory(homeDir, input.credentialsDir);
4143
- const resolution = await resolveDoctorRuntime(input, directory);
4144
- const runtime = resolution.runtime;
4145
- const input2 = { ...input, runtime };
4146
- const normalizedRuntime = normalizeRuntimeName(input2.runtime);
4147
- const configPath = runtimeConfigPathFor(normalizedRuntime ?? input2.runtime, homeDir);
4148
- let configText = null;
4149
- if (configPath !== null) {
4329
+ function completionHandoffLines(result, approval, approvalUrl) {
4330
+ const approveStep = approvalUrl ? `Approve the budget at ${approvalUrl}. Approval \u2014 not restarting \u2014 unlocks Haven tools.` : "Return to Haven and approve the budget. Approval \u2014 not restarting \u2014 unlocks Haven tools.";
4331
+ if (result.errorCode === "manual_runtime_setup_required") {
4332
+ return [
4333
+ "Next steps:",
4334
+ `1. ${approveStep}`,
4335
+ "2. Finish the manual MCP setup using the secret-free file references printed above, then start a fresh session in your runtime.",
4336
+ `3. ${runtimeVerificationInstruction(result.runtime)}`
4337
+ ];
4338
+ }
4339
+ if (result.errorCode) {
4340
+ return [
4341
+ "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."
4342
+ ];
4343
+ }
4344
+ if (approval === "ended") {
4345
+ return [
4346
+ "Next step: this setup ended in Haven before the budget was approved, so there is nothing left to approve on it \u2014 start a fresh connection from the dashboard when ready."
4347
+ ];
4348
+ }
4349
+ const profile = runtimeProfile(result.runtime);
4350
+ const activation = activationInstructionWithWhy(profile);
4351
+ if (approval === "approved") {
4352
+ return [
4353
+ "Next steps \u2014 the budget is already approved, so there is nothing more to do in Haven:",
4354
+ `1. ${activation}`,
4355
+ `2. ${runtimeVerificationInstruction(result.runtime)}`
4356
+ ];
4357
+ }
4358
+ return [
4359
+ "Next steps:",
4360
+ `1. ${approveStep}`,
4361
+ `2. ${activation}`,
4362
+ `3. ${runtimeVerificationInstruction(result.runtime)}`
4363
+ ];
4364
+ }
4365
+ function activationInstructionWithWhy(profile) {
4366
+ if (profile.restartMode === "restart-session") {
4367
+ return `${profile.activationInstruction} (The entries are already written and verified \u2014 ${profile.label} only reads MCP config when a session starts, which is why this step is still needed.)`;
4368
+ }
4369
+ if (profile.restartMode === "restart-app") {
4370
+ return `${profile.activationInstruction} (The entries are already written and verified \u2014 ${profile.label} only reads MCP config at app launch, which is why this step is still needed.)`;
4371
+ }
4372
+ return profile.activationInstruction;
4373
+ }
4374
+ async function listExistingKeyedAgents(baseDir) {
4375
+ const root = defaultCredentialRoot(baseDir);
4376
+ let entries = [];
4377
+ try {
4378
+ entries = await readdir(root);
4379
+ } catch {
4380
+ return [];
4381
+ }
4382
+ const out = [];
4383
+ for (const entry of entries) {
4384
+ const directory = join(root, entry);
4150
4385
  try {
4151
- configText = await readFile(configPath, "utf8");
4386
+ const identity = JSON.parse(await readFile(join(directory, "identity.json"), "utf8"));
4387
+ if (typeof identity.api_key !== "string" || identity.api_key.length === 0) continue;
4388
+ let agent = {};
4389
+ try {
4390
+ agent = JSON.parse(await readFile(join(directory, "agent.json"), "utf8"));
4391
+ } catch {
4392
+ }
4393
+ const { accountAddress } = readStoredAccountAddress(identity, agent);
4394
+ out.push({ agentId: typeof identity.agent_id === "string" ? identity.agent_id : entry, directory, accountAddress: accountAddress ?? null });
4152
4395
  } catch {
4153
- configText = null;
4154
4396
  }
4155
4397
  }
4156
- const allDirectories = directory ? [directory, ...others] : others;
4157
- let bareOwnerExists = false;
4158
- for (const dir of allDirectories) {
4159
- const sidecar = await readRuntimeSidecar(dir);
4160
- if (!sidecar?.server_name && sidecar?.wrapper_path && configText?.includes(sidecar.wrapper_path)) {
4161
- bareOwnerExists = true;
4162
- break;
4163
- }
4398
+ return out;
4399
+ }
4400
+ async function listOtherAgentIds(baseDir, currentDirectory) {
4401
+ const root = defaultCredentialRoot(baseDir);
4402
+ let entries = [];
4403
+ try {
4404
+ entries = await readdir(root);
4405
+ } catch {
4406
+ return null;
4164
4407
  }
4165
- const inventory = [];
4166
- const capabilitiesByDirectory = /* @__PURE__ */ new Map();
4167
- const primaryChecksById = /* @__PURE__ */ new Map();
4168
- for (const dir of allDirectories) {
4169
- const identity = await readIdentity(dir);
4170
- const sidecar = await readRuntimeSidecar(dir);
4171
- const tombstone = await readAgentTombstone(dir);
4172
- const slug = sidecar?.server_name;
4173
- const names = serverNamesFor(slug);
4174
- const rekeyPending = await inspectRekeyPending(dir, deps.now?.() ?? Date.now());
4175
- if (!identity?.api_key) {
4176
- const agentId = tombstone?.agent_id ?? rekeyPending?.agentId;
4177
- inventory.push({
4178
- ...slug ? { slug } : {},
4179
- ...agentId ? { agentId } : {},
4180
- directory: dir,
4181
- // A tombstone is a deliberate record and outranks the discovery tell:
4182
- // a retired directory that also holds a parked key stays `retired`.
4183
- classification: tombstone ? "retired" : parkedOnly.has(dir) ? "parked" : "orphaned",
4184
- checks: rekeyPending ? [rekeyPendingCheck(rekeyPending, void 0, input2.runtime, slug)] : [],
4185
- ...rekeyPending ? { rekeyPending } : {}
4186
- });
4408
+ const ids = [];
4409
+ for (const entry of entries) {
4410
+ if (join(root, entry) === currentDirectory) continue;
4411
+ const identityPath = join(root, entry, "identity.json");
4412
+ try {
4413
+ await stat(identityPath);
4414
+ } catch {
4187
4415
  continue;
4188
4416
  }
4189
- const wired = agentIsWired(configText, names, slug, identity, sidecar, dir === directory, bareOwnerExists);
4190
- const entry = {
4191
- ...slug ? { slug } : {},
4192
- ...identity.agent_id ? { agentId: identity.agent_id } : {},
4193
- directory: dir,
4194
- classification: wired ? "wired" : "superseded",
4195
- checks: [],
4196
- ...rekeyPending ? { rekeyPending } : {}
4197
- };
4198
- if (wired) {
4199
- const result = await checksForAgent({ directory: dir, identity, sidecar }, input2, deps);
4200
- entry.checks = result.checks;
4201
- capabilitiesByDirectory.set(dir, result.signerCapabilities);
4202
- } else if (rekeyPending) {
4203
- entry.checks = [rekeyPendingCheck(rekeyPending, void 0, input2.runtime, slug)];
4417
+ try {
4418
+ const identity = JSON.parse(await readFile(identityPath, "utf8"));
4419
+ ids.push(identity.agent_id ?? entry);
4420
+ } catch {
4421
+ ids.push(entry);
4204
4422
  }
4205
- inventory.push(entry);
4206
4423
  }
4207
- const wiredDirectories = inventory.filter((entry) => entry.classification === "wired").map((entry) => entry.directory);
4208
- const primaryDirectory = input.credentialsDir ? directory : wiredDirectories.includes(directory ?? "") ? directory : wiredDirectories[0] ?? directory;
4209
- if (primaryDirectory) {
4210
- const primaryEntry = inventory.find((entry) => entry.directory === primaryDirectory);
4211
- signerCapabilities = capabilitiesByDirectory.get(primaryDirectory);
4212
- for (const check of primaryEntry?.checks ?? []) primaryChecksById.set(check.id, check);
4424
+ return ids;
4425
+ }
4426
+ function printNextSteps(result, log, approval, approvalUrl) {
4427
+ for (const line of completionHandoffLines(result, approval, approvalUrl)) log(line);
4428
+ }
4429
+ var CONNECTOR_VERSION, CONNECTOR_CLIENT_IDENTITY, CONNECT_OUTCOME_SCHEMA_VERSION, failureOutcomesByError, RERUN_HINT;
4430
+ var init_runtime = __esm({
4431
+ "src/runtime.ts"() {
4432
+ init_api();
4433
+ init_key();
4434
+ init_redact();
4435
+ init_server_names();
4436
+ init_storage();
4437
+ init_runtime_install();
4438
+ init_runtime_registry();
4439
+ init_connect_error();
4440
+ init_installed_clients();
4441
+ init_wiring_collision();
4442
+ init_unwire();
4443
+ init_tombstone();
4444
+ init_local_mcp_runtime();
4445
+ init_runtime_manifest();
4446
+ CONNECTOR_VERSION = "0.6.0-alpha.0";
4447
+ CONNECTOR_CLIENT_IDENTITY = `@haven_ai/connect/${CONNECTOR_VERSION}`;
4448
+ CONNECT_OUTCOME_SCHEMA_VERSION = 1;
4449
+ failureOutcomesByError = /* @__PURE__ */ new WeakMap();
4450
+ RERUN_HINT = connectorRerunCommand();
4213
4451
  }
4214
- if (!primaryDirectory) {
4215
- checks.push({
4216
- id: "credentials",
4217
- label: "Agent credentials",
4218
- level: "failed",
4219
- detail: "No agent credential directory with an identity.json under ~/.haven/agents.",
4220
- repair: `Run the full setup once: ${RERUN} --setup <token from the Haven dashboard>.`
4221
- });
4222
- } else {
4223
- const primaryIdentity = await readIdentity(primaryDirectory);
4224
- const primarySidecar = await readRuntimeSidecar(primaryDirectory);
4225
- if (!primaryChecksById.has("credentials")) {
4226
- const result = await checksForAgent(
4227
- { directory: primaryDirectory, identity: primaryIdentity, sidecar: primarySidecar },
4228
- input2,
4229
- deps
4230
- );
4231
- signerCapabilities = result.signerCapabilities;
4232
- for (const check of result.checks) primaryChecksById.set(check.id, check);
4452
+ });
4453
+
4454
+ // src/rekey-messages.ts
4455
+ var REKEY_FINISH_NEEDS_API_KEY;
4456
+ var init_rekey_messages = __esm({
4457
+ "src/rekey-messages.ts"() {
4458
+ REKEY_FINISH_NEEDS_API_KEY = "--rekey-finish needs --api-key <key> \u2014 the one the Haven agent page showed once.";
4459
+ }
4460
+ });
4461
+
4462
+ // src/prune-runtimes.ts
4463
+ var prune_runtimes_exports = {};
4464
+ __export(prune_runtimes_exports, {
4465
+ normalizeRuntimePath: () => normalizeRuntimePath,
4466
+ pruneSignerRuntimes: () => pruneSignerRuntimes,
4467
+ referencedRuntimeDirectories: () => referencedRuntimeDirectories,
4468
+ rollUpPruneLevel: () => rollUpPruneLevel,
4469
+ signerRuntimeRoot: () => signerRuntimeRoot
4470
+ });
4471
+ function signerRuntimeRoot(homeDir) {
4472
+ return join(homeDir, ".haven", "signer-runtime");
4473
+ }
4474
+ function classifyKey(key) {
4475
+ if (key.startsWith("override-")) return "override";
4476
+ if (key === MCP_RUNTIME_MANIFEST.signerVersion || /^\d+\.\d+\.\d+/.test(key)) return "version";
4477
+ return "unknown";
4478
+ }
4479
+ async function directoryBytes(directory) {
4480
+ let total = 0;
4481
+ const walk = async (dir) => {
4482
+ let entries = [];
4483
+ try {
4484
+ entries = await readdir(dir, { withFileTypes: true });
4485
+ } catch {
4486
+ return;
4233
4487
  }
4234
- for (const id of ["credentials", "signer_runtime", "runtime_spec_override"]) {
4235
- const check = primaryChecksById.get(id);
4236
- if (check) checks.push(check);
4488
+ for (const entry of entries) {
4489
+ const path = join(dir, entry.name);
4490
+ if (entry.isDirectory()) await walk(path);
4491
+ else if (entry.isFile()) {
4492
+ try {
4493
+ total += (await stat(path)).size;
4494
+ } catch {
4495
+ }
4496
+ }
4237
4497
  }
4498
+ };
4499
+ await walk(directory);
4500
+ return total;
4501
+ }
4502
+ async function normalizeRuntimePath(path) {
4503
+ const resolved = resolve(path).replace(/[\\/]+$/, "");
4504
+ try {
4505
+ return await realpath(resolved);
4506
+ } catch {
4507
+ return resolved;
4238
4508
  }
4239
- const runtimeOwnsNoConfig = normalizedRuntime !== null && configPath === null;
4240
- if (configPath === null && input2.runtime !== "" && normalizedRuntime === null) {
4241
- checks.push({
4242
- id: "runtime_config",
4243
- label: "Runtime MCP config",
4244
- level: "failed",
4245
- detail: `Runtime '${input2.runtime}' is not one the connector recognises. The runtime config was NOT checked. Re-run the doctor naming the runtime \u2014 one of: ${RUNTIME_FLAG_VALUE_LIST.join(", ")}.`,
4246
- repair: `Re-run the doctor naming the runtime \u2014 one of: ${RUNTIME_FLAG_VALUE_LIST.join(", ")}.`
4247
- });
4248
- } else if (configPath === null && input2.runtime === "") {
4249
- checks.push({
4250
- id: "runtime_config",
4251
- label: "Runtime MCP config",
4252
- level: "failed",
4253
- detail: `Runtime is unknown \u2014 no runtime flag was given and the connector's record in ${primaryDirectory ?? input.credentialsDir ?? "~/.haven/agents"} carries no resolvable ${CONNECT_OUTCOME_FILENAME} runtime. The runtime config was NOT checked. Re-run the doctor naming the runtime \u2014 one of: ${RUNTIME_FLAG_VALUE_LIST.join(", ")}.`,
4254
- repair: `Re-run the doctor naming the runtime \u2014 one of: ${RUNTIME_FLAG_VALUE_LIST.join(", ")}.`
4255
- });
4256
- } else if (configPath === null) {
4257
- checks.push({
4258
- id: "runtime_config",
4259
- label: "Runtime MCP config",
4260
- level: "ok",
4261
- 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 \u2014 skipping the file check.`
4262
- });
4263
- } else if (configText === null) {
4264
- checks.push({
4265
- id: "runtime_config",
4266
- label: "Runtime MCP config",
4267
- level: "failed",
4268
- detail: `No runtime config at ${configPath}.`,
4269
- repair: `Run: ${RERUN} --doctor --repair${runtimeFlagFor(input2.runtime)}`
4270
- });
4271
- } else {
4272
- const primaryIdentity = await readIdentity(primaryDirectory ?? "");
4273
- const primarySidecar = primaryDirectory ? await readRuntimeSidecar(primaryDirectory) : null;
4274
- const hasHaven = primaryIdentity?.hosted_mcp_url ? configText.includes(primaryIdentity.hosted_mcp_url) : configText.includes("haven");
4275
- const signerViaNpx = configText.includes("@haven_ai/signer");
4276
- const wrapperReferenced = primarySidecar ? configText.includes(primarySidecar.wrapper_path) : false;
4277
- const ok = hasHaven && !signerViaNpx && (primarySidecar ? wrapperReferenced : true);
4278
- checks.push({
4279
- id: "runtime_config",
4280
- label: "Runtime MCP config",
4281
- level: ok ? "ok" : "failed",
4282
- detail: ok ? `Config at ${configPath} references the hosted server and the prepared signer wrapper.` : signerViaNpx ? `Config at ${configPath} still launches the signer via npx \u2014 the pre-#1586 shape that cannot start under a 120s startup timeout.` : `Config at ${configPath} is missing the Haven entries${primarySidecar && !wrapperReferenced ? " (or references a different signer wrapper)" : ""}.`,
4283
- ...ok ? {} : { repair: `Run: ${RERUN} --doctor --repair${runtimeFlagFor(input2.runtime)}` }
4284
- });
4285
- }
4286
- for (const id of ["hosted_mcp", "identity_match", "rekey_pending"]) {
4287
- const check = primaryChecksById.get(id);
4288
- if (check) checks.push(check);
4289
- }
4290
- const otherEntries = inventory.filter((entry) => entry.directory !== primaryDirectory);
4291
- if (otherEntries.length > 0) {
4292
- const live = [];
4293
- const revoked = [];
4294
- const unverifiable = [];
4295
- const retired = [];
4296
- for (const entry of otherEntries) {
4297
- const identity = await readIdentity(entry.directory);
4298
- const tombstone = await readAgentTombstone(entry.directory);
4299
- const otherAgent = entry.agentId ?? basename(entry.directory);
4300
- if (!identity?.api_key || !identity.api_url) {
4301
- if (tombstone) retired.push(`${otherAgent} (retired ${tombstone.retired_at})`);
4302
- else unverifiable.push(`${otherAgent} (no stored key/API URL to probe)`);
4303
- continue;
4509
+ }
4510
+ function escapeRegExp(text) {
4511
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4512
+ }
4513
+ async function referencedRuntimeDirectories(homeDir, credentialsDir) {
4514
+ const roots = /* @__PURE__ */ new Set([join(homeDir, ".haven", "agents")]);
4515
+ if (credentialsDir) roots.add(dirname(resolve(credentialsDir)));
4516
+ const referenced = /* @__PURE__ */ new Map();
4517
+ const runtimeRoot = await normalizeRuntimePath(signerRuntimeRoot(homeDir));
4518
+ const rootSpellings = [.../* @__PURE__ */ new Set([resolve(signerRuntimeRoot(homeDir)), runtimeRoot])];
4519
+ const wrapperRe = new RegExp(`(?:${rootSpellings.map(escapeRegExp).join("|")})[\\/]+([^\\/'"\\s]+)`, "g");
4520
+ const add = async (runtimeDirectory, by) => {
4521
+ const key = await normalizeRuntimePath(runtimeDirectory);
4522
+ const list = referenced.get(key) ?? [];
4523
+ if (!list.includes(by)) list.push(by);
4524
+ referenced.set(key, list);
4525
+ };
4526
+ for (const root of roots) {
4527
+ let entries = [];
4528
+ try {
4529
+ entries = await readdir(root);
4530
+ } catch {
4531
+ continue;
4532
+ }
4533
+ for (const entry of entries) {
4534
+ const directory = join(root, entry);
4535
+ try {
4536
+ const sidecar = JSON.parse(await readFile(join(directory, "signer-runtime.json"), "utf8"));
4537
+ if (typeof sidecar.runtime_directory === "string" && sidecar.runtime_directory.length > 0) {
4538
+ await add(sidecar.runtime_directory, directory);
4539
+ }
4540
+ } catch {
4541
+ }
4542
+ try {
4543
+ const wrapper = await readFile(join(directory, "bin", "haven-signer.mjs"), "utf8");
4544
+ for (const match of wrapper.matchAll(wrapperRe)) await add(join(runtimeRoot, match[1]), directory);
4545
+ } catch {
4304
4546
  }
4305
- const suffix = tombstone ? " [tombstoned \u2014 key material still present]" : "";
4306
- const probe = await (deps.probeHostedIdentity ?? probeHostedAgentIdentity)(
4307
- identity.api_key,
4308
- identity.api_url,
4309
- deps.fetch
4310
- );
4311
- if (probe.status === "ok") live.push({ label: `${otherAgent}${suffix}`, entry });
4312
- else if (probe.status === "unauthorized") revoked.push(`${otherAgent}${suffix}`);
4313
- else unverifiable.push(`${otherAgent} (${probe.status})${suffix}`);
4314
4547
  }
4315
- const parts = [];
4316
- if (live.length > 0) parts.push(`STILL SPEND-CAPABLE: ${live.map((item) => item.label).join(", ")}`);
4317
- if (revoked.length > 0) parts.push(`already revoked: ${revoked.join(", ")}`);
4318
- if (retired.length > 0) parts.push(`tombstoned (keys removed): ${retired.join(", ")}`);
4319
- if (unverifiable.length > 0) parts.push(`could not verify: ${unverifiable.join(", ")}`);
4320
- const knownIds = new Set([...inventory].map((e) => e.agentId ?? basename(e.directory)));
4321
- const ghostRecords = (await readTombstoneRecords(join(homeDir, ".haven", "tombstones"))).filter(
4322
- (rec) => !knownIds.has(rec.agent_id)
4323
- );
4324
- if (ghostRecords.length > 0) {
4325
- parts.push(
4326
- `retired records (dir removed): ${ghostRecords.map((rec) => `${rec.agent_id} (${rec.reason})`).join(", ")}`
4327
- );
4328
- }
4329
- const supersededLive = live.filter((item) => item.entry.classification !== "wired").map((item) => item.label);
4330
- const classificationUnreliable = configText === null && runtimeOwnsNoConfig;
4331
- const supersededLevel = supersededLive.length === 0 ? "ok" : classificationUnreliable ? "advisory" : "failed";
4332
- checks.push({
4333
- id: "superseded_agents",
4334
- label: "Superseded agent credentials",
4335
- level: supersededLevel,
4336
- detail: supersededLevel === "failed" ? `${otherEntries.length} other credential dir(s) found \u2014 ${parts.join("; ")}. A host started before your latest setup keeps authenticating (and spending) as the old agent.` : supersededLevel === "advisory" ? `${otherEntries.length} other credential dir(s) found \u2014 ${parts.join("; ")}. Runtime '${input2.runtime}' has no config file the connector can read, so which of these agents are wired cannot be verified from this machine: a live key here may be an agent you use deliberately, or one a host started before your latest setup is still spending as.` : `${otherEntries.length} other credential dir(s) found \u2014 ${parts.join("; ")}.`,
4337
- ...supersededLevel === "failed" ? {
4338
- repair: `Revoke ${supersededLive.join(", ")} on the Haven agent page, then remove the old director(y/ies) under ~/.haven/agents. Connect never revokes or deletes for you.`
4339
- } : supersededLevel === "advisory" ? {
4340
- repair: `Check ${supersededLive.join(", ")} on the Haven agent page: revoke the ones you no longer use, then remove their director(y/ies) under ~/.haven/agents. Connect never revokes or deletes for you.`
4341
- } : {}
4342
- });
4343
- }
4344
- const bindings = (await Promise.all(
4345
- inventory.filter((entry) => entry.classification !== "retired").map(async (entry) => ({ entry, binding: await readMcpServerBinding(entry.directory) }))
4346
- )).filter((item) => item.binding !== null);
4347
- const byName = /* @__PURE__ */ new Map();
4348
- for (const item of bindings) {
4349
- const list = byName.get(item.binding.server_name) ?? [];
4350
- list.push(item);
4351
- byName.set(item.binding.server_name, list);
4352
- }
4353
- const rebound = [...byName.entries()].filter(([, items]) => items.length > 1);
4354
- if (rebound.length > 0) {
4355
- const parts = rebound.map(([name, items]) => {
4356
- 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);
4357
- const backends = new Set(ordered.map((i) => withoutUserinfo(i.binding.api_url)));
4358
- return `'${name}': ` + ordered.map((i) => `${i.binding.agent_id} on ${withoutUserinfo(i.binding.api_url)} at ${i.binding.bound_at} [${i.entry.classification}]`).join(" \u2192 ") + (backends.size > 1 ? " (BACKEND CHANGED)" : "");
4359
- });
4360
- checks.push({
4361
- id: "mcp_server_name_rebound",
4362
- label: "MCP server names bound more than once",
4363
- level: "advisory",
4364
- detail: `${rebound.length} MCP server name${rebound.length === 1 ? "" : "s"} changed hands on this machine (locally recorded bindings; the backend's own record is the authority for the same backend): ${parts.join("; ")}. A saved session, script or document naming the server may still mean the earlier agent.`,
4365
- repair: `Retire the earlier director(y/ies) with ${RERUN} --unwire <dir> to release the name, or keep both and address them by --name.`
4366
- });
4367
- }
4368
- const parkedElsewhere = inventory.filter((entry) => entry.directory !== primaryDirectory && entry.rekeyPending).map((entry) => ({ entry, pending: entry.rekeyPending }));
4369
- if (parkedElsewhere.length > 0) {
4370
- const abandoned = parkedElsewhere.filter((item) => item.pending.state !== "pending");
4371
- const describe = (item) => `${item.entry.slug ?? item.entry.agentId ?? basename(item.entry.directory)} (${item.pending.state}, ${item.pending.path})`;
4372
- checks.push({
4373
- id: "rekey_pending_elsewhere",
4374
- label: "Parked re-keys in other credential directories",
4375
- level: abandoned.length === 0 ? "ok" : "failed",
4376
- detail: abandoned.length > 0 ? `ABANDONED re-key key material outside the agent this report describes: ${abandoned.map(describe).join(", ")}. Each holds a private key that was generated for a re-key nobody finished.` : `${parkedElsewhere.length} other director(y/ies) hold an open pending re-key: ${parkedElsewhere.map(describe).join(", ")}.`,
4377
- ...abandoned.length > 0 ? {
4378
- repair: "Check the Haven agent page for each before deleting: if its on-chain revoke already ran, the agent has no spend authority until you re-grant it (#1868), and that is not visible from this machine. Connect never deletes key material for you."
4379
- } : {}
4380
- });
4381
- }
4382
- const signerProcess = primaryChecksById.get("signer_process");
4383
- if (signerProcess) checks.push(signerProcess);
4384
- const prune = await (deps.pruneSignerRuntimes ?? pruneSignerRuntimes)({ dryRun: true, measure: false }, { homeDir, credentialsDir: input.credentialsDir });
4385
- const unused = prune.entries.filter((entry) => entry.action === "would_remove");
4386
- if (unused.length > 0) {
4387
- checks.push({
4388
- id: "signer_runtime_unused",
4389
- label: "Unused signer-runtime directories",
4390
- level: "advisory",
4391
- detail: `${unused.length} signer-runtime director${unused.length === 1 ? "y" : "ies"} under ${prune.root} that no credential directory names: ${unused.map((entry) => entry.key).join(", ")}. Nothing is broken; they are left over from earlier pins or overrides (sizes: --prune-signer-runtimes --dry-run).`,
4392
- repair: `Run: ${RERUN} --prune-signer-runtimes (add --dry-run to list only).`
4393
- });
4394
4548
  }
4395
- const restart = restartRequiredForRuntime(input2.runtime, deps.env);
4396
- checks.push({
4397
- id: "restart",
4398
- label: "Runtime restart",
4399
- level: "ok",
4400
- detail: restart ? "This runtime loads MCP config at startup \u2014 restart it after any repair before expecting the tools to appear." : input2.runtime === "" ? "Runtime is unknown \u2014 whether a restart is needed cannot be determined. Re-run the doctor naming the runtime for a definitive answer." : "No restart requirement known for this runtime."
4401
- });
4402
- const wiredChecks = inventory.filter((entry) => entry.classification === "wired").flatMap((entry) => entry.checks);
4403
- const finalChecks = checks.map(finalizeCheck);
4404
- const level = rollUpLevel([...finalChecks, ...wiredChecks]);
4405
- return {
4406
- version: 1,
4407
- ok: level !== "failed",
4408
- level,
4409
- runtime: input2.runtime,
4410
- credentialDirectory: primaryDirectory,
4411
- checks: finalChecks,
4412
- agents: inventory,
4413
- ...signerCapabilities ? { signerCapabilities } : {}
4414
- };
4549
+ return referenced;
4415
4550
  }
4416
- async function runRepair(input, deps = {}) {
4551
+ function rollUpPruneLevel(entries) {
4552
+ if (entries.some((e) => e.level === "failed")) return "failed";
4553
+ if (entries.some((e) => e.level === "advisory")) return "advisory";
4554
+ return "ok";
4555
+ }
4556
+ async function pruneSignerRuntimes(input, deps = {}) {
4417
4557
  const homeDir = deps.homeDir ?? homedir();
4418
- const messages = [];
4419
- const { directory, others } = await discoverCredentialDirectory(homeDir, input.credentialsDir);
4420
- if (others.length > 0) {
4421
- messages.push(`Note: ${others.length} other agent credential dir(s) exist \u2014 run --doctor for their status.`);
4422
- }
4423
- if (!directory) {
4424
- return {
4425
- ok: false,
4426
- messages: [`No agent credentials found to repair \u2014 run the full setup: ${RERUN} --setup <token>.`]
4427
- };
4428
- }
4429
- const resolution = await resolveDoctorRuntime(input, directory);
4430
- if (resolution.origin === "record") {
4431
- messages.push(`Runtime not given \u2014 resolved '${resolution.runtime}' from ${join(directory, CONNECT_OUTCOME_FILENAME)}.`);
4432
- }
4433
- const runtime = resolution.runtime;
4434
- const input2 = { ...input, runtime };
4435
- if (runtime === "") {
4436
- return {
4437
- ok: false,
4438
- messages: [
4439
- "Runtime is unknown \u2014 no runtime flag was given and the connector record carries no resolvable runtime.",
4440
- `Repair rewrites the runtime config, so it will not guess. Re-run repair naming the runtime \u2014 one of: ${RUNTIME_FLAG_VALUE_LIST.join(", ")}.`
4441
- ]
4442
- };
4443
- }
4444
- let identity;
4558
+ const root = signerRuntimeRoot(homeDir);
4559
+ const measure = input.measure ?? true;
4560
+ const referenced = await referencedRuntimeDirectories(homeDir, deps.credentialsDir);
4561
+ const pin = await normalizeRuntimePath(join(root, MCP_RUNTIME_MANIFEST.signerVersion));
4562
+ const remove = deps.rm ?? (async (directory) => rm(directory, { recursive: true, force: false }));
4563
+ const entries = [];
4564
+ let keys = [];
4445
4565
  try {
4446
- identity = JSON.parse(await readFile(join(directory, "identity.json"), "utf8"));
4566
+ keys = (await readdir(root, { withFileTypes: true })).filter((d) => d.isDirectory()).map((d) => d.name).sort();
4447
4567
  } catch {
4448
- return { ok: false, messages: ["identity.json is unreadable \u2014 re-run the full setup with a fresh token."] };
4449
- }
4450
- if (!identity.api_key || !(identity.hosted_mcp_url || identity.api_url)) {
4451
- return { ok: false, messages: ["identity.json lacks the stored API key / hosted URL \u2014 re-run the full setup."] };
4568
+ return { version: 1, root, dryRun: input.dryRun, entries, removed: 0, reclaimedBytes: 0, level: "ok" };
4452
4569
  }
4453
- const configPath = runtimeConfigPathFor(normalizeRuntimeName(input2.runtime) ?? input2.runtime, homeDir);
4454
- if (configPath) {
4570
+ let removed = 0;
4571
+ let reclaimedBytes = 0;
4572
+ for (const key of keys) {
4573
+ const directory = join(root, key);
4574
+ const normalized = await normalizeRuntimePath(directory);
4575
+ const referencedBy = referenced.get(normalized) ?? [];
4576
+ const kind = classifyKey(key);
4577
+ if (referencedBy.length > 0 || normalized === pin) {
4578
+ entries.push({
4579
+ directory,
4580
+ key,
4581
+ kind,
4582
+ bytes: 0,
4583
+ referencedBy,
4584
+ action: "kept",
4585
+ level: "ok",
4586
+ detail: referencedBy.length > 0 ? `kept \u2014 named by ${referencedBy.length} credential director${referencedBy.length === 1 ? "y" : "ies"} (sidecar or wrapper)` : "kept \u2014 the connector's current pinned version (what --repair installs)"
4587
+ });
4588
+ continue;
4589
+ }
4590
+ const bytes = measure ? await directoryBytes(directory) : 0;
4591
+ if (input.dryRun) {
4592
+ entries.push({
4593
+ directory,
4594
+ key,
4595
+ kind,
4596
+ bytes,
4597
+ referencedBy,
4598
+ action: "would_remove",
4599
+ level: "advisory",
4600
+ detail: `would remove \u2014 no credential directory names it (${kind}-keyed)`
4601
+ });
4602
+ continue;
4603
+ }
4455
4604
  try {
4456
- const existing = await readFile(configPath, "utf8");
4457
- if (existing.includes("bin/haven-mcp") || existing.includes(".haven/mcp-runtime")) {
4458
- return {
4459
- ok: false,
4460
- messages: [
4461
- `The config at ${configPath} is the LOCAL-stdio topology (--local). Repair currently rewrites only the hosted+signer shape and will not touch it.`,
4462
- "Re-run your original connector command (with --local) to repair a local-stdio install."
4463
- ]
4464
- };
4465
- }
4466
- } catch {
4605
+ await remove(directory);
4606
+ removed += 1;
4607
+ reclaimedBytes += bytes;
4608
+ entries.push({ directory, key, kind, bytes, referencedBy, action: "removed", level: "ok", detail: `removed \u2014 no credential directory named it (${kind}-keyed)` });
4609
+ } catch (err) {
4610
+ entries.push({
4611
+ directory,
4612
+ key,
4613
+ kind,
4614
+ bytes,
4615
+ referencedBy,
4616
+ action: "failed",
4617
+ level: "failed",
4618
+ detail: `removal failed: ${err instanceof Error ? err.message : String(err)} \u2014 a signer process may still hold it open; stop it and re-run`
4619
+ });
4467
4620
  }
4468
4621
  }
4469
- const existingSidecar = await readRuntimeSidecar(directory);
4470
- const serverName = existingSidecar?.server_name;
4471
- const signerPath = join(directory, "signer.json");
4472
- const prepared = await prepareSignerRuntime(
4473
- { credentialDirectory: directory, signerPath, homeDir, serverName },
4474
- { runCommand: deps.runCommand, env: deps.env }
4475
- );
4476
- messages.push(...prepared.messages);
4477
- const names = serverNamesFor(serverName);
4478
- messages.push(`Rewriting MCP entries ${names.hosted} / ${names.signer}${serverName ? ` (agent "${serverName}")` : " (unnamed pair)"} \u2014 no other pair is touched.`);
4479
- const configResult = await writeRuntimeConfig({
4480
- // Normalized for the WRITE too (#3145 review round 3): `writeRuntimeConfig`
4481
- // switches on the id, and the raw alias fell to its "manual runtime" arm
4482
- // — a repair that reported success while writing nothing.
4483
- runtime: normalizeRuntimeName(input2.runtime) ?? input2.runtime,
4484
- hostedMcpUrl: identity.hosted_mcp_url ?? `${identity.api_url}/mcp`,
4485
- apiKey: identity.api_key,
4486
- identityPath: join(directory, "identity.json"),
4487
- signerPath,
4488
- credentialDirectory: directory,
4489
- signerCommand: { command: prepared.command, args: prepared.args },
4490
- homeDir,
4491
- mode: "hosted",
4492
- serverName
4493
- });
4494
- messages.push(...configResult.messages);
4495
- messages.push("Repair complete \u2014 restart the runtime, then verify with --doctor.");
4496
- return { ok: true, messages };
4622
+ return { version: 1, root, dryRun: input.dryRun, entries, removed, reclaimedBytes, level: rollUpPruneLevel(entries) };
4497
4623
  }
4498
- var RERUN;
4499
- var init_doctor = __esm({
4500
- "src/doctor.ts"() {
4501
- init_prune_runtimes();
4624
+ var init_prune_runtimes = __esm({
4625
+ "src/prune-runtimes.ts"() {
4502
4626
  init_runtime_manifest();
4503
- init_probes();
4504
- init_signer_runtime();
4505
- init_runtime_spec_override();
4506
- init_config_writers();
4507
- init_runtime_registry();
4508
- init_signer_consent();
4509
- init_tombstone();
4510
- init_server_names();
4511
- init_storage();
4512
- init_redact();
4513
- RERUN = connectorRerunCommand();
4514
4627
  }
4515
4628
  });
4516
4629
 
4517
- // src/runtime.ts
4518
- init_api();
4519
- init_key();
4520
- init_redact();
4521
- init_server_names();
4522
- init_storage();
4523
- init_runtime_install();
4524
- init_runtime_registry();
4525
- init_connect_error();
4526
-
4527
- // src/installed-clients.ts
4528
- init_connect_error();
4529
- init_config_writers();
4530
- init_runtime_registry();
4531
- var SCAN_ORDER = [
4532
- "claude-code",
4533
- "codex-cli",
4534
- "cursor",
4535
- "vscode",
4536
- "vscode-insiders",
4537
- "claude-desktop",
4538
- "hermes"
4539
- ];
4540
- function installedClientTargets(homeDir = homedir(), cwd = process.cwd(), env = process.env) {
4541
- const targets = [
4542
- {
4543
- runtime: "claude-code",
4544
- label: "Claude Code",
4545
- // Claude Code is configured through its own CLI (`claude mcp add-json`),
4546
- // not by writing a file this module owns — so its evidence is the
4547
- // client directory, never a config path.
4548
- configPath: null,
4549
- markers: [join(homeDir, ".claude"), join(homeDir, ".claude.json")]
4550
- },
4551
- {
4552
- runtime: "codex-cli",
4553
- // Both Codex surfaces write the same ~/.codex/config.toml, so they are
4554
- // ONE candidate. Splitting them would ask the user to answer a question
4555
- // whose answers are the same write.
4556
- label: "Codex (CLI or Desktop)",
4557
- configPath: runtimeConfigPathFor("codex-cli", homeDir),
4558
- markers: [join(homeDir, ".codex")]
4559
- },
4560
- {
4561
- runtime: "cursor",
4562
- label: "Cursor",
4563
- configPath: runtimeConfigPathFor("cursor", homeDir),
4564
- markers: [join(homeDir, ".cursor")]
4565
- },
4566
- {
4567
- runtime: "vscode",
4568
- label: "VS Code",
4569
- configPath: runtimeConfigPathFor("vscode", homeDir),
4570
- markers: [resolve(cwd, ".vscode")]
4571
- },
4572
- {
4573
- runtime: "vscode-insiders",
4574
- label: "VS Code Insiders",
4575
- configPath: runtimeConfigPathFor("vscode-insiders", homeDir),
4576
- markers: []
4577
- },
4578
- {
4579
- runtime: "claude-desktop",
4580
- label: "Claude Desktop",
4581
- configPath: runtimeConfigPathFor("claude-desktop", homeDir),
4582
- markers: []
4583
- },
4584
- {
4585
- runtime: "hermes",
4586
- label: "Hermes Agent",
4587
- configPath: runtimeConfigPathFor("hermes", homeDir),
4588
- markers: [env.HERMES_HOME ?? join(homeDir, ".hermes")]
4589
- }
4590
- ];
4591
- return targets.filter((target) => runtimeProfile(target.runtime, {}).canWriteRuntimeConfig);
4592
- }
4593
- async function scanInstalledClients(options = {}) {
4594
- const exists = options.exists ?? pathExists;
4595
- const targets = installedClientTargets(options.homeDir, options.cwd, options.env ?? process.env);
4596
- const found = [];
4597
- for (const target of targets) {
4598
- if (target.configPath && await exists(target.configPath)) {
4599
- found.push({
4600
- runtime: target.runtime,
4601
- label: target.label,
4602
- detail: `MCP config found at ${target.configPath}`,
4603
- configPath: target.configPath,
4604
- evidence: "config-file"
4605
- });
4606
- continue;
4607
- }
4608
- for (const marker of target.markers) {
4609
- if (!await exists(marker)) continue;
4610
- found.push({
4611
- runtime: target.runtime,
4612
- label: target.label,
4613
- detail: `installed (${marker})`,
4614
- configPath: target.configPath,
4615
- evidence: "client-directory"
4616
- });
4617
- break;
4618
- }
4619
- }
4620
- return found.sort((a, b) => {
4621
- if (a.evidence !== b.evidence) return a.evidence === "config-file" ? -1 : 1;
4622
- return SCAN_ORDER.indexOf(a.runtime) - SCAN_ORDER.indexOf(b.runtime);
4630
+ // src/rekey.ts
4631
+ var rekey_exports = {};
4632
+ __export(rekey_exports, {
4633
+ finishRekey: () => finishRekey,
4634
+ startRekey: () => startRekey
4635
+ });
4636
+ async function startRekey(options, deps = {}) {
4637
+ const now = deps.now ?? (() => Date.now());
4638
+ const stored = await readStoredCredentials(
4639
+ options.serverName,
4640
+ options.agentId,
4641
+ options.credentialsDir
4642
+ );
4643
+ const api = (deps.createApi ?? ((url) => createConnectApiClient(url, void 0, CONNECTOR_CLIENT_IDENTITY)))(stored.apiUrl);
4644
+ const identity = await probeIdentity(api, stored.apiKey, "current");
4645
+ assertRekeyable(identity, stored);
4646
+ const key = (deps.generateKey ?? generateDelegateKey)();
4647
+ const startedAt = new Date(now()).toISOString();
4648
+ const expiresAt = new Date(now() + REKEY_PENDING_TTL_MS).toISOString();
4649
+ await writeRekeyPending(stored.directory, {
4650
+ agent_id: stored.agentId,
4651
+ new_delegate_address: key.address,
4652
+ new_delegate_key: key.privateKey,
4653
+ started_at: startedAt,
4654
+ expires_at: expiresAt
4623
4655
  });
4656
+ const finishCommand = [
4657
+ connectorRerunCommand("--rekey-finish"),
4658
+ options.serverName ? `--name ${options.serverName}` : void 0,
4659
+ "--api-key <the key the dashboard showed you>",
4660
+ options.runtime ? `--runtime ${options.runtime}` : "--runtime <your runtime>"
4661
+ ].filter(Boolean).join(" ");
4662
+ return {
4663
+ started: true,
4664
+ agentId: stored.agentId,
4665
+ directory: stored.directory,
4666
+ newDelegateAddress: key.address,
4667
+ expiresAt,
4668
+ messages: [
4669
+ `New signing key generated on this machine for agent ${identity.name || stored.agentId}.`,
4670
+ "",
4671
+ ` New signing address: ${key.address}`,
4672
+ "",
4673
+ "The private half stays here \u2014 Haven never receives it, and there is no way to move it",
4674
+ "between machines. That is what keeps the account non-custodial.",
4675
+ "",
4676
+ 'Next, on the Haven agent page: choose "Replace signing key" and paste that address.',
4677
+ "When it finishes it shows a new API key ONCE. Come back here and run:",
4678
+ "",
4679
+ ` ${finishCommand}`,
4680
+ "",
4681
+ `Nothing has changed yet \u2014 the agent keeps working on its old key until you finish.`,
4682
+ `This pending re-key expires ${expiresAt}.`
4683
+ ]
4684
+ };
4624
4685
  }
4625
- function installedClientHint(candidates) {
4626
- const installedClients = candidates.map((candidate) => candidate.runtime);
4627
- if (candidates.length === 1) {
4628
- return { installedClients, suggestedRuntime: candidates[0].runtime };
4629
- }
4630
- const configured = candidates.filter((candidate) => candidate.evidence === "config-file");
4631
- return configured.length === 1 ? { installedClients, suggestedRuntime: configured[0].runtime } : { installedClients };
4632
- }
4633
- var MAX_PROMPT_ATTEMPTS = 3;
4634
- async function promptForInstalledClient(candidates, io = defaultPromptIo()) {
4635
- if (candidates.length === 0) throw noInstalledClientsError();
4636
- io.write("Haven could not detect which agent runtime this is.\n");
4637
- io.write("These agent clients are installed on this machine:\n");
4638
- candidates.forEach((candidate, index) => {
4639
- io.write(` ${index + 1}) ${candidate.label} \u2014 ${candidate.detail}
4640
- `);
4641
- });
4642
- 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");
4643
- for (let attempt = 0; attempt < MAX_PROMPT_ATTEMPTS; attempt += 1) {
4644
- const answer = await io.question(`Which one? [1-${candidates.length}] (default 1 \u2014 ${candidates[0].label}): `);
4645
- if (answer === null) throw promptAbortedError("the prompt was cancelled");
4646
- const trimmed = answer.trim();
4647
- if (trimmed === "") return candidates[0].runtime;
4648
- const picked = Number.parseInt(trimmed, 10);
4649
- if (Number.isInteger(picked) && picked >= 1 && picked <= candidates.length) {
4650
- return candidates[picked - 1].runtime;
4651
- }
4652
- io.write(`"${trimmed}" is not one of 1-${candidates.length}.
4653
- `);
4686
+ async function finishRekey(options, deps = {}) {
4687
+ const now = deps.now ?? (() => Date.now());
4688
+ if (!options.newApiKey) {
4689
+ throw new Error(REKEY_FINISH_NEEDS_API_KEY);
4654
4690
  }
4655
- throw promptAbortedError(`no valid choice after ${MAX_PROMPT_ATTEMPTS} attempts`);
4656
- }
4657
- async function resolveRuntimeByInstalledClientPrompt(options = {}) {
4658
- const candidates = await scanInstalledClients(options);
4659
- if (candidates.length === 0) throw noInstalledClientsError();
4660
- return promptForInstalledClient(candidates, options.io ?? defaultPromptIo());
4661
- }
4662
- function noInstalledClientsError() {
4663
- return new ConnectError(
4664
- "runtime_no_installed_clients",
4665
- "Could not determine the agent runtime: nothing was detected in this environment, and no agent client Haven can configure is installed on this machine. Re-run with --runtime <name> naming the client you want configured, or --runtime other to store credentials and finish the MCP setup by hand.",
4666
- "rerun_connect_with_explicit_runtime"
4667
- );
4668
- }
4669
- function promptAbortedError(reason) {
4670
- return new ConnectError(
4671
- "runtime_prompt_aborted",
4672
- `Runtime not chosen (${reason}). Nothing was written: no agent was created, no credentials were stored, and the Haven setup token is still unused. Run the connector command again, or pass --runtime <name> to skip the prompt.`,
4673
- "rerun_connect_and_choose_a_runtime"
4691
+ const stored = await readStoredCredentials(
4692
+ options.serverName,
4693
+ options.agentId,
4694
+ options.credentialsDir
4674
4695
  );
4675
- }
4676
- async function pathExists(path) {
4677
- try {
4678
- await access(path);
4679
- return true;
4680
- } catch {
4681
- return false;
4696
+ const pending = await readRekeyPending(stored.directory, now());
4697
+ if (pending.agent_id !== stored.agentId) {
4698
+ throw new Error(
4699
+ `The pending re-key at ${stored.directory} belongs to agent ${pending.agent_id}, but that directory now holds ${stored.agentId}. Refusing to write a key into the wrong agent.`
4700
+ );
4682
4701
  }
4683
- }
4684
- function defaultPromptIo() {
4685
- return {
4686
- write: (text) => process.stdout.write(text),
4687
- question: (query) => new Promise((resolvePromise) => {
4688
- const rl = createInterface({ input: process.stdin, output: process.stdout });
4689
- let settled = false;
4690
- const settle = (value) => {
4691
- if (settled) return;
4692
- settled = true;
4693
- rl.close();
4694
- resolvePromise(value);
4695
- };
4696
- rl.once("SIGINT", () => settle(null));
4697
- rl.once("close", () => settle(null));
4698
- rl.question(query, (answer) => settle(answer));
4699
- })
4700
- };
4701
- }
4702
-
4703
- // src/wiring-collision.ts
4704
- init_server_names();
4705
- init_signer_runtime();
4706
- init_storage();
4707
- init_tombstone();
4708
- async function detectWiringCollision(input) {
4709
- const root = defaultCredentialRoot(input.credentialsDir);
4710
- let entries = [];
4711
- try {
4712
- entries = await readdir(root);
4713
- } catch {
4714
- return null;
4702
+ const api = (deps.createApi ?? ((url) => createConnectApiClient(url, void 0, CONNECTOR_CLIENT_IDENTITY)))(stored.apiUrl);
4703
+ const identity = await probeIdentity(api, options.newApiKey, "new");
4704
+ if (identity.id !== stored.agentId) {
4705
+ throw new Error(
4706
+ `That API key belongs to agent ${identity.id}, not ${stored.agentId}. Nothing was changed.`
4707
+ );
4715
4708
  }
4716
- const superseded = [];
4717
- const taken = /* @__PURE__ */ new Set();
4718
- for (const entry of entries) {
4719
- const directory = join(root, entry);
4720
- let identityRaw;
4721
- try {
4722
- identityRaw = await readFile(join(directory, "identity.json"), "utf8");
4723
- } catch {
4724
- continue;
4709
+ const onChain = (identity.delegate_address ?? "").toLowerCase();
4710
+ const expected = pending.new_delegate_address.toLowerCase();
4711
+ if (onChain !== expected) {
4712
+ throw new Error(
4713
+ `Haven says this agent's signing address is ${identity.delegate_address ?? "unset"}, but this machine generated ${pending.new_delegate_address}. Nothing was changed. Either the re-key on the agent page used a different address, or it has not finished yet.`
4714
+ );
4715
+ }
4716
+ await rewriteCredentialFiles({
4717
+ baseDir: options.credentialsDir,
4718
+ agentId: stored.agentId,
4719
+ serverName: options.serverName,
4720
+ apiKey: options.newApiKey,
4721
+ delegateKey: pending.new_delegate_key,
4722
+ delegateAddress: pending.new_delegate_address,
4723
+ // The stored value (already new-name-first, from the credential-FILE
4724
+ // permanent fallback) wins; the hosted identity's `account_address` is a
4725
+ // LIVE server read, which as of #2914 emits only that name.
4726
+ accountAddress: stored.accountAddress ?? identity.account_address ?? void 0,
4727
+ chainId: stored.chainId ?? identity.chain_id ?? void 0,
4728
+ network: stored.network,
4729
+ agentBudget: stored.agentBudget,
4730
+ apiUrl: stored.apiUrl,
4731
+ hostedMcpUrl: stored.hostedMcpUrl,
4732
+ x402BindingSigner: stored.x402BindingSigner,
4733
+ warn: deps.log
4734
+ });
4735
+ await clearRekeyPending(stored.directory);
4736
+ const names = serverNamesFor(options.serverName);
4737
+ const messages = [
4738
+ `Agent ${identity.name || stored.agentId} is now on its new signing key.`,
4739
+ ` Signing address: ${pending.new_delegate_address}`,
4740
+ ` Credentials: ${stored.directory} (rewritten in place)`,
4741
+ ` MCP servers: ${names.hosted} / ${names.signer} (unchanged names)`
4742
+ ];
4743
+ let configRewritten = false;
4744
+ if (options.runtime) {
4745
+ const prepared = await (deps.prepareSigner ?? prepareSignerRuntime)(
4746
+ {
4747
+ credentialDirectory: stored.directory,
4748
+ signerPath: `${stored.directory}/signer.json`,
4749
+ homeDir: options.homeDir
4750
+ },
4751
+ { runCommand: deps.runCommand, env: deps.env }
4752
+ );
4753
+ const result = await (deps.writeConfig ?? writeHostedRuntimeConfig)(
4754
+ { runCommand: deps.runCommand, homeDir: options.homeDir },
4755
+ {
4756
+ runtime: options.runtime,
4757
+ hostedMcpUrl: stored.hostedMcpUrl,
4758
+ apiKey: options.newApiKey,
4759
+ identityPath: `${stored.directory}/identity.json`,
4760
+ signerPath: `${stored.directory}/signer.json`,
4761
+ credentialDirectory: stored.directory,
4762
+ serverName: options.serverName
4763
+ },
4764
+ { command: prepared.command, args: prepared.args }
4765
+ );
4766
+ configRewritten = result.hostedConfigured;
4767
+ if (prepared.runtimeSpecOverride) {
4768
+ messages.push(
4769
+ ` Signer runtime: RUNTIME SPEC OVERRIDE ACTIVE \u2014 ${describeRuntimeSpecOverride(prepared.runtimeSpecOverride.specs)} (NOT the pinned manifest; installed into ${prepared.runtimeDirectory})`
4770
+ );
4725
4771
  }
4726
- taken.add(entry);
4727
- let identity;
4728
- try {
4729
- identity = JSON.parse(identityRaw);
4730
- } catch {
4731
- identity = void 0;
4772
+ messages.push(` Config: ${result.target}`);
4773
+ messages.push(...result.messages.map((line) => ` ${line}`));
4774
+ if (!configRewritten) {
4775
+ messages.push(
4776
+ "",
4777
+ "WARNING: the MCP config was NOT updated, so it still carries the OLD API key and every",
4778
+ `wired host will fail with 401. Fix the cause above and re-run with --runtime ${options.runtime},`,
4779
+ "or update the config by hand. The credential files on disk are already on the new key."
4780
+ );
4732
4781
  }
4733
- if (!identity?.api_key) continue;
4734
- if (await pathExists2(join(directory, TOMBSTONE_FILENAME))) continue;
4735
- const sidecar = await readRuntimeSidecar(directory);
4736
- if (sidecar?.server_name) continue;
4737
- superseded.push({ directory, agentId: identity.agent_id ?? entry });
4782
+ } else {
4783
+ messages.push(
4784
+ "",
4785
+ "NOTE: no --runtime was given, so the MCP config still carries the OLD API key and every",
4786
+ "wired host will fail with 401. Re-run with --runtime <name> to rewrite it."
4787
+ );
4738
4788
  }
4739
- if (superseded.length === 0) return null;
4740
4789
  return {
4741
- superseded,
4742
- suggestedServerName: proposeServerSlug(input.agentName, taken)
4790
+ finished: true,
4791
+ agentId: stored.agentId,
4792
+ directory: stored.directory,
4793
+ newDelegateAddress: pending.new_delegate_address,
4794
+ serverNames: { hosted: names.hosted, signer: names.signer },
4795
+ configRewritten,
4796
+ messages
4743
4797
  };
4744
4798
  }
4745
- function proposeServerSlug(agentName, taken) {
4746
- let base = agentName.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").replace(/-{2,}/g, "-").slice(0, 32).replace(/-+$/g, "");
4747
- if (!slugIsValid(base)) base = "agent";
4748
- if (!taken.has(base)) return base;
4749
- for (let n = 2; n < 1e3; n += 1) {
4750
- const suffix = `-${n}`;
4751
- const candidate = `${base.slice(0, 32 - suffix.length).replace(/-+$/g, "")}${suffix}`;
4752
- if (slugIsValid(candidate) && !taken.has(candidate)) return candidate;
4753
- }
4754
- throw new Error(`Could not propose an unused server name for ${JSON.stringify(agentName)}.`);
4755
- }
4756
- function slugIsValid(slug) {
4799
+ async function probeIdentity(api, apiKey, which) {
4757
4800
  try {
4758
- assertValidServerSlug(slug);
4759
- return true;
4760
- } catch {
4761
- return false;
4762
- }
4763
- }
4764
- var MAX_PROMPT_ATTEMPTS2 = 3;
4765
- async function promptWiringCollisionResolution(collision, agentName, io) {
4766
- const ids = collision.superseded.map((entry) => entry.agentId).join(", ");
4767
- io.write(`This machine is already wired to a Haven agent with a live key: ${ids}.
4768
- `);
4769
- io.write(`Setting up "${agentName}" on the bare haven / haven-signer pair would replace that wiring.
4770
- `);
4771
- io.write(" r) replace \u2014 re-point haven / haven-signer at the new agent and retire the previous directory locally\n");
4772
- io.write(" (tombstoned, local key files removed; you still revoke it on the Haven agent page)\n");
4773
- io.write(` a) alongside \u2014 install as a named agent (suggested: ${collision.suggestedServerName}) with its own
4774
- `);
4775
- io.write(` haven-<name> / haven-signer-<name> pair, leaving the current wiring untouched
4776
- `);
4777
- io.write(" q) quit \u2014 nothing is written and the setup token stays unused\n");
4778
- for (let attempt = 0; attempt < MAX_PROMPT_ATTEMPTS2; attempt += 1) {
4779
- const answer = await io.question("Replace, install alongside, or quit? [r/a/q]: ");
4780
- if (answer === null) return { action: "abort" };
4781
- const trimmed = answer.trim().toLowerCase();
4782
- if (trimmed === "r" || trimmed === "replace") return { action: "replace" };
4783
- if (trimmed === "q" || trimmed === "quit") return { action: "abort" };
4784
- if (trimmed === "a" || trimmed === "alongside") {
4785
- const typed = await io.question(`Server name [${collision.suggestedServerName}]: `);
4786
- if (typed === null) return { action: "abort" };
4787
- const serverName = typed.trim() === "" ? collision.suggestedServerName : typed.trim();
4788
- try {
4789
- assertValidServerSlug(serverName);
4790
- } catch (err) {
4791
- io.write(`${err instanceof Error ? err.message : String(err)}
4792
- `);
4793
- continue;
4794
- }
4795
- return { action: "alongside", serverName };
4801
+ return await api.getAgentIdentity(apiKey);
4802
+ } catch (err) {
4803
+ const status = err?.status;
4804
+ if (status === 401 || status === 403) {
4805
+ throw new Error(
4806
+ which === "current" ? "This machine's Haven API key is no longer accepted. If a re-key already finished elsewhere, run --rekey-finish with the key that re-key produced instead of starting a new one." : "Haven rejected that API key. Check you pasted the whole key from the agent page \u2014 nothing was changed."
4807
+ );
4796
4808
  }
4797
- io.write(`"${trimmed}" is not one of r, a, q.
4798
- `);
4809
+ throw new Error(
4810
+ `Could not reach Haven to check this agent (${redactSecrets(
4811
+ err instanceof Error ? err.message : String(err)
4812
+ )}). Nothing was changed.`
4813
+ );
4799
4814
  }
4800
- return { action: "abort" };
4801
4815
  }
4802
- async function pathExists2(path) {
4803
- try {
4804
- await stat(path);
4805
- return true;
4806
- } catch {
4807
- return false;
4816
+ function assertRekeyable(identity, stored) {
4817
+ if (identity.id !== stored.agentId) {
4818
+ throw new Error(
4819
+ `The credentials at ${stored.directory} say agent ${stored.agentId}, but Haven says that key belongs to ${identity.id}. Refusing to re-key an agent this directory does not own.`
4820
+ );
4821
+ }
4822
+ if (identity.execution_rail === "legacy") {
4823
+ throw new Error(
4824
+ `Agent ${identity.name || identity.id} is on the legacy rail, which cannot be re-keyed \u2014 its authority is per-token Safe allowances, not a signed delegation there is anything to re-issue. Re-onboard the agent on the delegation rail instead.`
4825
+ );
4826
+ }
4827
+ if (identity.status === "revoked") {
4828
+ throw new Error(
4829
+ `Agent ${identity.name || identity.id} is revoked. Re-keying would hand a revoked agent fresh credentials \u2014 create a new agent instead.`
4830
+ );
4808
4831
  }
4809
4832
  }
4833
+ var init_rekey = __esm({
4834
+ "src/rekey.ts"() {
4835
+ init_api();
4836
+ init_runtime_install();
4837
+ init_signer_runtime();
4838
+ init_runtime_spec_override();
4839
+ init_key();
4840
+ init_redact();
4841
+ init_rekey_messages();
4842
+ init_runtime();
4843
+ init_server_names();
4844
+ init_storage();
4845
+ }
4846
+ });
4810
4847
 
4811
- // src/runtime.ts
4812
- init_unwire();
4813
- init_local_mcp_runtime();
4814
- init_runtime_manifest();
4815
- var CONNECTOR_VERSION = "0.4.0-alpha.0";
4816
- var CONNECT_OUTCOME_SCHEMA_VERSION = 1;
4817
- var failureOutcomesByError = /* @__PURE__ */ new WeakMap();
4818
- function failureOutcomeFor(runtimeHint, error) {
4819
- if (error !== null && typeof error === "object") {
4820
- const recorded = failureOutcomesByError.get(error);
4821
- if (recorded) return recorded;
4848
+ // src/rekey-restart.ts
4849
+ var rekey_restart_exports = {};
4850
+ __export(rekey_restart_exports, {
4851
+ restartGuidance: () => restartGuidance
4852
+ });
4853
+ function restartGuidance(runtime) {
4854
+ const profile = runtime ? BY_RUNTIME[runtime] : void 0;
4855
+ const lines = ["The new key is only live in a process that started after now.", ""];
4856
+ if (profile) {
4857
+ lines.push(profile.how);
4858
+ for (const command of profile.commands) lines.push(` ${command}`);
4859
+ if (profile.commands.length > 0) lines.push("");
4860
+ } else {
4861
+ lines.push(
4862
+ runtime ? `No standard restart command is known for "${runtime}" \u2014 restart it the way you start it.` : "Pass --runtime <name> to get the restart command for a specific host."
4863
+ );
4864
+ lines.push("");
4822
4865
  }
4823
- return failedConnectOutcome(runtimeHint, error);
4866
+ lines.push(SWEEP);
4867
+ return { commands: profile?.commands ?? [], lines };
4824
4868
  }
4825
- async function runConnect(options, deps = {}) {
4826
- const trace = {};
4827
- try {
4828
- return await executeConnect(options, deps, trace);
4829
- } catch (err) {
4830
- const outcome = failedConnectOutcome(trace.runtime ?? options.runtime, err);
4831
- if (err !== null && typeof err === "object") failureOutcomesByError.set(err, outcome);
4832
- if (trace.directory) await recordConnectOutcome(deps, trace.directory, outcome);
4833
- throw err;
4869
+ var SWEEP, BY_RUNTIME;
4870
+ var init_rekey_restart = __esm({
4871
+ "src/rekey-restart.ts"() {
4872
+ SWEEP = "Then restart EVERY other long-lived MCP host on this machine \u2014 gateways, TUI workers, editors. Each holds the wiring snapshot from its own start time, so after a re-key each one is still presenting the OLD API key and will fail with 401 until it restarts.";
4873
+ BY_RUNTIME = {
4874
+ "claude-code": {
4875
+ commands: ["claude --continue"],
4876
+ how: "Exit this Claude Code session and start a new one:"
4877
+ },
4878
+ "codex-cli": {
4879
+ commands: ["codex resume --last"],
4880
+ how: "Start a fresh Codex CLI session:"
4881
+ },
4882
+ "codex-desktop": {
4883
+ commands: [],
4884
+ how: "Quit Codex Desktop completely (not just the window) and reopen it."
4885
+ },
4886
+ "claude-desktop": {
4887
+ commands: [],
4888
+ how: "Quit Claude Desktop completely (not just the window) and reopen it."
4889
+ },
4890
+ hermes: {
4891
+ commands: ["systemctl --user restart hermes-gateway", "/restart"],
4892
+ how: "Restart the Hermes gateway, or run /restart inside a Hermes session. The first form is the one that matters if you run it as a user service:"
4893
+ },
4894
+ cursor: {
4895
+ commands: [],
4896
+ how: 'Cursor hot-reloads MCP config, so it will pick the new key up on its own. If a tool call still fails with 401, reload the window (Cmd/Ctrl+Shift+P \u2192 "Reload Window").'
4897
+ },
4898
+ vscode: {
4899
+ commands: [],
4900
+ how: 'VS Code hot-reloads MCP config. If a tool call still fails with 401, reload the window (Cmd/Ctrl+Shift+P \u2192 "Reload Window").'
4901
+ },
4902
+ "vscode-insiders": {
4903
+ commands: [],
4904
+ how: 'VS Code Insiders hot-reloads MCP config. If a tool call still fails with 401, reload the window (Cmd/Ctrl+Shift+P \u2192 "Reload Window").'
4905
+ }
4906
+ };
4834
4907
  }
4908
+ });
4909
+
4910
+ // src/doctor.ts
4911
+ var doctor_exports = {};
4912
+ __export(doctor_exports, {
4913
+ describeAccountAddressKey: () => describeAccountAddressKey,
4914
+ rollUpLevel: () => rollUpLevel,
4915
+ runDoctor: () => runDoctor,
4916
+ runRepair: () => runRepair
4917
+ });
4918
+ function finalizeCheck(check) {
4919
+ return { ...check, ok: check.level !== "failed" };
4835
4920
  }
4836
- async function recordConnectOutcome(deps, directory, outcome) {
4837
- try {
4838
- return await (deps.writeOutcomeRecord ?? writeConnectOutcomeRecord)(directory, outcome);
4839
- } catch {
4840
- return void 0;
4841
- }
4921
+ function rollUpLevel(checks) {
4922
+ if (checks.some((check) => check.level === "failed")) return "failed";
4923
+ if (checks.some((check) => check.level === "advisory")) return "advisory";
4924
+ return "ok";
4842
4925
  }
4843
- async function executeConnect(options, deps, trace) {
4844
- assertSupportedNodeVersion(deps.nodeVersion, MCP_RUNTIME_MANIFEST.minimumNodeVersion);
4845
- const connectorVersion = options.connectorVersion ?? CONNECTOR_VERSION;
4846
- const api = deps.api ?? createConnectApiClient(options.apiBaseUrl);
4847
- const log = secureLogger(
4848
- deps.log ?? ((message) => process.stdout.write(`${message}
4849
- `)),
4850
- deps.redactPaths === true
4851
- );
4852
- const writeCredentials = deps.writeCredentials ?? writeCredentialFiles;
4853
- const preflightStorage = deps.preflightStorage ?? preflightCredentialStorage;
4854
- const runRuntimeInstall = deps.installRuntime ?? installRuntime;
4855
- const generateKey = deps.generateKey ?? generateDelegateKey;
4856
- const generateLocalApiKey = deps.generateApiKey ?? generateAgentApiKey;
4857
- const selection = await resolveRuntimeSelection(options.runtime, options.runtimeForce, {
4858
- env: deps.env ?? process.env,
4859
- selfReported: options.runtimeSelfReport,
4860
- promptForRuntime: runtimeSelectionPrompt(options, deps)
4861
- });
4862
- if (!selection.runtime) {
4863
- const hint = await installedClientHintFor(deps);
4864
- throw new ConnectError(
4865
- "runtime_undetermined",
4866
- `Could not determine the agent runtime: nothing was detected in this environment and no --runtime was given. If you are an AI agent running this command: re-run it once, unchanged except for adding --runtime <name>, naming the harness you are running in \u2014 one of: ${RUNTIME_FLAG_VALUES} (the aliases cowork, codex and openclaw are accepted too). Do not guess: if your harness is not one of those, use --runtime other, which stores the credentials and prints the manual MCP steps. ` + installedClientProse(hint) + "Nothing was written and the Haven setup token is still unused.",
4867
- "rerun_connect_with_explicit_runtime",
4868
- // #2091: the values must ride structurally too. The backend's setup
4869
- // prompt permits a retry only with "one of the values that refusal
4870
- // lists" — and --json discards prose, so a prose-only list deadlocked
4871
- // every automation run in an undetected runtime (Codex in the field:
4872
- // npx needs network, Codex runs network commands unsandboxed, and the
4873
- // unsandboxed path carries none of the CODEX_* detection vars).
4874
- //
4875
- // #2174: the list alone still leaves the retry a nine-value guess. The
4876
- // scan below narrows it to what is actually on this machine — as a
4877
- // HINT. It does not select, and this stays a refusal: see
4878
- // `installedClientHint`.
4879
- { allowedRuntimes: RUNTIME_FLAG_VALUE_LIST, ...hint }
4880
- );
4926
+ function runtimeFlagFor(runtime) {
4927
+ return normalizeRuntimeName(runtime) ? ` --runtime ${runtime}` : "";
4928
+ }
4929
+ function repairCommandFor(runtime, suffix = "") {
4930
+ if (normalizeRuntimeName(runtime)) return `Run: ${RERUN} --doctor --repair --runtime ${runtime}${suffix}`;
4931
+ return `Run: ${RERUN} --doctor --repair --runtime <runtime>${suffix.replace(/\.$/, "")} \u2014 --repair needs the runtime named; one of: ${RUNTIME_FLAG_VALUE_LIST.join(", ")}.`;
4932
+ }
4933
+ async function resolveDoctorRuntime(input, directory) {
4934
+ const explicit = input.runtime.trim();
4935
+ if (explicit) return { runtime: explicit, origin: "flag" };
4936
+ if (directory) {
4937
+ const recorded = await readConnectOutcomeRuntime(directory);
4938
+ if (recorded !== null && normalizeRuntimeName(recorded)) {
4939
+ return { runtime: recorded, origin: "record" };
4940
+ }
4881
4941
  }
4882
- const runtime = selection.runtime;
4883
- trace.runtime = runtime;
4884
- const installCapabilities = runtimeInstallCapabilities(runtime);
4885
- if (options.localMcp) {
4886
- if (!supportsLocalMcp(runtime)) {
4887
- throw new Error(
4888
- `--local (fully-local Haven MCP) is only available for Claude Code and Codex. The detected runtime is ${runtimeProfile(runtime).label}. Re-run without --local to use the default hosted MCP + local signer setup.`
4889
- );
4942
+ return { runtime: "", origin: "unknown" };
4943
+ }
4944
+ async function discoverCredentialDirectory(homeDir, explicit) {
4945
+ const root = explicit ? dirname(explicit) : join(homeDir, ".haven", "agents");
4946
+ let entries = [];
4947
+ try {
4948
+ entries = await readdir(root);
4949
+ } catch {
4950
+ return explicit ? { directory: explicit, others: [], parkedOnly: /* @__PURE__ */ new Set() } : { others: [], parkedOnly: /* @__PURE__ */ new Set() };
4951
+ }
4952
+ const candidates = [];
4953
+ const tombstonedOnly = [];
4954
+ const parkedOnly = [];
4955
+ for (const entry of entries) {
4956
+ const directory = join(root, entry);
4957
+ try {
4958
+ const s = await stat(join(directory, "identity.json"));
4959
+ candidates.push({ directory, mtimeMs: s.mtimeMs });
4960
+ } catch {
4961
+ try {
4962
+ await stat(join(directory, TOMBSTONE_FILENAME));
4963
+ tombstonedOnly.push(directory);
4964
+ } catch {
4965
+ try {
4966
+ await stat(join(directory, REKEY_PENDING_FILENAME));
4967
+ parkedOnly.push(directory);
4968
+ } catch {
4969
+ }
4970
+ }
4890
4971
  }
4891
4972
  }
4892
- if (selection.overrodeHint) {
4893
- log(`runtime: ${runtime} (detected; ignoring the ${selection.overrodeHint} hint \u2014 pass --runtime-force ${selection.overrodeHint} to override)`);
4973
+ const parkedOnlySet = new Set(parkedOnly);
4974
+ candidates.sort((a, b) => b.mtimeMs - a.mtimeMs);
4975
+ if (explicit) {
4976
+ return {
4977
+ directory: explicit,
4978
+ others: [...candidates.map((c) => c.directory), ...tombstonedOnly, ...parkedOnly].filter((d) => d !== explicit),
4979
+ parkedOnly: parkedOnlySet
4980
+ };
4894
4981
  }
4895
- if (selection.discardedHint) {
4896
- log(`runtime: ${runtime} (detected; "${selection.discardedHint}" is not a runtime Haven knows \u2014 valid values: ${RUNTIME_FLAG_VALUES})`);
4982
+ if (candidates.length === 0 && tombstonedOnly.length === 0 && parkedOnly.length === 0) {
4983
+ return { others: [], parkedOnly: parkedOnlySet };
4897
4984
  }
4898
- if (selection.source === "prompted") {
4899
- log(`runtime: ${runtime} (chosen at the prompt \u2014 nothing was detected in this environment)`);
4985
+ return {
4986
+ directory: candidates[0]?.directory,
4987
+ others: [...candidates.slice(1).map((c) => c.directory), ...tombstonedOnly, ...parkedOnly],
4988
+ parkedOnly: parkedOnlySet
4989
+ };
4990
+ }
4991
+ function agentIsWired(configText, names, slug, identity, sidecar, isPrimary, bareOwnerExists) {
4992
+ if (configText === null) return isPrimary;
4993
+ if (slug) {
4994
+ for (const name of [names.hosted, names.codexHosted, names.signer, names.codexSigner]) {
4995
+ if (new RegExp(`(^|[."'\\s\\[])${name}(["'\\]:\\s]|$)`, "m").test(configText)) return true;
4996
+ }
4997
+ return false;
4900
4998
  }
4901
- log("Warming up your connection to Haven\u2026");
4902
- let setup;
4903
- try {
4904
- setup = await api.resolveSetup({
4905
- setupToken: options.setupToken,
4906
- connectorVersion,
4907
- runtime
4908
- });
4909
- } catch (err) {
4910
- throw deadSetupTokenError(err) ?? err;
4999
+ if (sidecar?.wrapper_path && configText.includes(sidecar.wrapper_path)) return true;
5000
+ if (bareOwnerExists) return false;
5001
+ return isPrimary && Boolean(identity?.hosted_mcp_url && configText.includes(identity.hosted_mcp_url));
5002
+ }
5003
+ function rekeyPendingCheck(status, hostedDelegateAddress, runtime, slug) {
5004
+ return finalizeCheck(rekeyPendingVerdict(status, hostedDelegateAddress, runtime, slug));
5005
+ }
5006
+ function rekeyPendingVerdict(status, hostedDelegateAddress, runtime, slug) {
5007
+ const label = "Pending re-key";
5008
+ const nameFlag = slug ? ` --name ${slug}` : "";
5009
+ if (status.state === "unreadable") {
5010
+ return {
5011
+ id: "rekey_pending",
5012
+ label,
5013
+ level: "failed",
5014
+ detail: `A re-key was started here but ${status.path} does not parse, so neither the address it generated nor when it started can be read. The file still holds what was a private key.`,
5015
+ repair: `Delete ${status.path}, then start again: ${RERUN} --rekey${nameFlag}`
5016
+ };
4911
5017
  }
4912
- assertSetupChallengeIsUsable(setup.challenge.expires_at);
4913
- printSetupSummary(setup, log);
4914
- await preflightStorage({ baseDir: options.credentialsDir, warn: log });
4915
- if (options.serverName) {
4916
- assertValidServerSlug(options.serverName);
4917
- await assertServerSlugAvailable(options.serverName, options.credentialsDir);
5018
+ const started = status.startedAt ?? "an unknown time";
5019
+ const address = status.newDelegateAddress ?? "unknown";
5020
+ const completedOnHaven = hostedDelegateAddress !== void 0 && status.newDelegateAddress !== void 0 && hostedDelegateAddress.toLowerCase() === status.newDelegateAddress.toLowerCase();
5021
+ if (completedOnHaven) {
5022
+ return {
5023
+ id: "rekey_pending",
5024
+ label,
5025
+ level: "failed",
5026
+ detail: `A re-key started ${started} has COMPLETED on Haven \u2014 the agent's signing address is already ${address}, the one this machine generated \u2014 but the local half was never finished, so the credential files here still hold the old key. Parked at ${status.path}.` + (status.state === "expired" ? " The local file is also past its 24h TTL, which --rekey-finish refuses, so the finish command below will not accept it any more." : ""),
5027
+ repair: status.state === "expired" ? `The parked key expired. Start again \u2014 ${RERUN} --rekey${nameFlag} \u2014 and re-run "Replace signing key" on the Haven agent page with the new address it prints.` : `Run: ${RERUN} --rekey-finish${nameFlag} --api-key <the key the agent page showed you>${runtimeFlagFor(runtime)}`
5028
+ };
4918
5029
  }
4919
- log("Checked local credential storage \u2014 all clear.");
4920
- let serverName = options.serverName;
4921
- let replacing;
4922
- if (!serverName) {
4923
- const collision = await detectWiringCollision({
4924
- credentialsDir: options.credentialsDir,
4925
- agentName: setup.agent.name
4926
- });
4927
- if (collision) {
4928
- const resolution = await resolveWiringCollision(collision, setup.agent.name, options, deps);
4929
- if (resolution.action === "replace") {
4930
- replacing = collision;
4931
- log(
4932
- `Replacing the existing haven / haven-signer wiring (previous agent(s): ${supersededIds(collision)}). The previous directory is retired locally once the new wiring is written; nothing is revoked.`
4933
- );
4934
- } else {
4935
- serverName = resolution.serverName;
4936
- assertValidServerSlug(serverName);
4937
- await assertServerSlugAvailable(serverName, options.credentialsDir);
4938
- log(`Installing alongside the existing wiring as a named agent: ${serverNamesFor(serverName).hosted} / ${serverNamesFor(serverName).signer}.`);
4939
- }
4940
- }
5030
+ const wedgeNote = "Haven is NOT yet on this address, so the re-key did not complete. This machine cannot tell whether the on-chain revoke on the agent page already ran: if it did not, closing this costs nothing; if it did, the agent's old delegations are revoked, no new ones were issued, and only an owner re-grant restores its spend authority (#1868). Check the agent page before assuming the harmless case.";
5031
+ if (status.state === "expired") {
5032
+ return {
5033
+ id: "rekey_pending",
5034
+ label,
5035
+ level: "failed",
5036
+ detail: `A re-key started ${started} EXPIRED ${status.expiresAt ?? ""} without being finished. Its address was ${address}; the private half it generated is still on disk at ${status.path}. ` + wedgeNote,
5037
+ repair: `Either delete ${status.path} to drop the parked key, or start over: ${RERUN} --rekey${nameFlag}. Connect never deletes it for you \u2014 an expired TTL is a refusal to USE the key, not a licence to destroy key material you may still be mid-flow on.`
5038
+ };
4941
5039
  }
4942
- const existingAgents = await listExistingKeyedAgents(options.credentialsDir);
4943
- if (existingAgents.length > 0) {
4944
- log("");
4945
- log(
4946
- `Heads-up (before anything is written to this machine): it already carries ${existingAgents.length} agent director${existingAgents.length === 1 ? "y" : "ies"} with stored keys \u2014 ` + existingAgents.map((a) => `${a.agentId}${a.accountAddress ? ` (spends from ${shortAddress(a.accountAddress)})` : ""}`).join(", ") + ". This setup creates a NEW agent alongside them and revokes nothing."
5040
+ return {
5041
+ id: "rekey_pending",
5042
+ label,
5043
+ level: "ok",
5044
+ detail: `A re-key started ${started} is still open (expires ${status.expiresAt ?? "unknown"}). Paste this address into "Replace signing key" on the Haven agent page: ${address}. Parked at ${status.path}. ` + wedgeNote
5045
+ };
5046
+ }
5047
+ async function runtimeSpecOverrideCheck(directory, sidecar, env) {
5048
+ const facts = [];
5049
+ const installed = sidecar?.runtime_spec_override;
5050
+ if (installed) {
5051
+ facts.push(
5052
+ `signer runtime installed under ${describeRuntimeSpecOverride(installed.specs)} (resolved: ${installed.resolved_specs.join(" ")}; directory key ${installed.directory_key})`
4947
5053
  );
4948
5054
  }
4949
- const hostedNameForRun = serverNamesFor(serverName).hosted;
4950
- let reboundFrom;
4951
- const holders = (await listMcpServerBindings(options.credentialsDir)).filter(({ binding }) => binding.server_name === hostedNameForRun).sort((a, b) => a.binding.bound_at < b.binding.bound_at ? 1 : a.binding.bound_at > b.binding.bound_at ? -1 : 0);
4952
- const newest = holders[0];
4953
- if (newest) {
4954
- const { binding, directory } = newest;
4955
- const backendChanged = withoutUserinfo(binding.api_url) !== withoutUserinfo(options.apiBaseUrl);
4956
- const previousApiUrl = withoutUserinfo(binding.api_url);
4957
- reboundFrom = { server_name: binding.server_name, agent_id: binding.agent_id, api_url: previousApiUrl, bound_at: binding.bound_at, backend_changed: backendChanged };
4958
- const beingReplaced = replacing?.superseded.some((entry) => entry.directory === directory) ?? false;
4959
- log(
4960
- `Heads-up: the MCP server name '${binding.server_name}' was bound to agent ${binding.agent_id} on ${previousApiUrl} 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` : ""}). ` + (beingReplaced ? `This run replaces that wiring, as you chose, with a new agent on ${withoutUserinfo(options.apiBaseUrl)}` : `This run rebinds it to a new agent on ${withoutUserinfo(options.apiBaseUrl)}`) + (backendChanged ? " \u2014 a DIFFERENT backend: any saved session, script or document naming this MCP server now resolves to a different backend and agent." : ".")
5055
+ const mcpInstalled = await readMcpSidecarOverride(directory);
5056
+ if (mcpInstalled) {
5057
+ facts.push(
5058
+ `local MCP runtime installed under ${describeRuntimeSpecOverride(mcpInstalled.specs)} (resolved: ${mcpInstalled.resolved_specs.join(" ")}; directory key ${mcpInstalled.directory_key})`
4961
5059
  );
4962
5060
  }
4963
- const localKey = generateKey();
4964
- const localApiKey = generateLocalApiKey();
4965
- log("Minting a fresh signing key and API key \u2014 both stay on this machine.");
4966
- const proofSignature = await localKey.signChallenge(setup.challenge.message);
4967
- log("Introducing your agent to Haven\u2026");
4968
- let registration;
5061
+ let shell;
4969
5062
  try {
4970
- registration = await api.registerSetup({
4971
- setupToken: options.setupToken,
4972
- connectorVersion,
4973
- runtime,
4974
- challengeId: setup.challenge.id,
4975
- delegateAddress: localKey.address,
4976
- proofSignature,
4977
- apiKeyHash: hashAgentApiKey(localApiKey),
4978
- apiKeyPrefix: agentApiKeyPrefix(localApiKey),
4979
- // #1878: report the pair we are ACTUALLY wiring, bare pair included, so
4980
- // the dashboard can name it. Derived here rather than sent as the raw
4981
- // slug — `serverNamesFor` is the one place the naming rule lives, and
4982
- // the hosted name is what a user pastes into an MCP config.
4983
- mcpServerName: serverNamesFor(serverName).hosted,
4984
- // #2528: 'prose' is the default because it is what a caller who says
4985
- // nothing is doing — the library entry point is not a --json run.
4986
- runMode: options.runMode ?? "prose",
4987
- connectorContext: {
4988
- environment_label: options.environmentLabel ?? "Local workspace",
4989
- config_target: installCapabilities.canWriteRuntimeConfig ? "agent runtime MCP config" : "local credential files"
4990
- },
4991
- installCapabilities
4992
- });
5063
+ const active = resolveRuntimeSpecOverride(env);
5064
+ if (active) shell = `set in this shell: ${describeRuntimeSpecOverride(active)} \u2014 a --repair from here installs these, not the pin`;
4993
5065
  } catch (err) {
4994
- const dead = deadSetupTokenError(err);
4995
- if (dead) throw dead;
4996
- if (isExpiredSetupChallenge(err)) {
4997
- throw new Error(
4998
- "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."
4999
- );
5000
- }
5001
- throw err;
5066
+ shell = err instanceof RuntimeSpecOverrideError ? `set in this shell but REFUSED: ${err.message}` : `set in this shell but unreadable: ${err instanceof Error ? err.message : String(err)}`;
5002
5067
  }
5003
- log(`Registered signing address with Haven: ${shortAddress(registration.delegate_address)}.`);
5004
- log("Tucking your credentials away safely on disk\u2026");
5005
- const credentialPaths = await writeCredentials({
5006
- baseDir: options.credentialsDir,
5007
- agentId: registration.agent_id,
5008
- serverName,
5009
- apiKey: localApiKey,
5010
- delegateKey: localKey.privateKey,
5011
- delegateAddress: localKey.address,
5012
- accountAddress: setup.haven_wallet.address,
5013
- chainId: setup.haven_wallet.chain_id,
5014
- network: setup.haven_wallet.network,
5015
- agentBudget: setup.agent_budget.map((budget) => ({
5016
- token_symbol: budget.token_symbol,
5017
- allowance_amount: budget.allowance_amount,
5018
- reset_period_min: budget.reset_period_min
5019
- })),
5020
- apiUrl: options.apiBaseUrl,
5021
- hostedMcpUrl: registration.hosted_mcp_url,
5022
- x402BindingSigner: setup.x402_binding_signer ?? void 0,
5023
- warn: log
5068
+ if (shell) facts.push(shell);
5069
+ if (facts.length === 0) return void 0;
5070
+ const variables = Object.values(RUNTIME_SPEC_ENV).join(" / ");
5071
+ return finalizeCheck({
5072
+ id: "runtime_spec_override",
5073
+ label: "Runtime spec override",
5074
+ level: "failed",
5075
+ detail: `runtime spec overridden \u2014 not the pinned manifest (${MCP_RUNTIME_MANIFEST.signerPackage}@${MCP_RUNTIME_MANIFEST.signerVersion}, ${MCP_RUNTIME_MANIFEST.sdkPackage}@${MCP_RUNTIME_MANIFEST.sdkVersion}). ${facts.join(". ")}.`,
5076
+ repair: `Developer override (#2424). To return to the pinned manifest: unset ${variables}, then run ${RERUN} --doctor --repair --runtime <runtime>. If the override is intentional, this finding is the record of it.`
5024
5077
  });
5025
- trace.directory = credentialPaths.directory;
5078
+ }
5079
+ async function readMcpSidecarOverride(directory) {
5026
5080
  try {
5027
- const bindingRecord = {
5028
- version: 1,
5029
- server_name: hostedNameForRun,
5030
- signer_name: serverNamesFor(serverName).signer,
5031
- agent_id: registration.agent_id,
5032
- api_url: withoutUserinfo(options.apiBaseUrl),
5033
- // never persist `user:pass@` (#3154 doc review r2)
5034
- ...registration.hosted_mcp_url ? { hosted_mcp_url: registration.hosted_mcp_url } : {},
5035
- bound_at: (/* @__PURE__ */ new Date()).toISOString()
5036
- };
5037
- await writeMcpServerBinding(credentialPaths.directory, bindingRecord);
5081
+ const parsed = JSON.parse(await readFile(join(directory, "mcp-runtime.json"), "utf8"));
5082
+ return parsed.runtime_spec_override;
5038
5083
  } catch {
5039
- log("Could not record the MCP server-name binding locally (non-fatal; the next setup cannot see this binding).");
5084
+ return void 0;
5040
5085
  }
5041
- log(`Stored Haven identity credential locally: ${credentialPaths.identityPath}`);
5042
- log(`Stored local signer credential locally: ${credentialPaths.signerPath}`);
5043
- log(`Stored non-secret agent orientation locally: ${credentialPaths.agentPath}`);
5044
- if (setup.x402_binding_signer) {
5045
- log("Configured x402 binding signer for the local signer.");
5086
+ }
5087
+ async function readIdentity(directory) {
5088
+ try {
5089
+ return JSON.parse(await readFile(join(directory, "identity.json"), "utf8"));
5090
+ } catch {
5091
+ return void 0;
5092
+ }
5093
+ }
5094
+ function describeAccountAddressKey(identity, signerFile) {
5095
+ const files = [identity, signerFile];
5096
+ const has = (key) => files.some((f) => typeof f?.[key] === "string" && f[key].trim() !== "");
5097
+ if (has("account_address")) return "account address stored as account_address";
5098
+ if (has("safe_address")) {
5099
+ return "account address stored under the pre-#2908 name safe_address \u2014 still read; the next --rekey or setup rewrites it as account_address";
5100
+ }
5101
+ return "no account address stored";
5102
+ }
5103
+ async function checksForAgent(entry, input, deps) {
5104
+ const verdicts = await verdictsForAgent(entry, input, deps);
5105
+ return {
5106
+ checks: verdicts.checks.map(finalizeCheck),
5107
+ ...verdicts.signerCapabilities ? { signerCapabilities: verdicts.signerCapabilities } : {}
5108
+ };
5109
+ }
5110
+ async function verdictsForAgent(entry, input, deps) {
5111
+ const { directory, identity, sidecar } = entry;
5112
+ const checks = [];
5113
+ let signerCapabilities;
5114
+ let signerFile;
5115
+ try {
5116
+ const parsed = JSON.parse(await readFile(join(directory, "signer.json"), "utf8"));
5117
+ signerFile = typeof parsed === "object" && parsed !== null ? parsed : void 0;
5118
+ } catch {
5119
+ signerFile = void 0;
5120
+ }
5121
+ const credentialsOk = Boolean(identity?.api_key) && signerFile !== void 0;
5122
+ checks.push({
5123
+ id: "credentials",
5124
+ label: "Agent credentials",
5125
+ level: credentialsOk ? "ok" : "failed",
5126
+ detail: credentialsOk ? `identity.json and signer.json parse (agent ${identity?.agent_id ?? "unknown"}; ${describeAccountAddressKey(identity, signerFile)})` : "identity.json or signer.json is missing or unparseable.",
5127
+ ...credentialsOk ? {} : { repair: `Re-run the full setup with a fresh token: ${RERUN} --setup <token>.` }
5128
+ });
5129
+ if (!sidecar) {
5130
+ checks.push({
5131
+ id: "signer_runtime",
5132
+ label: "Signer runtime (preinstalled wrapper)",
5133
+ level: "failed",
5134
+ detail: "No signer-runtime.json sidecar \u2014 the pinned signer runtime was never prepared (or a pre-#1586 npx config).",
5135
+ repair: repairCommandFor(input.runtime)
5136
+ });
5137
+ } else if (sidecar.runtime_spec_override) {
5138
+ const matches = await installedRuntimeMatchesVersions(sidecar.runtime_directory, sidecar.cli_path, {
5139
+ signerVersion: sidecar.signer_version,
5140
+ sdkVersion: sidecar.sdk_version
5141
+ });
5142
+ checks.push({
5143
+ id: "signer_runtime",
5144
+ label: "Signer runtime (preinstalled wrapper)",
5145
+ level: matches ? "ok" : "failed",
5146
+ detail: matches ? `Installed ${sidecar.signer_package}@${sidecar.signer_version} at ${sidecar.runtime_directory} (override install \u2014 see runtime_spec_override)` : `Override runtime directory is stale or empty (${sidecar.runtime_directory}) \u2014 the CLI or package versions are missing.`,
5147
+ ...matches ? {} : { repair: repairCommandFor(input.runtime, " with the same HAVEN_*_SPEC variables set.") }
5148
+ });
5046
5149
  } else {
5047
- log(
5048
- "Warning: Haven did not provide an x402 binding signer, so x402 payments will not sign until HAVEN_X402_BINDING_SIGNER is set for the signer. Non-x402 payments are unaffected."
5049
- );
5150
+ const intact = await installedRuntimeMatchesVersions(sidecar.runtime_directory, sidecar.cli_path, {
5151
+ signerVersion: sidecar.signer_version,
5152
+ sdkVersion: sidecar.sdk_version
5153
+ });
5154
+ const versionOk = sidecar.signer_version === MCP_RUNTIME_MANIFEST.signerVersion;
5155
+ const ok = intact && versionOk;
5156
+ checks.push({
5157
+ id: "signer_runtime",
5158
+ label: "Signer runtime (preinstalled wrapper)",
5159
+ level: ok ? "ok" : intact ? "advisory" : "failed",
5160
+ detail: ok ? `Installed ${sidecar.signer_package}@${sidecar.signer_version} at ${sidecar.runtime_directory}` : intact ? `Installed version ${sidecar.signer_version} does not match the connector's pinned ${MCP_RUNTIME_MANIFEST.signerVersion} \u2014 intact, but outdated.` : `Runtime directory is stale or empty (${sidecar.runtime_directory}) \u2014 the CLI or package versions are missing.`,
5161
+ ...ok ? {} : { repair: repairCommandFor(input.runtime) }
5162
+ });
5050
5163
  }
5051
- const runtimeInstall = await runRuntimeInstall({
5052
- runtime,
5053
- hostedMcpUrl: registration.hosted_mcp_url,
5054
- apiKey: localApiKey,
5055
- signerPath: credentialPaths.signerPath,
5056
- identityPath: credentialPaths.identityPath,
5057
- credentialDirectory: credentialPaths.directory,
5058
- environmentLabel: options.environmentLabel ?? "Local workspace",
5059
- ackSigner: options.ackSigner,
5060
- ackLocalTools: options.ackLocalTools,
5061
- localMcp: options.localMcp,
5062
- serverName
5063
- }, {
5064
- onProgress: log,
5065
- // #1543: report "runtime configured" the moment the config write settles,
5066
- // so the dashboard can expose its budget-approval controls without
5067
- // waiting on the probes and skill install — a tail that approval does not
5068
- // depend on. Silent and best-effort: the complete report below remains
5069
- // authoritative (it overwrites these keys, adding the probe verdicts and
5070
- // skill state), so an early failure costs nothing but the head start.
5071
- onRuntimeConfigured: async (early) => {
5072
- try {
5073
- await api.updateInstallStatus(registration.setup_id, localApiKey, {
5074
- runtime: early.runtime,
5075
- connectorVersion,
5076
- runtimeMcpMode: early.runtimeMcpMode,
5077
- hostedMcpConfigured: early.hostedMcpConfigured,
5078
- localSignerConfigured: early.localSignerConfigured,
5079
- localMcpConfigured: early.localMcpConfigured,
5080
- credentialFilesWritten: true,
5081
- signerAcknowledged: early.signerAcknowledged,
5082
- localMcpAcknowledged: early.localMcpAcknowledged,
5083
- restartRequired: early.restartRequired,
5084
- nextUserAction: early.nextUserAction,
5085
- errorCode: early.errorCode ?? null,
5086
- environmentLabel: options.environmentLabel ?? "Local workspace"
5087
- });
5088
- if (!early.errorCode || early.errorCode === "manual_runtime_setup_required") {
5089
- log(approveBudgetCta(setup, registration.approval_url));
5090
- }
5091
- } catch {
5164
+ const overrideCheck = await runtimeSpecOverrideCheck(directory, sidecar, deps.env ?? process.env);
5165
+ if (overrideCheck) checks.push(overrideCheck);
5166
+ const hostedUrl = identity?.hosted_mcp_url ?? (identity?.api_url ? `${identity.api_url}/mcp` : void 0);
5167
+ if (identity?.api_key && hostedUrl) {
5168
+ const probe = await (deps.probeHosted ?? probeHostedMcpTools)(identity.api_key, hostedUrl, deps.fetch);
5169
+ checks.push({
5170
+ id: "hosted_mcp",
5171
+ label: "Hosted Haven MCP",
5172
+ level: probe.status === "ok" ? "ok" : "failed",
5173
+ detail: probe.status === "ok" ? `MCP tools endpoint is reachable (${hostedUrl}).` : `MCP tools endpoint probe failed: ${probe.status} (${hostedUrl}).`,
5174
+ ...probe.status === "ok" ? {} : {
5175
+ repair: "Check network access and runtime configuration for the hosted MCP URL, then re-run --doctor."
5092
5176
  }
5093
- }
5094
- });
5095
- printRuntimeInstall(runtimeInstall, log);
5096
- if (runtimeInstall.errorCode) {
5097
- log("Haven setup needs a couple more steps on this machine \u2014 see the notes above.");
5177
+ });
5098
5178
  } else {
5099
- log("Haven setup on this machine is complete.");
5179
+ checks.push({
5180
+ id: "hosted_mcp",
5181
+ label: "Hosted Haven MCP",
5182
+ level: "failed",
5183
+ detail: "No stored API key / hosted MCP URL to probe with.",
5184
+ repair: `Re-run the full setup: ${RERUN} --setup <token>.`
5185
+ });
5100
5186
  }
5101
- let supersededAgentsRetiredLocally;
5102
- const retiredAgentIds = [];
5103
- if (replacing) {
5104
- if (runtimeInstall.errorCode) {
5105
- supersededAgentsRetiredLocally = false;
5106
- log(
5107
- `Previous agent(s) ${supersededIds(replacing)} were NOT retired: the runtime install did not complete, so their wiring may still be the only working one. Resolve the install, then retire them with ${RERUN_HINT} --unwire <dir>.`
5108
- );
5187
+ const localDelegate = typeof signerFile?.delegate_address === "string" ? signerFile.delegate_address : void 0;
5188
+ let hostedDelegateAddress;
5189
+ if (identity?.api_key && identity.api_url) {
5190
+ const probe = await (deps.probeHostedIdentity ?? probeHostedAgentIdentity)(
5191
+ identity.api_key,
5192
+ identity.api_url,
5193
+ deps.fetch
5194
+ );
5195
+ if (probe.status === "ok") hostedDelegateAddress = probe.delegateAddress;
5196
+ if (probe.status !== "ok") {
5197
+ checks.push({
5198
+ id: "identity_match",
5199
+ label: "Hosted identity matches the local signing key",
5200
+ level: "failed",
5201
+ detail: probe.status === "unauthorized" ? "The stored API key was rejected, so the agent it authenticates as cannot be compared with the local signing key." : `Could not read the hosted identity (${probe.status}) \u2014 the comparison did not happen, so it cannot be reported as a match.`,
5202
+ repair: probe.status === "unauthorized" ? `Re-run the full setup with a fresh token: ${RERUN} --setup <token>.` : `Restore network access to the Haven API, then re-run: ${RERUN} --doctor${runtimeFlagFor(input.runtime)}`
5203
+ });
5204
+ } else if (!localDelegate) {
5205
+ checks.push({
5206
+ id: "identity_match",
5207
+ label: "Hosted identity matches the local signing key",
5208
+ level: "failed",
5209
+ detail: "signer.json holds no delegate_address to compare against the hosted identity.",
5210
+ repair: `Re-run the full setup with a fresh token: ${RERUN} --setup <token>.`
5211
+ });
5109
5212
  } else {
5110
- supersededAgentsRetiredLocally = true;
5111
- for (const entry of replacing.superseded) {
5112
- try {
5113
- await tombstoneDirectoryIfAbsent({
5114
- directory: entry.directory,
5115
- agentId: entry.agentId,
5116
- reason: "replaced by a new setup (--replace)",
5117
- replacedBy: registration.agent_id
5118
- });
5119
- await teardownLocalKeyMaterial(entry.directory, await readIdentityFile(entry.directory));
5120
- await clearMcpServerBinding(entry.directory);
5121
- retiredAgentIds.push(entry.agentId);
5122
- log(`Retired previous agent ${entry.agentId} locally: tombstoned, local key files removed.`);
5123
- } catch (err) {
5124
- supersededAgentsRetiredLocally = false;
5125
- log(`Could not retire previous agent ${entry.agentId} locally: ${err instanceof Error ? err.message : String(err)}`);
5213
+ const same = probe.delegateAddress?.toLowerCase() === localDelegate.toLowerCase();
5214
+ checks.push({
5215
+ id: "identity_match",
5216
+ label: "Hosted identity matches the local signing key",
5217
+ level: same ? "ok" : "failed",
5218
+ detail: same ? `The stored API key authenticates as the agent whose signing key is in this directory (${shortAddress(localDelegate)}).` : `MISMATCH: the stored API key authenticates as agent ${probe.agentId ?? "unknown"} with delegate ${shortAddress(probe.delegateAddress ?? "unknown")}, but signer.json here holds ${shortAddress(localDelegate)}. This runtime would quote as one agent and sign as another.`,
5219
+ ...same ? {} : {
5220
+ repair: `Re-run setup for this agent so its API key and signing key come from one run: ${RERUN} --setup <token>. Do not hand-edit either file.`
5126
5221
  }
5127
- }
5222
+ });
5128
5223
  }
5129
5224
  }
5130
- let supersededScan = null;
5131
- let supersededAgentIds = [];
5132
- try {
5133
- supersededScan = await listOtherAgentIds(options.credentialsDir, credentialPaths.directory);
5134
- supersededAgentIds = supersededScan ?? [];
5135
- if (supersededAgentsRetiredLocally === true) {
5136
- log("");
5137
- log(
5138
- `Replaced: previous agent(s) ${supersededIds(replacing)} are retired on this machine but NOT revoked \u2014 revoke them on the Haven agent page, then restart EVERY long-lived host (gateways, TUI workers, editors): each holds the MCP wiring snapshot from its own start time, and the tombstone speaks only when a stale host next probes the old path.`
5139
- );
5140
- } else if (supersededAgentIds.length > 0) {
5141
- log("");
5142
- log(
5143
- `Heads-up: this setup created a NEW agent. Your previous agent(s) \u2014 ${supersededAgentIds.join(", ")} \u2014 still exist with their own keys, and any host that was already running keeps acting as them.`
5144
- );
5145
- log(
5146
- `If you meant to replace them: revoke them on the Haven agent page, then restart EVERY long-lived host (gateways, TUI workers, editors) \u2014 each holds the MCP wiring snapshot from its own start time, so after repeated setups each can be stuck on a DIFFERENT old agent. Then remove their directories under ~/.haven/agents (or ${RERUN_HINT} --tombstone <dir> to leave a diagnostic in their place). Run ${RERUN_HINT} --doctor to check whether their keys are still live.`
5225
+ const pending = await inspectRekeyPending(directory, deps.now?.() ?? Date.now());
5226
+ if (pending) {
5227
+ checks.push(rekeyPendingCheck(pending, hostedDelegateAddress, input.runtime, sidecar?.server_name));
5228
+ }
5229
+ if (sidecar) {
5230
+ const consent = await getLocalSignerConsentStatus(join(directory, "signer.json"));
5231
+ if (!consent.acknowledged) {
5232
+ checks.push({
5233
+ id: "signer_process",
5234
+ label: "Signer stdio handshake",
5235
+ level: "failed",
5236
+ detail: "The local-tools consent is not acknowledged, so the signer refuses to start (by design).",
5237
+ repair: `Run: ${RERUN} --ack-local-tools --setup <token> (or re-run your original connector command with --ack-local-tools).`
5238
+ });
5239
+ } else {
5240
+ const probe = await (deps.probeSignerTools ?? probeLocalMcpTools)(
5241
+ sidecar.wrapper_path,
5242
+ [],
5243
+ MCP_RUNTIME_MANIFEST.requiredSignerTools
5147
5244
  );
5245
+ const experimental = probe.capabilities?.experimental ?? probe.capabilities;
5246
+ const compat = experimental?.["haven/signer-compatibility"];
5247
+ signerCapabilities = compat ? { "haven/signer-compatibility": compat } : void 0;
5248
+ const compatDetail = compat ? ` Compat: x402 expected-context v${JSON.stringify(compat.x402_expected_context_versions ?? "?")}.` : "";
5249
+ checks.push({
5250
+ id: "signer_process",
5251
+ label: "Signer stdio handshake",
5252
+ level: probe.status === "ok" ? "ok" : "failed",
5253
+ detail: probe.status === "ok" ? `Signer started, listed ${probe.toolNames?.length ?? 0} tools${probe.serverInfo?.version ? ` (v${probe.serverInfo.version})` : ""}.${compatDetail}` : `Handshake failed: ${probe.status}.`,
5254
+ ...probe.status === "ok" ? {} : { repair: repairCommandFor(input.runtime) }
5255
+ });
5148
5256
  }
5149
- } catch {
5150
- }
5151
- try {
5152
- await api.updateInstallStatus(registration.setup_id, localApiKey, {
5153
- runtime: runtimeInstall.runtime,
5154
- connectorVersion,
5155
- runtimeMcpMode: runtimeInstall.runtimeMcpMode,
5156
- hostedMcpConfigured: runtimeInstall.hostedMcpConfigured,
5157
- localSignerConfigured: runtimeInstall.localSignerConfigured,
5158
- localMcpConfigured: runtimeInstall.localMcpConfigured,
5159
- credentialFilesWritten: true,
5160
- signerAcknowledged: runtimeInstall.signerAcknowledged,
5161
- localMcpAcknowledged: runtimeInstall.localMcpAcknowledged,
5162
- activationCommandAvailable: Boolean(runtimeInstall.activationCommand),
5163
- skillInstalled: runtimeInstall.skillInstalled,
5164
- probeResult: runtimeInstall.probeResult,
5165
- restartRequired: runtimeInstall.restartRequired,
5166
- nextUserAction: runtimeInstall.nextUserAction,
5167
- errorCode: runtimeInstall.errorCode,
5168
- environmentLabel: options.environmentLabel ?? "Local workspace",
5169
- // The raw scan result, `null` and all — NOT the flattened
5170
- // `supersededAgentIds` the outcome carries. Flattening here would hand
5171
- // the dashboard the same ambiguity this field exists to remove (#2561).
5172
- supersededAgentIds: supersededScan
5257
+ } else {
5258
+ checks.push({
5259
+ id: "signer_process",
5260
+ label: "Signer stdio handshake",
5261
+ level: "failed",
5262
+ detail: "Skipped \u2014 no prepared signer runtime to probe.",
5263
+ repair: repairCommandFor(input.runtime)
5173
5264
  });
5174
- } catch (err) {
5175
- log(`Could not report install status to Haven: ${err instanceof Error ? err.message : String(err)}`);
5176
- }
5177
- let approval;
5178
- const narrateApprovalWait = options.waitForApproval === true || options.waitForApproval === void 0 && (deps.isStdoutTty ?? Boolean(process.stdout.isTTY));
5179
- if (narrateApprovalWait && !runtimeInstall.errorCode) {
5180
- approval = await waitForBudgetApproval(api, registration.setup_id, localApiKey, log, options.approvalWait);
5181
- }
5182
- printNextSteps(runtimeInstall, log, approval, registration.approval_url);
5183
- const outcome = completionOutcome({
5184
- runtimeInstall,
5185
- delegateAddress: registration.delegate_address,
5186
- hostedMcpUrl: registration.hosted_mcp_url,
5187
- supersededAgentIds,
5188
- supersededAgentsRetiredLocally,
5189
- ...replacing ? { retiredAgentIds } : {},
5190
- existingAgentsBeforeWrite: existingAgents.map((a) => ({ agent_id: a.agentId, account_address: a.accountAddress })),
5191
- ...reboundFrom ? { serverNameReboundFrom: reboundFrom } : {},
5192
- setupChallengeExpiresAt: setup.challenge.expires_at,
5193
- approvalRequired: registration.agent_status === "pending_approval",
5194
- approvalUrl: registration.approval_url
5195
- });
5196
- if (await recordConnectOutcome(deps, credentialPaths.directory, outcome)) {
5197
- log(`Saved this run's outcome to ${CONNECT_OUTCOME_FILENAME} in the agent's credential directory.`);
5198
5265
  }
5199
- return {
5200
- setupId: registration.setup_id,
5201
- agentId: registration.agent_id,
5202
- delegateAddress: registration.delegate_address,
5203
- credentialPaths,
5204
- outcome
5205
- };
5206
- }
5207
- function completionOutcome(input) {
5208
- const { runtimeInstall } = input;
5209
- const manualSetup = runtimeInstall.errorCode === "manual_runtime_setup_required";
5210
- const nextAction2 = runtimeInstall.nextUserAction;
5211
- const outcome = {
5212
- schema_version: CONNECT_OUTCOME_SCHEMA_VERSION,
5213
- outcome: runtimeInstall.errorCode ? "action_required" : "complete",
5214
- runtime: runtimeInstall.runtime,
5215
- topology: runtimeInstall.runtimeMcpMode,
5216
- configuration: {
5217
- hosted_mcp: runtimeInstall.hostedMcpConfigured,
5218
- local_signer: runtimeInstall.localSignerConfigured,
5219
- local_mcp: runtimeInstall.localMcpConfigured
5220
- },
5221
- probe: { result: runtimeInstall.probeResult },
5222
- activation: {
5223
- restart_required: runtimeInstall.restartRequired,
5224
- instruction: manualSetup ? "Finish the manual MCP setup using the secret-free references shown in normal Connect output, then start a fresh session." : runtimeProfile(runtimeInstall.runtime).activationInstruction
5225
- },
5226
- next_action: nextAction2,
5227
- approval: {
5228
- required: input.approvalRequired,
5229
- expires_at: null,
5230
- // Only when there is something to approve AND the backend supplied a
5231
- // link. Never synthesised here: the connector does not know the
5232
- // dashboard's origin, and a guessed URL is worse than none — it is the
5233
- // "do not invent one" rule the agent runbook states, applied to the
5234
- // tool rather than the agent.
5235
- ...input.approvalRequired && input.approvalUrl ? { url: input.approvalUrl } : {}
5236
- },
5237
- verification: {
5238
- tools: ["haven_get_agent", "haven_get_allowances"],
5239
- instruction: runtimeVerificationInstruction(runtimeInstall.runtime)
5240
- },
5241
- // The backend contract supplies a 20-byte address. If an unexpected
5242
- // malformed value arrives, do not echo it into an automation-facing
5243
- // record; the human log has already been redacted separately.
5244
- delegate_address: /^0x[0-9a-fA-F]{40}$/.test(input.delegateAddress) ? shortAddress(input.delegateAddress) : "[delegate-address-redacted]",
5245
- // The endpoint Connect wrote into the runtime's MCP config, verbatim — the
5246
- // same string that already sits in the user's own config file. Passed
5247
- // through the secret filter anyway: this is the automation contract, the
5248
- // value is server-supplied, and belts are cheap (the #1589 stance).
5249
- ...input.hostedMcpUrl ? { hosted_mcp_url: redactSecrets(input.hostedMcpUrl) } : {},
5250
- // Always emitted on a completed run, empty list included: "no superseded
5251
- // agents" is a fact a caller needs, and an omitted key would be
5252
- // indistinguishable from an older connector that never reported it.
5253
- superseded_agent_ids: input.supersededAgentIds ?? [],
5254
- ...input.supersededAgentsRetiredLocally !== void 0 ? { superseded_agents_retired_locally: input.supersededAgentsRetiredLocally } : {},
5255
- ...input.retiredAgentIds ? { retired_agent_ids: input.retiredAgentIds } : {},
5256
- // #3122: always emitted on a completed run (empty list included), for the
5257
- // same reason as superseded_agent_ids above.
5258
- existing_agents_before_write: input.existingAgentsBeforeWrite ?? [],
5259
- ...input.serverNameReboundFrom ? { server_name_rebound_from: input.serverNameReboundFrom } : {},
5260
- ...input.setupChallengeExpiresAt ? { setup_challenge_expires_at: input.setupChallengeExpiresAt } : {},
5261
- ...runtimeInstall.errorCode ? { error: { code: runtimeInstall.errorCode, next_action: nextAction2 } } : {}
5262
- };
5263
- return outcome;
5266
+ return { checks, ...signerCapabilities ? { signerCapabilities } : {} };
5264
5267
  }
5265
- async function installedClientHintFor(deps) {
5266
- try {
5267
- const candidates = await (deps.scanInstalledClients ?? scanInstalledClients)({ env: deps.env });
5268
- const hint = installedClientHint(candidates);
5269
- return hint.installedClients.length > 0 ? hint : {};
5270
- } catch {
5271
- return {};
5268
+ async function runDoctor(input, deps = {}) {
5269
+ const homeDir = deps.homeDir ?? homedir();
5270
+ const checks = [];
5271
+ let signerCapabilities;
5272
+ const { directory, others, parkedOnly } = await discoverCredentialDirectory(homeDir, input.credentialsDir);
5273
+ const resolution = await resolveDoctorRuntime(input, directory);
5274
+ const runtime = resolution.runtime;
5275
+ const input2 = { ...input, runtime };
5276
+ const normalizedRuntime = normalizeRuntimeName(input2.runtime);
5277
+ const configPath = runtimeConfigPathFor(normalizedRuntime ?? input2.runtime, homeDir);
5278
+ let configText = null;
5279
+ if (configPath !== null) {
5280
+ try {
5281
+ configText = await readFile(configPath, "utf8");
5282
+ } catch {
5283
+ configText = null;
5284
+ }
5272
5285
  }
5273
- }
5274
- function installedClientProse(hint) {
5275
- const found = hint.installedClients ?? [];
5276
- if (found.length === 0) return "";
5277
- const suggestion = hint.suggestedRuntime ? ` The likeliest is ${hint.suggestedRuntime}, but Haven will not choose for you \u2014 pass it yourself if it is right.` : " Haven will not choose between them for you.";
5278
- return `Haven can see these agent clients installed here, likeliest first: ${found.join(", ")}.${suggestion} `;
5279
- }
5280
- function runtimeSelectionPrompt(options, deps) {
5281
- if (!interactivePromptAllowed(options, deps)) return void 0;
5282
- return deps.promptRuntime ?? (() => resolveRuntimeByInstalledClientPrompt());
5283
- }
5284
- function interactivePromptAllowed(options, deps) {
5285
- if (options.interactive !== true) return false;
5286
- return deps.isTty ?? Boolean(process.stdin.isTTY);
5287
- }
5288
- function supersededIds(collision) {
5289
- return collision.superseded.map((entry) => entry.agentId).join(", ");
5290
- }
5291
- async function resolveWiringCollision(collision, agentName, options, deps) {
5292
- if (options.replaceExistingWiring) return { action: "replace" };
5293
- if (interactivePromptAllowed(options, deps)) {
5294
- const prompt = deps.promptWiringCollision ?? ((c, name) => promptWiringCollisionResolution(c, name, defaultPromptIo()));
5295
- const resolution = await prompt(collision, agentName);
5296
- if (resolution.action === "abort") {
5297
- throw new ConnectError(
5298
- "wiring_collision_declined",
5299
- `Setup stopped at your request: this machine is already wired to ${supersededIds(collision)} and you chose neither to replace that wiring nor to install alongside it. Nothing was written: no agent was created, no credentials were stored, and the Haven setup token is still unused. Run the connector command again with --replace to re-point haven / haven-signer at the new agent, or with --name <slug> (e.g. --name ${collision.suggestedServerName}) to install alongside.`,
5300
- "rerun_connect_with_replace_or_name",
5301
- { supersededAgentIds: collision.superseded.map((e) => e.agentId), suggestedServerName: collision.suggestedServerName }
5302
- );
5286
+ const allDirectories = directory ? [directory, ...others] : others;
5287
+ let bareOwnerExists = false;
5288
+ for (const dir of allDirectories) {
5289
+ const sidecar = await readRuntimeSidecar(dir);
5290
+ if (!sidecar?.server_name && sidecar?.wrapper_path && configText?.includes(sidecar.wrapper_path)) {
5291
+ bareOwnerExists = true;
5292
+ break;
5303
5293
  }
5304
- return resolution;
5305
5294
  }
5306
- throw new ConnectError(
5307
- "wiring_collision",
5308
- `This machine is already wired to a Haven agent with a live key (${supersededIds(collision)}), and setting up "${agentName}" on the bare haven / haven-signer pair would replace that wiring. Nothing was written and the Haven setup token is still unused. If you are an AI agent running this command: do NOT add a flag yourself \u2014 relay this to your user and stop. Your user decides: REPLACE the existing wiring (re-run the same command with --replace added, which re-points the pair at the new agent and retires the previous directory locally \u2014 they still revoke the old agent on the Haven agent page), or install ALONGSIDE it (re-run with --name <slug> added, e.g. --name ${collision.suggestedServerName}, which gives the new agent its own haven-<slug> / haven-signer-<slug> pair). Re-run only with the flag your user chooses.`,
5309
- "relay_wiring_collision_to_user",
5310
- { supersededAgentIds: collision.superseded.map((e) => e.agentId), suggestedServerName: collision.suggestedServerName }
5311
- );
5312
- }
5313
- function failedConnectOutcome(runtimeHint, error) {
5314
- const message = error instanceof Error ? error.message : "";
5315
- const code = error instanceof ConnectError ? error.code : /Node\.js >=/i.test(message) ? "unsupported_node_version" : /setup challenge.*expired|expired or invalid/i.test(message) ? "setup_challenge_expired_or_invalid" : /only available for Claude Code and Codex/i.test(message) ? "local_mcp_unsupported_runtime" : "connect_failed";
5316
- const runtime = normalizeRuntime(runtimeHint);
5317
- const nextAction2 = error instanceof ConnectError ? error.nextAction : code === "setup_challenge_expired_or_invalid" ? "return_to_haven_for_fresh_setup" : code === "unsupported_node_version" ? "install_supported_node_and_rerun_connect" : code === "local_mcp_unsupported_runtime" ? "rerun_without_local_mcp" : "review_the_safe_error_output_and_start_a_fresh_haven_setup_if_needed";
5318
- return {
5319
- schema_version: CONNECT_OUTCOME_SCHEMA_VERSION,
5320
- outcome: "failed",
5321
- runtime,
5322
- topology: "unknown",
5323
- configuration: { hosted_mcp: false, local_signer: false, local_mcp: false },
5324
- probe: { result: "not_run" },
5325
- activation: { restart_required: false, instruction: "Resolve the reported problem before activating Haven tools." },
5326
- next_action: nextAction2,
5327
- approval: { required: false, expires_at: null },
5328
- verification: {
5329
- tools: ["haven_get_agent", "haven_get_allowances"],
5330
- instruction: "After a successful setup and activation, verify only with haven_get_agent and haven_get_allowances."
5331
- },
5332
- error: {
5333
- code,
5334
- next_action: nextAction2,
5335
- // Only a ConnectError's message enters the JSON record: the vocabulary's
5336
- // prose is connector-authored and safe to serialize, while a plain
5337
- // Error can carry arbitrary server or filesystem detail (that stance is
5338
- // pinned by test). Redaction stays on as belt-and-braces; plain-Error
5339
- // runs still get their redacted message on stderr via the CLI mirror.
5340
- ...error instanceof ConnectError && message ? { message: redactForAutomation(message) } : {},
5341
- ...error instanceof ConnectError && error.details.allowedRuntimes ? { allowed_runtimes: error.details.allowedRuntimes } : {},
5342
- ...error instanceof ConnectError && error.details.installedClients?.length ? { installed_clients: error.details.installedClients } : {},
5343
- ...error instanceof ConnectError && error.details.suggestedRuntime ? { suggested_runtime: error.details.suggestedRuntime } : {},
5344
- ...error instanceof ConnectError && error.details.supersededAgentIds ? { superseded_agent_ids: error.details.supersededAgentIds } : {},
5345
- ...error instanceof ConnectError && error.details.suggestedServerName ? { suggested_name: error.details.suggestedServerName } : {}
5295
+ const inventory = [];
5296
+ const capabilitiesByDirectory = /* @__PURE__ */ new Map();
5297
+ const primaryChecksById = /* @__PURE__ */ new Map();
5298
+ for (const dir of allDirectories) {
5299
+ const identity = await readIdentity(dir);
5300
+ const sidecar = await readRuntimeSidecar(dir);
5301
+ const tombstone = await readAgentTombstone(dir);
5302
+ const slug = sidecar?.server_name;
5303
+ const names = serverNamesFor(slug);
5304
+ const rekeyPending = await inspectRekeyPending(dir, deps.now?.() ?? Date.now());
5305
+ if (!identity?.api_key) {
5306
+ const agentId = tombstone?.agent_id ?? rekeyPending?.agentId;
5307
+ inventory.push({
5308
+ ...slug ? { slug } : {},
5309
+ ...agentId ? { agentId } : {},
5310
+ directory: dir,
5311
+ // A tombstone is a deliberate record and outranks the discovery tell:
5312
+ // a retired directory that also holds a parked key stays `retired`.
5313
+ classification: tombstone ? "retired" : parkedOnly.has(dir) ? "parked" : "orphaned",
5314
+ checks: rekeyPending ? [rekeyPendingCheck(rekeyPending, void 0, input2.runtime, slug)] : [],
5315
+ ...rekeyPending ? { rekeyPending } : {}
5316
+ });
5317
+ continue;
5346
5318
  }
5347
- };
5348
- }
5349
- function printSetupSummary(setup, log) {
5350
- log(`Fetched Haven setup for ${setup.agent.name}.`);
5351
- log(`Haven wallet: ${setup.haven_wallet.name} on ${setup.haven_wallet.network}.`);
5352
- if (setup.agent_budget.length > 0) {
5353
- for (const budget of setup.agent_budget) {
5354
- log(
5355
- `Agent budget: ${budget.allowance_amount} atomic ${budget.token_symbol} / ${budget.reset_period_min} minute reset.`
5356
- );
5319
+ const wired = agentIsWired(configText, names, slug, identity, sidecar, dir === directory, bareOwnerExists);
5320
+ const entry = {
5321
+ ...slug ? { slug } : {},
5322
+ ...identity.agent_id ? { agentId: identity.agent_id } : {},
5323
+ directory: dir,
5324
+ classification: wired ? "wired" : "superseded",
5325
+ checks: [],
5326
+ ...rekeyPending ? { rekeyPending } : {}
5327
+ };
5328
+ if (wired) {
5329
+ const result = await checksForAgent({ directory: dir, identity, sidecar }, input2, deps);
5330
+ entry.checks = result.checks;
5331
+ capabilitiesByDirectory.set(dir, result.signerCapabilities);
5332
+ } else if (rekeyPending) {
5333
+ entry.checks = [rekeyPendingCheck(rekeyPending, void 0, input2.runtime, slug)];
5357
5334
  }
5335
+ inventory.push(entry);
5358
5336
  }
5359
- log(`Setup challenge expires at ${setup.challenge.expires_at}. If it expires, return to Haven for a fresh setup and rerun Connect \u2014 do not reuse or paste credentials.`);
5360
- }
5361
- function approveBudgetCta(setup, approvalUrl) {
5362
- const where = approvalUrl ? `at ${approvalUrl}` : "in the Haven dashboard";
5363
- const budgetPhrase = setup.agent_budget.length > 0 ? setup.agent_budget.map((budget) => `up to ${describeSetupBudget(budget)}`).join(", ") : void 0;
5364
- if (budgetPhrase) {
5365
- return `\u2192 Action needed: approve this agent's budget \u2014 ${budgetPhrase} from ${setup.haven_wallet.name} on ${setup.haven_wallet.network} \u2014 ${where}. The approval button is live now; setup continues here in the meantime.`;
5337
+ const wiredDirectories = inventory.filter((entry) => entry.classification === "wired").map((entry) => entry.directory);
5338
+ const primaryDirectory = input.credentialsDir ? directory : wiredDirectories.includes(directory ?? "") ? directory : wiredDirectories[0] ?? directory;
5339
+ if (primaryDirectory) {
5340
+ const primaryEntry = inventory.find((entry) => entry.directory === primaryDirectory);
5341
+ signerCapabilities = capabilitiesByDirectory.get(primaryDirectory);
5342
+ for (const check of primaryEntry?.checks ?? []) primaryChecksById.set(check.id, check);
5366
5343
  }
5367
- return `\u2192 Action needed: approve this agent's budget ${where} \u2014 the approval button is live now. Setup continues here in the meantime.`;
5368
- }
5369
- function describeSetupBudget(budget) {
5370
- return describeApprovedBudget({
5371
- token_symbol: budget.token_symbol,
5372
- token_address: budget.token_address,
5373
- amount: budget.allowance_amount,
5374
- reset_period_min: budget.reset_period_min
5375
- });
5376
- }
5377
- function assertSetupChallengeIsUsable(expiresAt) {
5378
- const expiresAtMs = Date.parse(expiresAt);
5379
- if (!Number.isNaN(expiresAtMs) && expiresAtMs > Date.now()) return;
5380
- throw new Error(
5381
- "This Haven setup challenge is expired or invalid. Return to Haven, start a fresh connection, and rerun Connect. No local credentials were written."
5382
- );
5383
- }
5384
- function deadSetupTokenError(err) {
5385
- if (!(err instanceof ConnectRequestError) || err.status !== 410 && err.status !== 401) return null;
5386
- return new ConnectError(
5387
- "setup_challenge_expired_or_invalid",
5388
- "This Haven setup token is expired or invalid \u2014 tokens are single-use and expire 30 minutes after the dashboard issues them, and a mistyped token reads the same way. Return to Haven, start a fresh connection, and run its new connector command. No local credentials were written.",
5389
- "return_to_haven_for_fresh_setup"
5390
- );
5391
- }
5392
- function isExpiredSetupChallenge(err) {
5393
- return err instanceof Error && /(?:setup )?challenge.*expir|expir.*(?:setup )?challenge/i.test(err.message);
5394
- }
5395
- function secureLogger(log, redactPaths = false) {
5396
- return (message) => {
5397
- log(redactPaths ? redactForAutomation(message) : redactSecrets(message));
5398
- };
5399
- }
5400
- function printRuntimeInstall(result, log) {
5401
- for (const message of result.messages) log(message);
5402
- if (result.localMcpConfigured) {
5403
- log("Configured local Haven MCP tools.");
5404
- } else if (result.hostedMcpConfigured) {
5405
- log("Configured hosted Haven MCP identity.");
5344
+ if (!primaryDirectory) {
5345
+ checks.push({
5346
+ id: "credentials",
5347
+ label: "Agent credentials",
5348
+ level: "failed",
5349
+ detail: "No agent credential directory with an identity.json under ~/.haven/agents.",
5350
+ repair: `Run the full setup once: ${RERUN} --setup <token from the Haven dashboard>.`
5351
+ });
5406
5352
  } else {
5407
- log("Haven MCP tools still need runtime setup.");
5353
+ const primaryIdentity = await readIdentity(primaryDirectory);
5354
+ const primarySidecar = await readRuntimeSidecar(primaryDirectory);
5355
+ if (!primaryChecksById.has("credentials")) {
5356
+ const result = await checksForAgent(
5357
+ { directory: primaryDirectory, identity: primaryIdentity, sidecar: primarySidecar },
5358
+ input2,
5359
+ deps
5360
+ );
5361
+ signerCapabilities = result.signerCapabilities;
5362
+ for (const check of result.checks) primaryChecksById.set(check.id, check);
5363
+ }
5364
+ for (const id of ["credentials", "signer_runtime", "runtime_spec_override"]) {
5365
+ const check = primaryChecksById.get(id);
5366
+ if (check) checks.push(check);
5367
+ }
5408
5368
  }
5409
- if (result.localSignerConfigured) {
5410
- log("Configured local Haven signer.");
5369
+ const runtimeOwnsNoConfig = normalizedRuntime !== null && configPath === null;
5370
+ if (configPath === null && input2.runtime !== "" && normalizedRuntime === null) {
5371
+ checks.push({
5372
+ id: "runtime_config",
5373
+ label: "Runtime MCP config",
5374
+ level: "failed",
5375
+ detail: `Runtime '${input2.runtime}' is not one the connector recognises. The runtime config was NOT checked. Re-run the doctor naming the runtime \u2014 one of: ${RUNTIME_FLAG_VALUE_LIST.join(", ")}.`,
5376
+ repair: `Re-run the doctor naming the runtime \u2014 one of: ${RUNTIME_FLAG_VALUE_LIST.join(", ")}.`
5377
+ });
5378
+ } else if (configPath === null && input2.runtime === "") {
5379
+ checks.push({
5380
+ id: "runtime_config",
5381
+ label: "Runtime MCP config",
5382
+ level: "failed",
5383
+ detail: `Runtime is unknown \u2014 no runtime flag was given and the connector's record in ${primaryDirectory ?? input.credentialsDir ?? "~/.haven/agents"} carries no resolvable ${CONNECT_OUTCOME_FILENAME} runtime. The runtime config was NOT checked. Re-run the doctor naming the runtime \u2014 one of: ${RUNTIME_FLAG_VALUE_LIST.join(", ")}.`,
5384
+ repair: `Re-run the doctor naming the runtime \u2014 one of: ${RUNTIME_FLAG_VALUE_LIST.join(", ")}.`
5385
+ });
5386
+ } else if (configPath === null) {
5387
+ checks.push({
5388
+ id: "runtime_config",
5389
+ label: "Runtime MCP config",
5390
+ level: "ok",
5391
+ 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 \u2014 skipping the file check.`
5392
+ });
5393
+ } else if (configText === null) {
5394
+ checks.push({
5395
+ id: "runtime_config",
5396
+ label: "Runtime MCP config",
5397
+ level: "failed",
5398
+ detail: `No runtime config at ${configPath}.`,
5399
+ repair: repairCommandFor(input2.runtime)
5400
+ });
5411
5401
  } else {
5412
- log("Local Haven signer still needs runtime setup.");
5402
+ const primaryIdentity = await readIdentity(primaryDirectory ?? "");
5403
+ const primarySidecar = primaryDirectory ? await readRuntimeSidecar(primaryDirectory) : null;
5404
+ const hasHaven = primaryIdentity?.hosted_mcp_url ? configText.includes(primaryIdentity.hosted_mcp_url) : configText.includes("haven");
5405
+ const signerViaNpx = configText.includes("@haven_ai/signer");
5406
+ const wrapperReferenced = primarySidecar ? configText.includes(primarySidecar.wrapper_path) : false;
5407
+ const ok = hasHaven && !signerViaNpx && (primarySidecar ? wrapperReferenced : true);
5408
+ checks.push({
5409
+ id: "runtime_config",
5410
+ label: "Runtime MCP config",
5411
+ level: ok ? "ok" : "failed",
5412
+ detail: ok ? `Config at ${configPath} references the hosted server and the prepared signer wrapper.` : signerViaNpx ? `Config at ${configPath} still launches the signer via npx \u2014 the pre-#1586 shape that cannot start under a 120s startup timeout.` : `Config at ${configPath} is missing the Haven entries${primarySidecar && !wrapperReferenced ? " (or references a different signer wrapper)" : ""}.`,
5413
+ ...ok ? {} : { repair: repairCommandFor(input2.runtime) }
5414
+ });
5413
5415
  }
5414
- }
5415
- function formatAtomicAmount(atomic, decimals) {
5416
- const s = atomic.toString().padStart(decimals + 1, "0");
5417
- const intPart = s.slice(0, s.length - decimals) || "0";
5418
- const fracPart = s.slice(s.length - decimals).replace(/0+$/, "");
5419
- return fracPart ? `${intPart}.${fracPart}` : intPart;
5420
- }
5421
- function describeResetPeriod(resetPeriodMin) {
5422
- if (resetPeriodMin === 1440) return "per day";
5423
- if (resetPeriodMin === 10080) return "per week";
5424
- if (resetPeriodMin === 43200) return "per month";
5425
- if (resetPeriodMin === 60) return "per hour";
5426
- if (resetPeriodMin === 0) return "in total";
5427
- return `every ${resetPeriodMin} minutes`;
5428
- }
5429
- function describeApprovedBudget(budget) {
5430
- const token = resolveTokenFromAddress(budget.token_address);
5431
- const amount = token ? `${formatAtomicAmount(BigInt(budget.amount), token.decimals)} ${budget.token_symbol}` : `${budget.amount} ${budget.token_symbol} (atomic units)`;
5432
- return `${amount} ${describeResetPeriod(budget.reset_period_min)}`;
5433
- }
5434
- function describeWaitBound(timeoutMs) {
5435
- if (timeoutMs >= 12e4) {
5436
- const minutes = Math.round(timeoutMs / 6e4);
5437
- return `${minutes} minutes`;
5416
+ for (const id of ["hosted_mcp", "identity_match", "rekey_pending"]) {
5417
+ const check = primaryChecksById.get(id);
5418
+ if (check) checks.push(check);
5438
5419
  }
5439
- return `${Math.round(timeoutMs / 1e3)}s`;
5440
- }
5441
- async function waitForBudgetApproval(api, setupId, apiKey, log, options = {}) {
5442
- const intervalMs = options.intervalMs ?? 5e3;
5443
- const timeoutMs = options.timeoutMs ?? 18e4;
5444
- const sleep = options.sleep ?? ((ms) => new Promise((resolve10) => setTimeout(resolve10, ms)));
5445
- const maxPolls = Math.max(1, Math.floor(timeoutMs / intervalMs));
5446
- const remindEvery = Math.max(1, Math.floor(3e4 / intervalMs));
5447
- let waitingAnnounced = false;
5448
- const announceWaiting = () => {
5449
- if (waitingAnnounced) return;
5450
- waitingAnnounced = true;
5451
- log("Now waiting for you to approve the budget in the Haven dashboard \u2014 approval is what unlocks the agent's Haven tools\u2026");
5452
- };
5453
- for (let i = 0; i < maxPolls; i++) {
5454
- if (i > 0) await sleep(intervalMs);
5455
- let status;
5456
- try {
5457
- status = await api.getConnectorStatus(setupId, apiKey);
5458
- } catch (err) {
5459
- if (err instanceof ConnectRequestError && (err.status === 401 || err.status === 404)) {
5460
- log("This setup ended in Haven \u2014 start a fresh connection from the dashboard when ready.");
5461
- return "ended";
5420
+ const otherEntries = inventory.filter((entry) => entry.directory !== primaryDirectory);
5421
+ if (otherEntries.length > 0) {
5422
+ const live = [];
5423
+ const revoked = [];
5424
+ const unverifiable = [];
5425
+ const retired = [];
5426
+ for (const entry of otherEntries) {
5427
+ const identity = await readIdentity(entry.directory);
5428
+ const tombstone = await readAgentTombstone(entry.directory);
5429
+ const otherAgent = entry.agentId ?? basename(entry.directory);
5430
+ if (!identity?.api_key || !identity.api_url) {
5431
+ if (tombstone) retired.push(`${otherAgent} (retired ${tombstone.retired_at})`);
5432
+ else unverifiable.push(`${otherAgent} (no stored key/API URL to probe)`);
5433
+ continue;
5462
5434
  }
5463
- announceWaiting();
5464
- continue;
5465
- }
5466
- if (status.status === "active") {
5467
- log(
5468
- status.approved_budget ? `Budget approved \u{1F389} \u2014 I can now spend up to ${describeApprovedBudget(status.approved_budget)} from your Haven wallet.` : "Budget approved \u{1F389} \u2014 the agent can now spend within its Haven rules."
5435
+ const suffix = tombstone ? " [tombstoned \u2014 key material still present]" : "";
5436
+ const probe = await (deps.probeHostedIdentity ?? probeHostedAgentIdentity)(
5437
+ identity.api_key,
5438
+ identity.api_url,
5439
+ deps.fetch
5469
5440
  );
5470
- return "approved";
5471
- }
5472
- if (status.status === "cancelled" || status.status === "expired" || status.status === "failed") {
5473
- log(`This setup ended in Haven (${status.status}) \u2014 start a fresh connection from the dashboard when ready.`);
5474
- return "ended";
5441
+ if (probe.status === "ok") live.push({ label: `${otherAgent}${suffix}`, entry });
5442
+ else if (probe.status === "unauthorized") revoked.push(`${otherAgent}${suffix}`);
5443
+ else unverifiable.push(`${otherAgent} (${probe.status})${suffix}`);
5475
5444
  }
5476
- announceWaiting();
5477
- if (i > 0 && i % remindEvery === 0) {
5478
- const elapsedSeconds = Math.round(i * intervalMs / 1e3);
5479
- log(
5480
- `Still waiting for budget approval in Haven \u2014 ${elapsedSeconds}s elapsed, checking every ${Math.round(intervalMs / 1e3)}s. I'll stop waiting after ${describeWaitBound(timeoutMs)}; you can approve later and the tools unlock then.`
5445
+ const parts = [];
5446
+ if (live.length > 0) parts.push(`STILL SPEND-CAPABLE: ${live.map((item) => item.label).join(", ")}`);
5447
+ if (revoked.length > 0) parts.push(`already revoked: ${revoked.join(", ")}`);
5448
+ if (retired.length > 0) parts.push(`tombstoned (keys removed): ${retired.join(", ")}`);
5449
+ if (unverifiable.length > 0) parts.push(`could not verify: ${unverifiable.join(", ")}`);
5450
+ const knownIds = new Set([...inventory].map((e) => e.agentId ?? basename(e.directory)));
5451
+ const ledgerDir = input.credentialsDir ? tombstonesDirForAgentDirectory(input.credentialsDir, homeDir) : join(homeDir, ".haven", "tombstones");
5452
+ const ghostRecords = (await readTombstoneRecords(ledgerDir)).filter(
5453
+ (rec) => !knownIds.has(rec.agent_id)
5454
+ );
5455
+ if (ghostRecords.length > 0) {
5456
+ parts.push(
5457
+ `retired records (dir removed): ${ghostRecords.map((rec) => `${rec.agent_id} (${rec.reason})`).join(", ")}`
5481
5458
  );
5482
5459
  }
5460
+ const supersededLive = live.filter((item) => item.entry.classification !== "wired").map((item) => item.label);
5461
+ const classificationUnreliable = configText === null && runtimeOwnsNoConfig;
5462
+ const supersededLevel = supersededLive.length === 0 ? "ok" : classificationUnreliable ? "advisory" : "failed";
5463
+ checks.push({
5464
+ id: "superseded_agents",
5465
+ label: "Superseded agent credentials",
5466
+ level: supersededLevel,
5467
+ detail: supersededLevel === "failed" ? `${otherEntries.length} other credential dir(s) found \u2014 ${parts.join("; ")}. A host started before your latest setup keeps authenticating (and spending) as the old agent.` : supersededLevel === "advisory" ? `${otherEntries.length} other credential dir(s) found \u2014 ${parts.join("; ")}. Runtime '${input2.runtime}' has no config file the connector can read, so which of these agents are wired cannot be verified from this machine: a live key here may be an agent you use deliberately, or one a host started before your latest setup is still spending as.` : `${otherEntries.length} other credential dir(s) found \u2014 ${parts.join("; ")}.`,
5468
+ ...supersededLevel === "failed" ? {
5469
+ repair: `Revoke ${supersededLive.join(", ")} on the Haven agent page, then remove the old director(y/ies) under ~/.haven/agents. Connect never revokes or deletes for you.`
5470
+ } : supersededLevel === "advisory" ? {
5471
+ repair: `Check ${supersededLive.join(", ")} on the Haven agent page: revoke the ones you no longer use, then remove their director(y/ies) under ~/.haven/agents. Connect never revokes or deletes for you.`
5472
+ } : {}
5473
+ });
5483
5474
  }
5484
- log(
5485
- "Budget approval is still pending in Haven. Approve it in the dashboard whenever you are ready \u2014 the agent tools unlock the moment you do. Verify later with the read-only haven_get_agent tool."
5486
- );
5487
- return "pending";
5488
- }
5489
- function completionHandoffLines(result, approval, approvalUrl) {
5490
- const approveStep = approvalUrl ? `Approve the budget at ${approvalUrl}. Approval \u2014 not restarting \u2014 unlocks Haven tools.` : "Return to Haven and approve the budget. Approval \u2014 not restarting \u2014 unlocks Haven tools.";
5491
- if (result.errorCode === "manual_runtime_setup_required") {
5492
- return [
5493
- "Next steps:",
5494
- `1. ${approveStep}`,
5495
- "2. Finish the manual MCP setup using the secret-free file references printed above, then start a fresh session in your runtime.",
5496
- `3. ${runtimeVerificationInstruction(result.runtime)}`
5497
- ];
5475
+ const bindings = (await Promise.all(
5476
+ inventory.filter((entry) => entry.classification !== "retired").map(async (entry) => ({ entry, binding: await readMcpServerBinding(entry.directory) }))
5477
+ )).filter((item) => item.binding !== null);
5478
+ const byName = /* @__PURE__ */ new Map();
5479
+ for (const item of bindings) {
5480
+ const list = byName.get(item.binding.server_name) ?? [];
5481
+ list.push(item);
5482
+ byName.set(item.binding.server_name, list);
5498
5483
  }
5499
- if (result.errorCode) {
5500
- return [
5501
- "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."
5502
- ];
5484
+ const rebound = [...byName.entries()].filter(([, items]) => items.length > 1);
5485
+ if (rebound.length > 0) {
5486
+ const parts = rebound.map(([name, items]) => {
5487
+ 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);
5488
+ const backends = new Set(ordered.map((i) => withoutUserinfo(i.binding.api_url)));
5489
+ return `'${name}': ` + ordered.map((i) => `${i.binding.agent_id} on ${withoutUserinfo(i.binding.api_url)} at ${i.binding.bound_at} [${i.entry.classification}]`).join(" \u2192 ") + (backends.size > 1 ? " (BACKEND CHANGED)" : "");
5490
+ });
5491
+ checks.push({
5492
+ id: "mcp_server_name_rebound",
5493
+ label: "MCP server names bound more than once",
5494
+ level: "advisory",
5495
+ detail: `${rebound.length} MCP server name${rebound.length === 1 ? "" : "s"} changed hands on this machine (locally recorded bindings; the backend's own record is the authority for the same backend): ${parts.join("; ")}. A saved session, script or document naming the server may still mean the earlier agent.`,
5496
+ repair: `Retire the earlier director(y/ies) with ${RERUN} --unwire <dir> to release the name, or keep both and address them by --name.`
5497
+ });
5503
5498
  }
5504
- if (approval === "ended") {
5505
- return [
5506
- "Next step: this setup ended in Haven before the budget was approved, so there is nothing left to approve on it \u2014 start a fresh connection from the dashboard when ready."
5507
- ];
5499
+ const parkedElsewhere = inventory.filter((entry) => entry.directory !== primaryDirectory && entry.rekeyPending).map((entry) => ({ entry, pending: entry.rekeyPending }));
5500
+ if (parkedElsewhere.length > 0) {
5501
+ const abandoned = parkedElsewhere.filter((item) => item.pending.state !== "pending");
5502
+ const describe = (item) => `${item.entry.slug ?? item.entry.agentId ?? basename(item.entry.directory)} (${item.pending.state}, ${item.pending.path})`;
5503
+ checks.push({
5504
+ id: "rekey_pending_elsewhere",
5505
+ label: "Parked re-keys in other credential directories",
5506
+ level: abandoned.length === 0 ? "ok" : "failed",
5507
+ detail: abandoned.length > 0 ? `ABANDONED re-key key material outside the agent this report describes: ${abandoned.map(describe).join(", ")}. Each holds a private key that was generated for a re-key nobody finished.` : `${parkedElsewhere.length} other director(y/ies) hold an open pending re-key: ${parkedElsewhere.map(describe).join(", ")}.`,
5508
+ ...abandoned.length > 0 ? {
5509
+ repair: "Check the Haven agent page for each before deleting: if its on-chain revoke already ran, the agent has no spend authority until you re-grant it (#1868), and that is not visible from this machine. Connect never deletes key material for you."
5510
+ } : {}
5511
+ });
5508
5512
  }
5509
- const profile = runtimeProfile(result.runtime);
5510
- const activation = activationInstructionWithWhy(profile);
5511
- if (approval === "approved") {
5512
- return [
5513
- "Next steps \u2014 the budget is already approved, so there is nothing more to do in Haven:",
5514
- `1. ${activation}`,
5515
- `2. ${runtimeVerificationInstruction(result.runtime)}`
5516
- ];
5513
+ const signerProcess = primaryChecksById.get("signer_process");
5514
+ if (signerProcess) checks.push(signerProcess);
5515
+ const prune = await (deps.pruneSignerRuntimes ?? pruneSignerRuntimes)({ dryRun: true, measure: false }, { homeDir, credentialsDir: input.credentialsDir });
5516
+ const unused = prune.entries.filter((entry) => entry.action === "would_remove");
5517
+ if (unused.length > 0) {
5518
+ checks.push({
5519
+ id: "signer_runtime_unused",
5520
+ label: "Unused signer-runtime directories",
5521
+ level: "advisory",
5522
+ detail: `${unused.length} signer-runtime director${unused.length === 1 ? "y" : "ies"} under ${prune.root} that no credential directory names: ${unused.map((entry) => entry.key).join(", ")}. Nothing is broken; they are left over from earlier pins or overrides (sizes: --prune-signer-runtimes --dry-run).`,
5523
+ repair: `Run: ${RERUN} --prune-signer-runtimes (add --dry-run to list only).`
5524
+ });
5517
5525
  }
5518
- return [
5519
- "Next steps:",
5520
- `1. ${approveStep}`,
5521
- `2. ${activation}`,
5522
- `3. ${runtimeVerificationInstruction(result.runtime)}`
5523
- ];
5526
+ if (resolution.origin === "record") {
5527
+ const rc = checks.find((check) => check.id === "runtime_config");
5528
+ if (rc) {
5529
+ rc.detail += ` (Resolved '${resolution.runtime}' from ${join(directory ?? "", CONNECT_OUTCOME_FILENAME)}; pass --runtime to check a different one.)`;
5530
+ }
5531
+ }
5532
+ const restart = normalizedRuntime === null ? false : restartRequiredForRuntime(input2.runtime, deps.env);
5533
+ checks.push({
5534
+ id: "restart",
5535
+ label: "Runtime restart",
5536
+ level: "ok",
5537
+ detail: restart ? "This runtime loads MCP config at startup \u2014 restart it after any repair before expecting the tools to appear." : input2.runtime === "" ? "Runtime is unknown \u2014 whether a restart is needed cannot be determined. Re-run the doctor naming the runtime for a definitive answer." : "No restart requirement known for this runtime."
5538
+ });
5539
+ const wiredChecks = inventory.filter((entry) => entry.classification === "wired").flatMap((entry) => entry.checks);
5540
+ const finalChecks = checks.map(finalizeCheck);
5541
+ const level = rollUpLevel([...finalChecks, ...wiredChecks]);
5542
+ return {
5543
+ version: 1,
5544
+ ok: level !== "failed",
5545
+ level,
5546
+ runtime: input2.runtime,
5547
+ credentialDirectory: primaryDirectory,
5548
+ checks: finalChecks,
5549
+ agents: inventory,
5550
+ ...signerCapabilities ? { signerCapabilities } : {}
5551
+ };
5524
5552
  }
5525
- function activationInstructionWithWhy(profile) {
5526
- if (profile.restartMode === "restart-session") {
5527
- return `${profile.activationInstruction} (The entries are already written and verified \u2014 ${profile.label} only reads MCP config when a session starts, which is why this step is still needed.)`;
5553
+ async function runRepair(input, deps = {}) {
5554
+ const homeDir = deps.homeDir ?? homedir();
5555
+ const messages = [];
5556
+ const { directory, others } = await discoverCredentialDirectory(homeDir, input.credentialsDir);
5557
+ if (others.length > 0) {
5558
+ messages.push(`Note: ${others.length} other agent credential dir(s) exist \u2014 run --doctor for their status.`);
5528
5559
  }
5529
- if (profile.restartMode === "restart-app") {
5530
- return `${profile.activationInstruction} (The entries are already written and verified \u2014 ${profile.label} only reads MCP config at app launch, which is why this step is still needed.)`;
5560
+ if (!directory) {
5561
+ return {
5562
+ ok: false,
5563
+ messages: [`No agent credentials found to repair \u2014 run the full setup: ${RERUN} --setup <token>.`]
5564
+ };
5531
5565
  }
5532
- return profile.activationInstruction;
5533
- }
5534
- var RERUN_HINT = connectorRerunCommand();
5535
- async function listExistingKeyedAgents(baseDir) {
5536
- const root = defaultCredentialRoot(baseDir);
5537
- let entries = [];
5538
- try {
5539
- entries = await readdir(root);
5540
- } catch {
5541
- return [];
5566
+ const resolution = await resolveDoctorRuntime(input, directory);
5567
+ if (resolution.origin === "record") {
5568
+ messages.push(`Runtime not given \u2014 resolved '${resolution.runtime}' from ${join(directory, CONNECT_OUTCOME_FILENAME)}.`);
5542
5569
  }
5543
- const out = [];
5544
- for (const entry of entries) {
5545
- const directory = join(root, entry);
5546
- try {
5547
- const identity = JSON.parse(await readFile(join(directory, "identity.json"), "utf8"));
5548
- if (typeof identity.api_key !== "string" || identity.api_key.length === 0) continue;
5549
- let agent = {};
5550
- try {
5551
- agent = JSON.parse(await readFile(join(directory, "agent.json"), "utf8"));
5552
- } catch {
5553
- }
5554
- const { accountAddress } = readStoredAccountAddress(identity, agent);
5555
- out.push({ agentId: typeof identity.agent_id === "string" ? identity.agent_id : entry, directory, accountAddress: accountAddress ?? null });
5556
- } catch {
5557
- }
5570
+ const runtime = resolution.runtime;
5571
+ const input2 = { ...input, runtime };
5572
+ if (runtime === "") {
5573
+ return {
5574
+ ok: false,
5575
+ messages: [
5576
+ "Runtime is unknown \u2014 no runtime flag was given and the connector record carries no resolvable runtime.",
5577
+ `Repair rewrites the runtime config, so it will not guess. Re-run repair naming the runtime \u2014 one of: ${RUNTIME_FLAG_VALUE_LIST.join(", ")}.`
5578
+ ]
5579
+ };
5558
5580
  }
5559
- return out;
5560
- }
5561
- async function listOtherAgentIds(baseDir, currentDirectory) {
5562
- const root = defaultCredentialRoot(baseDir);
5563
- let entries = [];
5581
+ let identity;
5564
5582
  try {
5565
- entries = await readdir(root);
5583
+ identity = JSON.parse(await readFile(join(directory, "identity.json"), "utf8"));
5566
5584
  } catch {
5567
- return null;
5585
+ return { ok: false, messages: ["identity.json is unreadable \u2014 re-run the full setup with a fresh token."] };
5568
5586
  }
5569
- const ids = [];
5570
- for (const entry of entries) {
5571
- if (join(root, entry) === currentDirectory) continue;
5572
- const identityPath = join(root, entry, "identity.json");
5573
- try {
5574
- await stat(identityPath);
5575
- } catch {
5576
- continue;
5577
- }
5587
+ if (!identity.api_key || !(identity.hosted_mcp_url || identity.api_url)) {
5588
+ return { ok: false, messages: ["identity.json lacks the stored API key / hosted URL \u2014 re-run the full setup."] };
5589
+ }
5590
+ const configPath = runtimeConfigPathFor(normalizeRuntimeName(input2.runtime) ?? input2.runtime, homeDir);
5591
+ if (configPath) {
5578
5592
  try {
5579
- const identity = JSON.parse(await readFile(identityPath, "utf8"));
5580
- ids.push(identity.agent_id ?? entry);
5593
+ const existing = await readFile(configPath, "utf8");
5594
+ if (existing.includes("bin/haven-mcp") || existing.includes(".haven/mcp-runtime")) {
5595
+ return {
5596
+ ok: false,
5597
+ messages: [
5598
+ `The config at ${configPath} is the LOCAL-stdio topology (--local). Repair currently rewrites only the hosted+signer shape and will not touch it.`,
5599
+ "Re-run your original connector command (with --local) to repair a local-stdio install."
5600
+ ]
5601
+ };
5602
+ }
5581
5603
  } catch {
5582
- ids.push(entry);
5583
5604
  }
5584
5605
  }
5585
- return ids;
5586
- }
5587
- function printNextSteps(result, log, approval, approvalUrl) {
5588
- for (const line of completionHandoffLines(result, approval, approvalUrl)) log(line);
5606
+ const existingSidecar = await readRuntimeSidecar(directory);
5607
+ const serverName = existingSidecar?.server_name;
5608
+ const signerPath = join(directory, "signer.json");
5609
+ const prepared = await prepareSignerRuntime(
5610
+ { credentialDirectory: directory, signerPath, homeDir, serverName },
5611
+ { runCommand: deps.runCommand, env: deps.env }
5612
+ );
5613
+ messages.push(...prepared.messages);
5614
+ const names = serverNamesFor(serverName);
5615
+ messages.push(`Rewriting MCP entries ${names.hosted} / ${names.signer}${serverName ? ` (agent "${serverName}")` : " (unnamed pair)"} \u2014 no other pair is touched.`);
5616
+ const configResult = await writeRuntimeConfig({
5617
+ // Normalized for the WRITE too (#3145 review round 3): `writeRuntimeConfig`
5618
+ // switches on the id, and the raw alias fell to its "manual runtime" arm
5619
+ // — a repair that reported success while writing nothing.
5620
+ runtime: normalizeRuntimeName(input2.runtime) ?? input2.runtime,
5621
+ hostedMcpUrl: identity.hosted_mcp_url ?? `${identity.api_url}/mcp`,
5622
+ apiKey: identity.api_key,
5623
+ identityPath: join(directory, "identity.json"),
5624
+ signerPath,
5625
+ credentialDirectory: directory,
5626
+ signerCommand: { command: prepared.command, args: prepared.args },
5627
+ homeDir,
5628
+ mode: "hosted",
5629
+ serverName
5630
+ });
5631
+ messages.push(...configResult.messages);
5632
+ messages.push("Repair complete \u2014 restart the runtime, then verify with --doctor.");
5633
+ return { ok: true, messages };
5589
5634
  }
5635
+ var RERUN;
5636
+ var init_doctor = __esm({
5637
+ "src/doctor.ts"() {
5638
+ init_prune_runtimes();
5639
+ init_runtime_manifest();
5640
+ init_probes();
5641
+ init_signer_runtime();
5642
+ init_runtime_spec_override();
5643
+ init_config_writers();
5644
+ init_runtime_registry();
5645
+ init_signer_consent();
5646
+ init_tombstone();
5647
+ init_server_names();
5648
+ init_storage();
5649
+ init_redact();
5650
+ RERUN = connectorRerunCommand();
5651
+ }
5652
+ });
5590
5653
 
5591
5654
  // src/args.ts
5655
+ init_runtime();
5592
5656
  init_server_names();
5593
5657
  init_rekey_messages();
5594
5658
  function parseArgs(argv, env = process.env) {
@@ -5753,8 +5817,10 @@ function parseArgs(argv, env = process.env) {
5753
5817
  return { options, help, json, doctor, repair, tombstone, rekey, unwire, unwireDir };
5754
5818
  }
5755
5819
  if (doctor || repair) {
5756
- if (!options.runtime) {
5757
- throw new Error("--doctor/--repair need --runtime <runtime> (which config to examine).");
5820
+ if (repair && !options.runtime?.trim()) {
5821
+ throw new Error(
5822
+ "--repair needs --runtime <runtime>: it rewrites that runtime's config, so the runtime is named explicitly rather than inherited from the setup record. --doctor alone resolves it from the record."
5823
+ );
5758
5824
  }
5759
5825
  return { options, help, json, doctor, repair, tombstone, rekey };
5760
5826
  }
@@ -5805,9 +5871,12 @@ function helpText() {
5805
5871
  " --json Emit one versioned, secret-free result object on stdout; progress stays on stderr.",
5806
5872
  " --doctor Diagnose an existing setup (read-only, no token): config, credentials,",
5807
5873
  " signer runtime, hosted MCP, and a live signer handshake. Exits non-zero only on a failed check; an advisory (!) exits 0.",
5874
+ " --runtime is optional: without it the doctor checks the runtime the setup recorded,",
5875
+ " and reports a failure (not a pass) when no record names one.",
5808
5876
  " --repair Repair, then re-diagnose (implies --doctor): reinstall the pinned signer",
5809
5877
  " runtime, rewrite the wrapper and runtime config from stored credentials.",
5810
5878
  " Hosted topology only (refuses to touch a --local config). No keys, no token.",
5879
+ " Requires --runtime <runtime>: it rewrites that config, so the runtime is never inherited.",
5811
5880
  " --rekey Replace this agent's signing key (no token). Generates a fresh keypair HERE and",
5812
5881
  " prints its public address to paste into the Haven agent page. Nothing changes",
5813
5882
  " until you finish; the agent keeps working on its old key throughout.",
@@ -5856,6 +5925,8 @@ function requireValue(argv, index, option) {
5856
5925
  init_api();
5857
5926
  init_key();
5858
5927
  init_redact();
5928
+ init_runtime();
5929
+ init_runtime();
5859
5930
  init_redact();
5860
5931
  init_connect_error();
5861
5932
  function failSubcommand(io, json, err, envelope, fallback) {
@@ -5912,7 +5983,7 @@ async function runCli(argv, io = {
5912
5983
  return 0;
5913
5984
  }
5914
5985
  if (parsed.tombstone) {
5915
- const { writeAgentTombstone: writeAgentTombstone2 } = await Promise.resolve().then(() => (init_tombstone(), tombstone_exports));
5986
+ const { writeAgentTombstone: writeAgentTombstone2, tombstonesDirForAgentDirectory: tombstonesDirForAgentDirectory2 } = await Promise.resolve().then(() => (init_tombstone(), tombstone_exports));
5916
5987
  const { readFile: readFile15 } = await import('fs/promises');
5917
5988
  const { join: join13 } = await import('path');
5918
5989
  try {
@@ -5924,11 +5995,16 @@ async function runCli(argv, io = {
5924
5995
  agentId = identity.agent_id ?? "unknown";
5925
5996
  } catch {
5926
5997
  }
5998
+ const ledgerDir = tombstonesDirForAgentDirectory2(parsed.tombstone.directory);
5927
5999
  const info = await writeAgentTombstone2({
5928
6000
  directory: parsed.tombstone.directory,
5929
6001
  agentId,
5930
6002
  reason: parsed.tombstone.reason ?? "retired by operator via --tombstone",
5931
- replacedBy: parsed.tombstone.replacedBy
6003
+ replacedBy: parsed.tombstone.replacedBy,
6004
+ // #3251: the ledger of the root that holds the retired directory —
6005
+ // ~/.haven/agents/<x> → ~/.haven/tombstones, exactly as before; a
6006
+ // directory under any other root → <root>/.tombstones.
6007
+ tombstonesDir: ledgerDir
5932
6008
  });
5933
6009
  if (parsed.json) {
5934
6010
  io.stdout(`${redactSecrets(JSON.stringify({ tombstoned: true, ...info }))}
@@ -5940,11 +6016,18 @@ async function runCli(argv, io = {
5940
6016
  "Key files were NOT touched and nothing was revoked \u2014 revoke the agent on the Haven agent page if you have not already.\n"
5941
6017
  );
5942
6018
  io.stdout(
5943
- `A surviving tombstone record was mirrored to ${redactSecrets(info.recordPath)}
6019
+ info.recordPath !== null ? `A surviving tombstone record was mirrored to ${redactSecrets(info.recordPath)}
6020
+ ` : (
6021
+ // #3259: the directory IS tombstoned; only the surviving copy failed.
6022
+ redactSecrets(
6023
+ `! The surviving tombstone record could NOT be written to ${ledgerDir} (${info.mirrorError}). The in-place TOMBSTONE.json stands, but --doctor will not list this retirement once the directory is deleted.
5944
6024
  `
6025
+ )
6026
+ )
5945
6027
  );
5946
6028
  io.stdout(
5947
- "Restart EVERY long-lived MCP host (gateway, TUI workers, editors): each holds the wiring snapshot from its own start time, and the tombstone only speaks when a stale host next probes the old path. The mirrored record keeps this retirement observable even after the agent directory itself is deleted.\n"
6029
+ "Restart EVERY long-lived MCP host (gateway, TUI workers, editors): each holds the wiring snapshot from its own start time, and the tombstone only speaks when a stale host next probes the old path." + // #3259 review: never claim a copy that the line above says was not written.
6030
+ (info.recordPath !== null ? " The mirrored record keeps this retirement observable even after the agent directory itself is deleted." : "") + "\n"
5948
6031
  );
5949
6032
  }
5950
6033
  return 0;
@@ -5957,11 +6040,13 @@ async function runCli(argv, io = {
5957
6040
  }
5958
6041
  if (parsed.unwire) {
5959
6042
  const { unwireAgent: unwireAgent2 } = await Promise.resolve().then(() => (init_unwire(), unwire_exports));
6043
+ const { tombstonesDirForAgentDirectory: tombstonesDirForAgentDirectory2 } = await Promise.resolve().then(() => (init_tombstone(), tombstone_exports));
5960
6044
  const { homedir: homedir11 } = await import('os');
5961
6045
  const { join: join13 } = await import('path');
5962
6046
  const homeDir = homedir11();
5963
6047
  const root = parsed.options.credentialsDir ?? join13(homeDir, ".haven", "agents");
5964
6048
  const directory = parsed.unwireDir ?? (parsed.options.serverName ? join13(root, parsed.options.serverName) : root);
6049
+ const ledgerDir = tombstonesDirForAgentDirectory2(directory, homeDir);
5965
6050
  try {
5966
6051
  const result = await unwireAgent2({
5967
6052
  directory,
@@ -5969,7 +6054,14 @@ async function runCli(argv, io = {
5969
6054
  reason: parsed.unwire.reason,
5970
6055
  replacedBy: parsed.unwire.replacedBy,
5971
6056
  destroyKeyMaterial: parsed.unwire.destroyKeyMaterial,
5972
- homeDir
6057
+ homeDir,
6058
+ // #3251: the ledger of the root that holds the directory being
6059
+ // retired. Derived from the RESOLVED directory, not from
6060
+ // --credentials-dir: `--unwire --credentials-dir <path>` names the agent
6061
+ // directory itself, not a root. ~/.haven/agents/<slug> →
6062
+ // ~/.haven/tombstones, exactly as before; any other root →
6063
+ // <root>/.tombstones.
6064
+ tombstonesDir: ledgerDir
5973
6065
  });
5974
6066
  const failures = result.runtimes.filter((r) => r.status === "refused" || r.status === "unreadable");
5975
6067
  const retained = result.teardown.status === "retained";
@@ -5982,6 +6074,8 @@ async function runCli(argv, io = {
5982
6074
  slug: result.slug ?? null,
5983
6075
  directory: result.directory,
5984
6076
  tombstoned: result.tombstoned,
6077
+ // #3259: additive — present only when the surviving ledger record failed.
6078
+ ...result.mirrorError !== void 0 ? { mirror_error: result.mirrorError } : {},
5985
6079
  runtimes: result.runtimes.map((r) => ({
5986
6080
  runtime: r.runtime,
5987
6081
  label: r.label,
@@ -6007,6 +6101,12 @@ async function runCli(argv, io = {
6007
6101
  io.stdout(
6008
6102
  result.tombstoned ? " \xB7 Tombstoned first: any long-lived host still resolving the old wrapper gets the HAVEN-TOMBSTONE diagnosis.\n" : " \xB7 Directory was already tombstoned.\n"
6009
6103
  );
6104
+ if (result.mirrorError !== void 0) {
6105
+ io.stdout(redactSecrets(
6106
+ ` ! Surviving tombstone record: NOT written to ${ledgerDir} (${result.mirrorError}) \u2014 the in-place tombstone stands; --doctor will not list this retirement once the directory is deleted.
6107
+ `
6108
+ ));
6109
+ }
6010
6110
  for (const r of result.runtimes) {
6011
6111
  const mark = r.status === "removed" ? "\u2713" : r.status === "clean" ? "\u2013" : "\u2717";
6012
6112
  io.stdout(redactSecrets(` ${mark} ${r.label}: ${r.status}${r.detail ? ` \u2014 ${r.detail}` : ""}
@@ -6259,6 +6359,7 @@ init_runtime_install();
6259
6359
  init_signer_runtime();
6260
6360
  init_runtime_registry();
6261
6361
  init_connect_error();
6362
+ init_installed_clients();
6262
6363
  init_storage();
6263
6364
  init_runtime_manifest();
6264
6365