@haven_ai/connect 0.0.0-dev.202609250737.3bd5a51 → 0.0.0-dev.202609251409.98ed67a

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