@haven_ai/connect 0.1.28-alpha.0 → 0.1.30-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,17 +1,18 @@
1
1
  #!/usr/bin/env node
2
+ import crypto from 'crypto';
3
+ import { Wallet } from 'ethers';
4
+ import { mkdir, rm, stat, readdir, readFile, chmod, access, writeFile, unlink, rename } from 'fs/promises';
5
+ import { homedir, platform } from 'os';
6
+ import { join, resolve, dirname, basename } from 'path';
2
7
  import { ensureConsent, computeConsentHash, loadCredentials, consentInputFromClient, registeredToolNames, MCP_VERSION } from '@haven_ai/mcp';
3
8
  import { ensureSignerConsent, computeSignerConsentHash, loadSignerCredentials, createEdgeSigner, toolSchemas } from '@haven_ai/signer';
4
- import { isSupportedNodeVersion, unsupportedNodeVersionMessage, SKILL_FOLDER_NAME, resolveTokenFromAddress, HAVEN_SKILL_MD, HAVEN_SKILL_BODY_MD, HAVEN_MINIMUM_NODE_VERSION } from '@haven_ai/sdk';
5
- import { mkdir, rm, chmod, access, writeFile, readFile, unlink, readdir, stat } from 'fs/promises';
6
- import { homedir, platform } from 'os';
7
- import { join, resolve, dirname } from 'path';
9
+ import { isSupportedNodeVersion, SKILL_FOLDER_NAME, resolveTokenFromAddress, HAVEN_SKILL_MD, HAVEN_SKILL_BODY_MD, HAVEN_MINIMUM_NODE_VERSION, unsupportedNodeVersionMessage } from '@haven_ai/sdk';
8
10
  import { parseDocument, isMap, stringify } from 'yaml';
9
11
  import { execFile, spawn } from 'child_process';
10
12
  import { promisify } from 'util';
11
13
  import { realpathSync } from 'fs';
12
14
  import { fileURLToPath, pathToFileURL } from 'url';
13
- import crypto from 'crypto';
14
- import { Wallet } from 'ethers';
15
+ import { createInterface } from 'readline';
15
16
 
16
17
  var __defProp = Object.defineProperty;
17
18
  var __getOwnPropNames = Object.getOwnPropertyNames;
@@ -22,125 +23,605 @@ var __export = (target, all) => {
22
23
  for (var name in all)
23
24
  __defProp(target, name, { get: all[name], enumerable: true });
24
25
  };
25
- function mcpPackageSpec() {
26
- return `${MCP_RUNTIME_MANIFEST.mcpPackage}@${MCP_RUNTIME_MANIFEST.mcpVersion}`;
27
- }
28
- function sdkPackageSpec() {
29
- return `${MCP_RUNTIME_MANIFEST.sdkPackage}@${MCP_RUNTIME_MANIFEST.sdkVersion}`;
26
+
27
+ // src/api.ts
28
+ function createConnectApiClient(baseUrl, fetchImpl = fetch) {
29
+ const root = baseUrl.replace(/\/+$/, "");
30
+ return {
31
+ resolveSetup: (input) => request(fetchImpl, `${root}/agent-connection-setups/resolve`, {
32
+ method: "POST",
33
+ body: JSON.stringify({
34
+ setup_token: input.setupToken,
35
+ connector_version: input.connectorVersion,
36
+ runtime: input.runtime
37
+ })
38
+ }),
39
+ registerSetup: (input) => request(fetchImpl, `${root}/agent-connection-setups/register`, {
40
+ method: "POST",
41
+ body: JSON.stringify({
42
+ setup_token: input.setupToken,
43
+ challenge_id: input.challengeId,
44
+ delegate_address: input.delegateAddress,
45
+ proof_signature: input.proofSignature,
46
+ api_key_hash: input.apiKeyHash,
47
+ api_key_prefix: input.apiKeyPrefix,
48
+ runtime: input.runtime,
49
+ connector_version: input.connectorVersion,
50
+ mcp_server_name: input.mcpServerName,
51
+ connector_context: input.connectorContext,
52
+ install_capabilities: input.installCapabilities && {
53
+ can_write_runtime_config: input.installCapabilities.canWriteRuntimeConfig,
54
+ restart_required: input.installCapabilities.restartRequired
55
+ }
56
+ })
57
+ }),
58
+ getAgentIdentity: (apiKey) => request(fetchImpl, `${root}/machine-payments/agent`, {
59
+ method: "GET",
60
+ headers: { Authorization: `Bearer ${apiKey}` }
61
+ }),
62
+ getConnectorStatus: (setupId, apiKey) => request(fetchImpl, `${root}/agent-connection-setups/${encodeURIComponent(setupId)}/connector-status`, {
63
+ method: "GET",
64
+ headers: { Authorization: `Bearer ${apiKey}` }
65
+ }),
66
+ updateInstallStatus: async (setupId, apiKey, input) => {
67
+ await request(fetchImpl, `${root}/agent-connection-setups/${encodeURIComponent(setupId)}/install-status`, {
68
+ method: "POST",
69
+ headers: { Authorization: `Bearer ${apiKey}` },
70
+ body: JSON.stringify({
71
+ runtime: input.runtime,
72
+ connector_version: input.connectorVersion,
73
+ runtime_mcp_mode: input.runtimeMcpMode,
74
+ hosted_mcp_configured: input.hostedMcpConfigured,
75
+ local_signer_configured: input.localSignerConfigured,
76
+ local_mcp_configured: input.localMcpConfigured,
77
+ credential_files_written: input.credentialFilesWritten,
78
+ signer_acknowledged: input.signerAcknowledged,
79
+ local_mcp_acknowledged: input.localMcpAcknowledged,
80
+ activation_command_available: input.activationCommandAvailable,
81
+ skill_installed: input.skillInstalled,
82
+ probe_result: input.probeResult,
83
+ restart_required: input.restartRequired,
84
+ next_user_action: input.nextUserAction,
85
+ error_code: input.errorCode ?? null,
86
+ environment_label: input.environmentLabel
87
+ })
88
+ });
89
+ }
90
+ };
30
91
  }
31
- function signerPackageSpec() {
32
- return `${MCP_RUNTIME_MANIFEST.signerPackage}@${MCP_RUNTIME_MANIFEST.signerVersion}`;
92
+ async function request(fetchImpl, url, init) {
93
+ const response = await fetchImpl(url, {
94
+ ...init,
95
+ headers: {
96
+ "Content-Type": "application/json",
97
+ ...init.headers ?? {}
98
+ }
99
+ });
100
+ const text = await response.text();
101
+ const body = text ? JSON.parse(text) : null;
102
+ if (!response.ok) {
103
+ const message = body?.error ?? body?.message ?? `${response.status} ${response.statusText}`;
104
+ throw new ConnectRequestError(`Haven setup request failed: ${message}`, response.status);
105
+ }
106
+ return body;
33
107
  }
34
- var MCP_RUNTIME_MANIFEST;
35
- var init_runtime_manifest = __esm({
36
- "src/runtime-manifest.ts"() {
37
- MCP_RUNTIME_MANIFEST = {
38
- mcpPackage: "@haven_ai/mcp",
39
- mcpVersion: MCP_VERSION,
40
- sdkPackage: "@haven_ai/sdk",
41
- sdkVersion: "0.1.28-alpha.0",
42
- signerPackage: "@haven_ai/signer",
43
- signerVersion: "0.1.28-alpha.0",
44
- // Sourced from the SDK, never a literal (#1161). This field read '20.0.0'
45
- // while every package's `engines` said `>=24` and the docs said `>=24.0.0`,
46
- // so the guard that was supposed to enforce the floor waved Node v23 through
47
- // — including on the `--local` path where it does run. A hand-maintained
48
- // second copy of a number is a drift waiting to happen; a guard test pins
49
- // this against `package.json`'s `engines.node`.
50
- minimumNodeVersion: HAVEN_MINIMUM_NODE_VERSION,
51
- supportedClients: ["codex-cli", "codex-desktop", "claude-code"],
52
- requiredTools: registeredToolNames(),
53
- /**
54
- * The signer MCP's tool surface, DERIVED from the pinned @haven_ai/signer
55
- * package (#1587) — same anti-drift rule as `requiredTools` above: a
56
- * literal list here would rot the first time the signer gains a tool.
57
- * The handshake probe requires all of them.
58
- */
59
- requiredSignerTools: Object.keys(toolSchemas)
108
+ var ConnectRequestError;
109
+ var init_api = __esm({
110
+ "src/api.ts"() {
111
+ ConnectRequestError = class extends Error {
112
+ constructor(message, status) {
113
+ super(message);
114
+ this.status = status;
115
+ this.name = "ConnectRequestError";
116
+ }
117
+ status;
60
118
  };
61
119
  }
62
120
  });
63
- async function writeRuntimeConfig(input, deps = {}) {
64
- switch (input.runtime) {
65
- case "codex-cli":
66
- case "codex-desktop":
67
- return writeCodexConfig(input);
68
- case "cursor":
69
- return writeJsonRuntimeConfig(input, cursorConfigPath(input.homeDir), "mcpServers");
70
- case "vscode":
71
- return writeJsonRuntimeConfig(input, vscodeConfigPath(input.homeDir), "servers");
72
- case "vscode-insiders":
73
- return writeJsonRuntimeConfig(input, vscodeInsidersConfigPath(input.homeDir), "servers");
74
- case "claude-desktop":
75
- return writeJsonRuntimeConfig(input, claudeDesktopConfigPath(input.homeDir), "mcpServers");
76
- case "hermes":
77
- return writeHermesConfig(input, deps);
78
- default:
79
- return {
80
- hostedConfigured: false,
81
- signerConfigured: false,
82
- localMcpConfigured: false,
83
- runtimeMcpMode: "manual",
84
- target: "manual runtime setup",
85
- changed: false,
86
- restartRequired: true,
87
- messages: ["Runtime config needs to be added manually for this agent environment."],
88
- errorCode: "manual_runtime_setup_required"
89
- };
121
+ function generateDelegateKey() {
122
+ return delegateKeyFromPrivateKey(Wallet.createRandom().privateKey);
123
+ }
124
+ function delegateKeyFromPrivateKey(privateKey) {
125
+ const wallet = new Wallet(privateKey);
126
+ return {
127
+ privateKey: wallet.privateKey,
128
+ address: wallet.address,
129
+ signChallenge: (message) => wallet.signMessage(message)
130
+ };
131
+ }
132
+ function generateAgentApiKey() {
133
+ return `sk_agent_${crypto.randomBytes(24).toString("hex")}`;
134
+ }
135
+ function hashAgentApiKey(apiKey) {
136
+ return crypto.createHash("sha256").update(apiKey).digest("hex");
137
+ }
138
+ function agentApiKeyPrefix(apiKey) {
139
+ return apiKey.slice(0, 12);
140
+ }
141
+ var init_key = __esm({
142
+ "src/key.ts"() {
90
143
  }
144
+ });
145
+
146
+ // src/redact.ts
147
+ function redactSecrets(value) {
148
+ return value.replace(API_KEY_RE, "sk_agent_[redacted]").replace(PRIVATE_KEY_RE, "0x[redacted-private-key]");
91
149
  }
92
- function buildHostedServer(hostedMcpUrl, apiKey, runtime) {
93
- if (runtime === "vscode" || runtime === "vscode-insiders") {
150
+ function shortAddress(address) {
151
+ if (!/^0x[0-9a-fA-F]{40}$/.test(address)) return address;
152
+ return `${address.slice(0, 6)}...${address.slice(-4)}`;
153
+ }
154
+ var API_KEY_RE, PRIVATE_KEY_RE;
155
+ var init_redact = __esm({
156
+ "src/redact.ts"() {
157
+ API_KEY_RE = /sk_agent_[A-Za-z0-9]+/g;
158
+ PRIVATE_KEY_RE = /0x[0-9a-fA-F]{64}/g;
159
+ }
160
+ });
161
+
162
+ // src/server-names.ts
163
+ function assertValidServerSlug(slug) {
164
+ if (slug.length === 0 || slug.length > 32 || !SLUG_RE.test(slug)) {
165
+ throw new Error(
166
+ `Invalid server name ${JSON.stringify(slug)}: use 1-32 lowercase letters, digits, and single hyphens (e.g. "research").`
167
+ );
168
+ }
169
+ if (slug === "haven" || slug === "haven-signer") {
170
+ throw new Error(
171
+ `Invalid server name ${JSON.stringify(slug)}: "haven" and "haven-signer" are the unnamed pair's own names \u2014 omit --name for the bare pair.`
172
+ );
173
+ }
174
+ if (slug === "signer" || slug.startsWith("signer-")) {
175
+ throw new Error(
176
+ `Invalid server name ${JSON.stringify(slug)}: "signer" and "signer-*" are reserved \u2014 they would collide with another pair's haven-signer-* entry.`
177
+ );
178
+ }
179
+ }
180
+ function serverNamesFor(slug) {
181
+ if (slug === void 0) {
94
182
  return {
95
- type: "http",
96
- url: hostedMcpUrl,
97
- headers: { Authorization: `Bearer ${apiKey}` }
183
+ hosted: "haven",
184
+ signer: "haven-signer",
185
+ // Historical Codex table names — every wired Codex host has these.
186
+ codexHosted: "haven",
187
+ codexSigner: "haven_signer",
188
+ hermesEnvKey: "MCP_HAVEN_API_KEY"
98
189
  };
99
190
  }
191
+ assertValidServerSlug(slug);
100
192
  return {
101
- url: hostedMcpUrl,
102
- headers: { Authorization: `Bearer ${apiKey}` }
193
+ hosted: `haven-${slug}`,
194
+ signer: `haven-signer-${slug}`,
195
+ // Hyphens are valid TOML bare keys, so named Codex tables match the
196
+ // JSON/YAML names instead of inheriting the legacy underscore.
197
+ codexHosted: `haven-${slug}`,
198
+ codexSigner: `haven-signer-${slug}`,
199
+ hermesEnvKey: `MCP_HAVEN_${slug.toUpperCase().replace(/-/g, "_")}_API_KEY`
103
200
  };
104
201
  }
105
- function resolveSignerLaunchSpec(input) {
106
- return input.signerCommand ?? {
107
- command: "npx",
108
- args: ["-y", signerPackageSpec(), "--credentials", input.signerPath]
202
+ var SLUG_RE;
203
+ var init_server_names = __esm({
204
+ "src/server-names.ts"() {
205
+ SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
206
+ }
207
+ });
208
+ async function preflightCredentialStorage(input = {}) {
209
+ const directory = defaultCredentialRoot(input.baseDir);
210
+ await mkdir(directory, { recursive: true, mode: 448 });
211
+ await restrictPermissions(directory, 448, input.warn);
212
+ const probePath = join(directory, `.haven-connect-preflight-${crypto.randomBytes(8).toString("hex")}`);
213
+ try {
214
+ await writeOwnerOnlyJson(probePath, { ok: true }, input.warn);
215
+ } finally {
216
+ await rm(probePath, { force: true }).catch(() => void 0);
217
+ }
218
+ return directory;
219
+ }
220
+ async function writeCredentialFiles(input) {
221
+ const directory = defaultAgentDirectory(input.serverName ?? input.agentId, input.baseDir);
222
+ await mkdir(directory, { recursive: true, mode: 448 });
223
+ await restrictPermissions(directory, 448, input.warn);
224
+ const identityPath = join(directory, "identity.json");
225
+ const signerPath = join(directory, "signer.json");
226
+ const agentPath = join(directory, "agent.json");
227
+ await assertDoesNotExist(identityPath);
228
+ await assertDoesNotExist(signerPath);
229
+ await assertDoesNotExist(agentPath);
230
+ await writeOwnerOnlyJson(signerPath, signerPayload(input), input.warn);
231
+ try {
232
+ await writeOwnerOnlyJson(identityPath, identityPayload(input), input.warn);
233
+ } catch (err) {
234
+ await rm(signerPath, { force: true }).catch(() => void 0);
235
+ throw err;
236
+ }
237
+ try {
238
+ await writeOwnerOnlyJson(agentPath, agentPayload(input), input.warn);
239
+ } catch (err) {
240
+ await rm(signerPath, { force: true }).catch(() => void 0);
241
+ await rm(identityPath, { force: true }).catch(() => void 0);
242
+ await rm(agentPath, { force: true }).catch(() => void 0);
243
+ throw err;
244
+ }
245
+ return { directory, identityPath, signerPath, agentPath };
246
+ }
247
+ function signerPayload(input) {
248
+ return {
249
+ delegate_key: input.delegateKey,
250
+ delegate_address: input.delegateAddress,
251
+ agent_id: input.agentId,
252
+ safe_address: input.safeAddress,
253
+ chain_id: input.chainId,
254
+ network: input.network,
255
+ x402_binding_signer: input.x402BindingSigner,
256
+ note: "Local signer credential. Haven backend never receives this private key."
109
257
  };
110
258
  }
111
- function buildSignerServer(spec, runtime) {
112
- const server = {
113
- command: spec.command,
114
- args: spec.args
259
+ function identityPayload(input) {
260
+ return {
261
+ api_key: input.apiKey,
262
+ agent_id: input.agentId,
263
+ safe_address: input.safeAddress,
264
+ chain_id: input.chainId,
265
+ network: input.network,
266
+ api_url: input.apiUrl,
267
+ hosted_mcp_url: input.hostedMcpUrl,
268
+ agent_budget: input.agentBudget,
269
+ note: "Haven API key identifies the agent only. It cannot spend without the local signer key and on-chain Haven wallet rules."
115
270
  };
116
- if (runtime === "vscode" || runtime === "vscode-insiders") return { type: "stdio", ...server };
117
- return server;
118
271
  }
119
- function mergeJsonMcpConfig(existingJson, serverRoot, hostedServer, signerServer) {
120
- const config = existingJson?.trim() ? parseJsonObject(existingJson) : {};
121
- const existingRoot = config[serverRoot];
122
- const servers = existingRoot && typeof existingRoot === "object" && !Array.isArray(existingRoot) ? existingRoot : {};
123
- config[serverRoot] = {
124
- ...servers,
125
- haven: hostedServer,
126
- "haven-signer": signerServer
272
+ function agentPayload(input) {
273
+ return {
274
+ agent_id: input.agentId,
275
+ delegate_address: input.delegateAddress,
276
+ safe_address: input.safeAddress,
277
+ chain_id: input.chainId,
278
+ network: input.network,
279
+ agent_budget: input.agentBudget,
280
+ note: "Non-secret orientation for the agent: public delegate/Haven wallet identity + configured budget. Contains no API key or signing key. For the live remaining budget, call haven_get_allowances."
127
281
  };
128
- return `${JSON.stringify(config, null, 2)}
129
- `;
130
282
  }
131
- function mergeHermesYaml(existingYaml, hostedServer, signerServer) {
132
- if (!existingYaml?.trim()) return renderHermesYaml({ haven: hostedServer, "haven-signer": signerServer });
133
- const doc = parseDocument(existingYaml, { keepSourceTokens: true });
134
- if (doc.errors.length > 0 || !isMap(doc.contents)) {
135
- throw new Error("Hermes config must be a YAML object");
283
+ async function readStoredCredentials(serverName, agentIdOrSlug, baseDir) {
284
+ const key = serverName ?? agentIdOrSlug;
285
+ const directory = key ? defaultAgentDirectory(key, baseDir) : await discoverSoleAgentDirectory(baseDir);
286
+ const identity = await readJsonFile(join(directory, "identity.json"));
287
+ if (!identity) {
288
+ throw new Error(
289
+ `No Haven credentials at ${directory}. Nothing to re-key \u2014 connect this agent first, or pass the --name you wired it under.`
290
+ );
136
291
  }
137
- const mcpPair = doc.contents.items.find((item) => item.key?.toString() === "mcp_servers");
138
- const existingServers = mcpPair && isMap(mcpPair.value) ? mcpPair.value.toJSON() : {};
139
- const servers = isRecord(existingServers) ? existingServers : {};
292
+ const agent = await readJsonFile(join(directory, "agent.json")) ?? {};
293
+ const signer = await readJsonFile(join(directory, "signer.json")) ?? {};
294
+ const agentId = asString(identity.agent_id);
295
+ const apiKey = asString(identity.api_key);
296
+ const apiUrl = asString(identity.api_url);
297
+ const hostedMcpUrl = asString(identity.hosted_mcp_url);
298
+ if (!agentId || !apiKey || !apiUrl || !hostedMcpUrl) {
299
+ throw new Error(
300
+ `The credential set at ${directory} is incomplete (identity.json is missing agent_id, api_key, api_url or hosted_mcp_url). Re-key cannot rebuild it \u2014 reconnect the agent instead.`
301
+ );
302
+ }
303
+ return {
304
+ directory,
305
+ agentId,
306
+ apiKey,
307
+ apiUrl,
308
+ hostedMcpUrl,
309
+ delegateAddress: asString(agent.delegate_address) ?? asString(signer.delegate_address),
310
+ safeAddress: asString(identity.safe_address) ?? asString(agent.safe_address),
311
+ chainId: typeof identity.chain_id === "number" ? identity.chain_id : void 0,
312
+ network: asString(identity.network),
313
+ x402BindingSigner: asString(signer.x402_binding_signer),
314
+ agentBudget: Array.isArray(identity.agent_budget) ? identity.agent_budget : void 0
315
+ };
316
+ }
317
+ async function discoverSoleAgentDirectory(baseDir) {
318
+ const root = defaultCredentialRoot(baseDir);
319
+ let entries = [];
320
+ try {
321
+ entries = await readdir(root);
322
+ } catch {
323
+ throw new Error(`No Haven credentials found under ${root}. Connect an agent on this machine first.`);
324
+ }
325
+ const candidates = [];
326
+ for (const entry of entries) {
327
+ const directory = join(root, entry);
328
+ if (!await readJsonFile(join(directory, "identity.json"))) continue;
329
+ if (await readJsonFile(join(directory, "TOMBSTONE.json"))) continue;
330
+ candidates.push(directory);
331
+ }
332
+ if (candidates.length === 1) return candidates[0];
333
+ if (candidates.length === 0) {
334
+ throw new Error(`No Haven credentials found under ${root}. Connect an agent on this machine first.`);
335
+ }
336
+ throw new Error(
337
+ `Several agents are wired on this machine, so --rekey cannot tell which one you mean:
338
+ ` + candidates.map((d) => ` ${d}`).join("\n") + "\nRe-run with --name <slug> to pick one."
339
+ );
340
+ }
341
+ async function rewriteCredentialFiles(input) {
342
+ const directory = defaultAgentDirectory(input.serverName ?? input.agentId, input.baseDir);
343
+ const identityPath = join(directory, "identity.json");
344
+ const signerPath = join(directory, "signer.json");
345
+ const agentPath = join(directory, "agent.json");
346
+ const targets = [
347
+ { path: signerPath, payload: signerPayload(input) },
348
+ { path: identityPath, payload: identityPayload(input) },
349
+ { path: agentPath, payload: agentPayload(input) }
350
+ ];
351
+ const originals = /* @__PURE__ */ new Map();
352
+ for (const { path } of targets) {
353
+ originals.set(path, await readRawFile(path));
354
+ }
355
+ const temps = [];
356
+ try {
357
+ for (const { path, payload } of targets) {
358
+ const temp = `${path}.rekey-${crypto.randomBytes(6).toString("hex")}.tmp`;
359
+ await writeOwnerOnlyJson(temp, payload, input.warn);
360
+ temps.push({ from: temp, to: path });
361
+ }
362
+ for (const { from, to } of temps) {
363
+ await rename(from, to);
364
+ }
365
+ } catch (err) {
366
+ for (const { from } of temps) await rm(from, { force: true }).catch(() => void 0);
367
+ for (const [path, contents] of originals) {
368
+ if (contents === null) {
369
+ await rm(path, { force: true }).catch(() => void 0);
370
+ } else {
371
+ await writeFile(path, contents, { mode: 384 }).catch(() => void 0);
372
+ }
373
+ }
374
+ throw err;
375
+ }
376
+ return { directory, identityPath, signerPath, agentPath };
377
+ }
378
+ async function writeRekeyPending(directory, pending, warn) {
379
+ const path = join(directory, REKEY_PENDING_FILENAME);
380
+ await rm(path, { force: true }).catch(() => void 0);
381
+ await writeOwnerOnlyJson(path, { ...pending }, warn);
382
+ return path;
383
+ }
384
+ async function readRekeyPending(directory, now = Date.now()) {
385
+ const path = join(directory, REKEY_PENDING_FILENAME);
386
+ const raw = await readJsonFile(path);
387
+ if (!raw) {
388
+ throw new Error(
389
+ `No re-key in progress at ${directory}. Run the connector with --rekey first \u2014 it prints the new signing address to paste into the Haven agent page.`
390
+ );
391
+ }
392
+ const pending = raw;
393
+ if (!pending.new_delegate_key || !pending.new_delegate_address || !pending.agent_id) {
394
+ throw new Error(`The pending re-key at ${path} is unreadable. Delete it and start again with --rekey.`);
395
+ }
396
+ if (pending.expires_at && Date.parse(pending.expires_at) < now) {
397
+ throw new Error(
398
+ `The re-key started at ${pending.started_at} has expired. Start again with --rekey \u2014 the address currently shown in your dashboard is no longer the one this machine holds.`
399
+ );
400
+ }
401
+ return pending;
402
+ }
403
+ async function inspectRekeyPending(directory, now = Date.now()) {
404
+ const path = join(directory, REKEY_PENDING_FILENAME);
405
+ const raw = await readJsonFile(path);
406
+ if (!raw) {
407
+ const present = await readRawFile(path) !== null;
408
+ return present ? { state: "unreadable", path } : null;
409
+ }
410
+ const agentId = asString(raw.agent_id);
411
+ const newDelegateAddress = asString(raw.new_delegate_address);
412
+ const startedAt = asString(raw.started_at);
413
+ const expiresAt = asString(raw.expires_at);
414
+ if (!agentId || !newDelegateAddress) {
415
+ return { state: "unreadable", path, ...startedAt ? { startedAt } : {} };
416
+ }
417
+ const expired = expiresAt !== void 0 && Date.parse(expiresAt) < now;
418
+ return {
419
+ state: expired ? "expired" : "pending",
420
+ path,
421
+ agentId,
422
+ newDelegateAddress,
423
+ ...startedAt ? { startedAt } : {},
424
+ ...expiresAt ? { expiresAt } : {}
425
+ };
426
+ }
427
+ async function clearRekeyPending(directory) {
428
+ await rm(join(directory, REKEY_PENDING_FILENAME), { force: true }).catch(() => void 0);
429
+ }
430
+ async function readJsonFile(path) {
431
+ const raw = await readRawFile(path);
432
+ if (raw === null) return null;
433
+ try {
434
+ const parsed = JSON.parse(raw);
435
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
436
+ } catch {
437
+ return null;
438
+ }
439
+ }
440
+ async function readRawFile(path) {
441
+ try {
442
+ return await readFile(path, "utf8");
443
+ } catch {
444
+ return null;
445
+ }
446
+ }
447
+ function asString(value) {
448
+ return typeof value === "string" && value.length > 0 ? value : void 0;
449
+ }
450
+ async function assertServerSlugAvailable(serverName, baseDir) {
451
+ const directory = defaultAgentDirectory(serverName, baseDir);
452
+ try {
453
+ await stat(join(directory, "identity.json"));
454
+ } catch {
455
+ return;
456
+ }
457
+ throw new Error(
458
+ `The name "${serverName}" is already wired on this machine (${directory} holds credentials). Pick a different --name, or revoke and remove that agent first \u2014 connect never overwrites credentials.`
459
+ );
460
+ }
461
+ function defaultAgentDirectory(agentId, baseDir = join(homedir(), ".haven", "agents")) {
462
+ return resolve(defaultCredentialRoot(baseDir), safePathPart(agentId));
463
+ }
464
+ function defaultCredentialRoot(baseDir = join(homedir(), ".haven", "agents")) {
465
+ return resolve(baseDir);
466
+ }
467
+ async function writeOwnerOnlyJson(path, value, warn) {
468
+ const json = JSON.stringify(dropUndefined(value), null, 2);
469
+ await writeFile(path, `${json}
470
+ `, { mode: 384, flag: "wx" });
471
+ await restrictPermissions(path, 384, warn);
472
+ }
473
+ function safePathPart(value) {
474
+ return value.replace(/[^A-Za-z0-9_.-]/g, "_");
475
+ }
476
+ function dropUndefined(value) {
477
+ return Object.fromEntries(Object.entries(value).filter(([, field]) => field !== void 0));
478
+ }
479
+ async function assertDoesNotExist(path) {
480
+ try {
481
+ await access(path);
482
+ } catch (err) {
483
+ if (err && typeof err === "object" && "code" in err && err.code === "ENOENT") return;
484
+ throw err;
485
+ }
486
+ throw new Error(`Refusing to overwrite existing Haven credential file: ${path}`);
487
+ }
488
+ async function restrictPermissions(path, mode, warn) {
489
+ try {
490
+ await chmod(path, mode);
491
+ } catch (err) {
492
+ warn?.(
493
+ `Warning: could not restrict permissions on ${path} to ${mode.toString(8)}. Move this credential to a private location or run chmod ${mode.toString(8)} ${path}. ${err instanceof Error ? err.message : String(err)}`
494
+ );
495
+ }
496
+ }
497
+ var REKEY_PENDING_FILENAME, REKEY_PENDING_TTL_MS;
498
+ var init_storage = __esm({
499
+ "src/storage.ts"() {
500
+ REKEY_PENDING_FILENAME = "rekey-pending.json";
501
+ REKEY_PENDING_TTL_MS = 24 * 60 * 60 * 1e3;
502
+ }
503
+ });
504
+ function mcpPackageSpec() {
505
+ return `${MCP_RUNTIME_MANIFEST.mcpPackage}@${MCP_RUNTIME_MANIFEST.mcpVersion}`;
506
+ }
507
+ function sdkPackageSpec() {
508
+ return `${MCP_RUNTIME_MANIFEST.sdkPackage}@${MCP_RUNTIME_MANIFEST.sdkVersion}`;
509
+ }
510
+ function signerPackageSpec() {
511
+ return `${MCP_RUNTIME_MANIFEST.signerPackage}@${MCP_RUNTIME_MANIFEST.signerVersion}`;
512
+ }
513
+ var MCP_RUNTIME_MANIFEST;
514
+ var init_runtime_manifest = __esm({
515
+ "src/runtime-manifest.ts"() {
516
+ MCP_RUNTIME_MANIFEST = {
517
+ mcpPackage: "@haven_ai/mcp",
518
+ mcpVersion: MCP_VERSION,
519
+ sdkPackage: "@haven_ai/sdk",
520
+ sdkVersion: "0.1.30-alpha.0",
521
+ signerPackage: "@haven_ai/signer",
522
+ signerVersion: "0.1.30-alpha.0",
523
+ // Sourced from the SDK, never a literal (#1161). This field read '20.0.0'
524
+ // while every package's `engines` said `>=24` and the docs said `>=24.0.0`,
525
+ // so the guard that was supposed to enforce the floor waved Node v23 through
526
+ // — including on the `--local` path where it does run. A hand-maintained
527
+ // second copy of a number is a drift waiting to happen; a guard test pins
528
+ // this against `package.json`'s `engines.node`.
529
+ minimumNodeVersion: HAVEN_MINIMUM_NODE_VERSION,
530
+ supportedClients: ["codex-cli", "codex-desktop", "claude-code"],
531
+ requiredTools: registeredToolNames(),
532
+ /**
533
+ * The signer MCP's tool surface, DERIVED from the pinned @haven_ai/signer
534
+ * package (#1587) — same anti-drift rule as `requiredTools` above: a
535
+ * literal list here would rot the first time the signer gains a tool.
536
+ * The handshake probe requires all of them.
537
+ */
538
+ requiredSignerTools: Object.keys(toolSchemas)
539
+ };
540
+ }
541
+ });
542
+ async function writeRuntimeConfig(input, deps = {}) {
543
+ switch (input.runtime) {
544
+ case "codex-cli":
545
+ case "codex-desktop":
546
+ return writeCodexConfig(input);
547
+ case "cursor":
548
+ return writeJsonRuntimeConfig(input, cursorConfigPath(input.homeDir), "mcpServers");
549
+ case "vscode":
550
+ return writeJsonRuntimeConfig(input, vscodeConfigPath(input.homeDir), "servers");
551
+ case "vscode-insiders":
552
+ return writeJsonRuntimeConfig(input, vscodeInsidersConfigPath(input.homeDir), "servers");
553
+ case "claude-desktop":
554
+ return writeJsonRuntimeConfig(input, claudeDesktopConfigPath(input.homeDir), "mcpServers");
555
+ case "hermes":
556
+ return writeHermesConfig(input, deps);
557
+ default:
558
+ return {
559
+ hostedConfigured: false,
560
+ signerConfigured: false,
561
+ localMcpConfigured: false,
562
+ runtimeMcpMode: "manual",
563
+ target: "manual runtime setup",
564
+ changed: false,
565
+ restartRequired: true,
566
+ messages: ["Runtime config needs to be added manually for this agent environment."],
567
+ errorCode: "manual_runtime_setup_required"
568
+ };
569
+ }
570
+ }
571
+ function buildHostedServer(hostedMcpUrl, apiKey, runtime) {
572
+ if (runtime === "vscode" || runtime === "vscode-insiders") {
573
+ return {
574
+ type: "http",
575
+ url: hostedMcpUrl,
576
+ headers: { Authorization: `Bearer ${apiKey}` }
577
+ };
578
+ }
579
+ return {
580
+ url: hostedMcpUrl,
581
+ headers: { Authorization: `Bearer ${apiKey}` }
582
+ };
583
+ }
584
+ function resolveSignerLaunchSpec(input) {
585
+ return input.signerCommand ?? {
586
+ command: "npx",
587
+ args: ["-y", signerPackageSpec(), "--credentials", input.signerPath]
588
+ };
589
+ }
590
+ function buildSignerServer(spec, runtime) {
591
+ const server = {
592
+ command: spec.command,
593
+ args: spec.args
594
+ };
595
+ if (runtime === "vscode" || runtime === "vscode-insiders") return { type: "stdio", ...server };
596
+ return server;
597
+ }
598
+ function mergeJsonMcpConfig(existingJson, serverRoot, hostedServer, signerServer, names = serverNamesFor(), configPath) {
599
+ const config = existingJson?.trim() ? parseJsonObject(existingJson, configPath) : {};
600
+ const existingRoot = config[serverRoot];
601
+ const servers = existingRoot && typeof existingRoot === "object" && !Array.isArray(existingRoot) ? existingRoot : {};
602
+ config[serverRoot] = {
603
+ ...servers,
604
+ [names.hosted]: hostedServer,
605
+ [names.signer]: signerServer
606
+ };
607
+ return `${JSON.stringify(config, null, 2)}
608
+ `;
609
+ }
610
+ function mergeHermesYaml(existingYaml, hostedServer, signerServer, names = serverNamesFor(), configPath) {
611
+ if (!existingYaml?.trim()) {
612
+ return renderHermesYaml({ [names.hosted]: hostedServer, [names.signer]: signerServer });
613
+ }
614
+ const doc = parseDocument(existingYaml, { keepSourceTokens: true });
615
+ if (doc.errors.length > 0 || !isMap(doc.contents)) {
616
+ throw new UnreadableRuntimeConfigError(configPath ?? "the Hermes config", "it is not a YAML object");
617
+ }
618
+ const mcpPair = doc.contents.items.find((item) => item.key?.toString() === "mcp_servers");
619
+ const existingServers = mcpPair && isMap(mcpPair.value) ? mcpPair.value.toJSON() : {};
620
+ const servers = isRecord(existingServers) ? existingServers : {};
140
621
  const mergedServers = {
141
622
  ...servers,
142
- haven: hostedServer,
143
- "haven-signer": signerServer
623
+ [names.hosted]: hostedServer,
624
+ [names.signer]: signerServer
144
625
  };
145
626
  if (!mcpPair) {
146
627
  return appendHermesMcpServers(existingYaml, mergedServers);
@@ -148,9 +629,9 @@ function mergeHermesYaml(existingYaml, hostedServer, signerServer) {
148
629
  if (!mcpPair.value?.range) return replaceEmptyHermesMcpServers(existingYaml, mcpPair.key?.range, mergedServers);
149
630
  return replaceHermesMcpServers(existingYaml, mcpPair.key?.range, mcpPair.value.range, mergedServers);
150
631
  }
151
- function mergeHermesEnv(existingEnv, apiKey) {
632
+ function mergeHermesEnv(existingEnv, apiKey, envKey = HERMES_API_KEY_ENV) {
152
633
  if (/[\r\n]/.test(apiKey)) throw new Error("Hermes API key must be a single line");
153
- const assignment = `${HERMES_API_KEY_ENV}=${apiKey}`;
634
+ const assignment = `${envKey}=${apiKey}`;
154
635
  if (!existingEnv) return `${assignment}
155
636
  `;
156
637
  const lineEnding = existingEnv.includes("\r\n") ? "\r\n" : "\n";
@@ -159,12 +640,12 @@ function mergeHermesEnv(existingEnv, apiKey) {
159
640
  if (hasTrailingNewline) lines.pop();
160
641
  let found = false;
161
642
  const merged = lines.flatMap((line) => {
162
- if (isHermesEnvAssignment(line)) {
643
+ if (isHermesEnvAssignment(line, envKey)) {
163
644
  if (found) return [];
164
645
  found = true;
165
646
  return [assignment];
166
647
  }
167
- if (isAmbiguousHermesEnvLine(line)) {
648
+ if (isAmbiguousHermesEnvLine(line, envKey)) {
168
649
  throw new Error("Hermes environment contains an ambiguous managed key");
169
650
  }
170
651
  return [line];
@@ -174,11 +655,11 @@ function mergeHermesEnv(existingEnv, apiKey) {
174
655
  }
175
656
  return `${merged.join(lineEnding)}${hasTrailingNewline ? lineEnding : ""}`;
176
657
  }
177
- function isHermesEnvAssignment(line) {
178
- return /^\s*(?:export[ \t]+)?MCP_HAVEN_API_KEY[ \t]*=/.test(line);
658
+ function isHermesEnvAssignment(line, envKey) {
659
+ return new RegExp(`^\\s*(?:export[ \\t]+)?${envKey}[ \\t]*=`).test(line);
179
660
  }
180
- function isAmbiguousHermesEnvLine(line) {
181
- return /^\s*(?:export[ \t]+)?MCP_HAVEN_API_KEY\b/.test(line);
661
+ function isAmbiguousHermesEnvLine(line, envKey) {
662
+ return new RegExp(`^\\s*(?:export[ \\t]+)?${envKey}\\b`).test(line);
182
663
  }
183
664
  function appendHermesMcpServers(source, servers) {
184
665
  const documentEnd = /(?:^|\n)[ \t]*\.\.\.[ \t]*(?:#[^\n]*)?\r?\n?$/.exec(source);
@@ -237,11 +718,14 @@ function renderHermesMcpServerEntries(servers, indent) {
237
718
  function isRecord(value) {
238
719
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
239
720
  }
240
- function mergeCodexToml(existingToml, localMcpCommand) {
241
- let next = removeTomlTableTree(removeTomlTableTree(existingToml, "mcp_servers.haven"), "mcp_servers.haven_signer");
721
+ function mergeCodexToml(existingToml, localMcpCommand, names = serverNamesFor()) {
722
+ let next = removeTomlTableTree(
723
+ removeTomlTableTree(existingToml, `mcp_servers.${names.codexHosted}`),
724
+ `mcp_servers.${names.codexSigner}`
725
+ );
242
726
  next = next.trimEnd();
243
727
  const block = [
244
- "[mcp_servers.haven]",
728
+ `[mcp_servers.${names.codexHosted}]`,
245
729
  `command = ${tomlString(localMcpCommand)}`,
246
730
  "args = []",
247
731
  "startup_timeout_sec = 120"
@@ -253,15 +737,18 @@ function mergeCodexToml(existingToml, localMcpCommand) {
253
737
  `;
254
738
  return merged;
255
739
  }
256
- function mergeCodexTomlHosted(existingToml, hostedMcpUrl, apiKey, signerSpec) {
257
- let next = removeTomlTableTree(removeTomlTableTree(existingToml, "mcp_servers.haven"), "mcp_servers.haven_signer");
740
+ function mergeCodexTomlHosted(existingToml, hostedMcpUrl, apiKey, signerSpec, names = serverNamesFor()) {
741
+ let next = removeTomlTableTree(
742
+ removeTomlTableTree(existingToml, `mcp_servers.${names.codexHosted}`),
743
+ `mcp_servers.${names.codexSigner}`
744
+ );
258
745
  next = next.trimEnd();
259
746
  const block = [
260
- "[mcp_servers.haven]",
747
+ `[mcp_servers.${names.codexHosted}]`,
261
748
  `url = ${tomlString(hostedMcpUrl)}`,
262
749
  `http_headers = { "Authorization" = ${tomlString(`Bearer ${apiKey}`)} }`,
263
750
  "",
264
- "[mcp_servers.haven_signer]",
751
+ `[mcp_servers.${names.codexSigner}]`,
265
752
  `command = ${tomlString(signerSpec.command)}`,
266
753
  `args = [${signerSpec.args.map((arg) => tomlString(arg)).join(", ")}]`,
267
754
  "startup_timeout_sec = 120"
@@ -280,7 +767,9 @@ async function writeJsonRuntimeConfig(input, target, serverRoot) {
280
767
  existing,
281
768
  serverRoot,
282
769
  buildHostedServer(input.hostedMcpUrl, input.apiKey, input.runtime),
283
- buildSignerServer(resolveSignerLaunchSpec(input), input.runtime)
770
+ buildSignerServer(resolveSignerLaunchSpec(input), input.runtime),
771
+ serverNamesFor(input.serverName),
772
+ target
284
773
  );
285
774
  await writeOwnerOnlyText(target, merged);
286
775
  return {
@@ -294,6 +783,7 @@ async function writeJsonRuntimeConfig(input, target, serverRoot) {
294
783
  messages: [`Updated Haven MCP entries in ${configTargetLabel(input.runtime)}.`]
295
784
  };
296
785
  } catch (err) {
786
+ const unreadable = err instanceof UnreadableRuntimeConfigError;
297
787
  return {
298
788
  hostedConfigured: false,
299
789
  signerConfigured: false,
@@ -302,8 +792,11 @@ async function writeJsonRuntimeConfig(input, target, serverRoot) {
302
792
  target: configTargetLabel(input.runtime),
303
793
  changed: false,
304
794
  restartRequired: true,
305
- messages: [`Could not update ${configTargetLabel(input.runtime)}: ${err instanceof Error ? err.message : String(err)}`],
306
- errorCode: "runtime_config_write_failed"
795
+ messages: unreadable ? [
796
+ `Could not update ${configTargetLabel(input.runtime)}: ${err.message}.`,
797
+ `Nothing was written to ${err.configPath}. Fix the JSON there (or move the file aside), then run \`${REPAIR_COMMAND_PREFIX} ${input.runtime}\` to write the Haven entries from the credentials already stored on this machine. Do not re-run the setup command: its token is already used.`
798
+ ] : [`Could not update ${configTargetLabel(input.runtime)}: ${err instanceof Error ? err.message : String(err)}`],
799
+ errorCode: unreadable ? "runtime_config_unreadable" : "runtime_config_write_failed"
307
800
  };
308
801
  }
309
802
  }
@@ -312,8 +805,9 @@ async function writeHermesConfig(input, deps) {
312
805
  const envTarget = hermesEnvPath(input.homeDir);
313
806
  try {
314
807
  const [existing, existingEnv] = await Promise.all([readOptional(target), readOptional(envTarget)]);
808
+ const names = serverNamesFor(input.serverName);
315
809
  const hostedServer = {
316
- ...buildHostedServer(input.hostedMcpUrl, `\${${HERMES_API_KEY_ENV}}`, input.runtime),
810
+ ...buildHostedServer(input.hostedMcpUrl, `\${${names.hermesEnvKey}}`, input.runtime),
317
811
  enabled: true
318
812
  };
319
813
  const signerServer = {
@@ -323,9 +817,11 @@ async function writeHermesConfig(input, deps) {
323
817
  const merged = mergeHermesYaml(
324
818
  existing,
325
819
  hostedServer,
326
- signerServer
820
+ signerServer,
821
+ names,
822
+ target
327
823
  );
328
- const mergedEnv = mergeHermesEnv(existingEnv, input.apiKey);
824
+ const mergedEnv = mergeHermesEnv(existingEnv, input.apiKey, names.hermesEnvKey);
329
825
  const writeText = deps.writeOwnerOnlyText ?? writeOwnerOnlyText;
330
826
  await writeText(envTarget, mergedEnv);
331
827
  try {
@@ -346,11 +842,13 @@ async function writeHermesConfig(input, deps) {
346
842
  messages: [
347
843
  `Updated Haven MCP entries in ${target}; stored the hosted MCP identity in ${envTarget}.`,
348
844
  "Restart Hermes (start a new session; gateway users: /restart), then verify with `hermes mcp list`, `hermes mcp test haven`, and `hermes mcp test haven-signer`.",
845
+ "If several long-lived Hermes processes are running (a gateway plus TUI workers), restart EVERY one: each loads its MCP wiring at startup, so a process started before this setup keeps using its old snapshot.",
349
846
  "If no mcp_* tools appear after restart, ensure the MCP SDK is installed in Hermes: pip install mcp"
350
847
  ]
351
848
  };
352
849
  } catch (err) {
353
850
  const recoveryIncomplete = err instanceof HermesConfigRecoveryError;
851
+ const unreadable = err instanceof UnreadableRuntimeConfigError;
354
852
  return {
355
853
  hostedConfigured: false,
356
854
  signerConfigured: false,
@@ -359,8 +857,11 @@ async function writeHermesConfig(input, deps) {
359
857
  target: "Hermes Agent config",
360
858
  changed: false,
361
859
  restartRequired: true,
362
- messages: [recoveryIncomplete ? "Could not update Hermes Agent config. Recovery did not complete; inspect the Hermes configuration before retrying." : "Could not update Hermes Agent config. Existing configuration was left unchanged."],
363
- errorCode: "runtime_config_write_failed"
860
+ messages: unreadable ? [
861
+ `Could not update Hermes Agent config: ${err.message}.`,
862
+ `Nothing was written to ${err.configPath}. Fix the YAML there (or move the file aside), then run \`${REPAIR_COMMAND_PREFIX} hermes\` to write the Haven entries from the credentials already stored on this machine. Do not re-run the setup command: its token is already used.`
863
+ ] : [recoveryIncomplete ? "Could not update Hermes Agent config. Recovery did not complete; inspect the Hermes configuration before retrying." : "Could not update Hermes Agent config. Existing configuration was left unchanged."],
864
+ errorCode: unreadable ? "runtime_config_unreadable" : "runtime_config_write_failed"
364
865
  };
365
866
  }
366
867
  }
@@ -392,7 +893,7 @@ async function writeCodexConfig(input) {
392
893
  if (!input.localMcpCommand) {
393
894
  throw new Error("local MCP wrapper command is required");
394
895
  }
395
- const merged2 = mergeCodexToml(existing ?? "", input.localMcpCommand);
896
+ const merged2 = mergeCodexToml(existing ?? "", input.localMcpCommand, serverNamesFor(input.serverName));
396
897
  await writeOwnerOnlyText(target, merged2);
397
898
  return {
398
899
  hostedConfigured: false,
@@ -407,7 +908,13 @@ async function writeCodexConfig(input) {
407
908
  ]
408
909
  };
409
910
  }
410
- const merged = mergeCodexTomlHosted(existing ?? "", input.hostedMcpUrl, input.apiKey, resolveSignerLaunchSpec(input));
911
+ const merged = mergeCodexTomlHosted(
912
+ existing ?? "",
913
+ input.hostedMcpUrl,
914
+ input.apiKey,
915
+ resolveSignerLaunchSpec(input),
916
+ serverNamesFor(input.serverName)
917
+ );
411
918
  await writeOwnerOnlyText(target, merged);
412
919
  return {
413
920
  hostedConfigured: true,
@@ -449,10 +956,15 @@ async function writeOwnerOnlyText(path, value) {
449
956
  await writeFile(path, value, { mode: 384 });
450
957
  await chmod(path, 384).catch(() => void 0);
451
958
  }
452
- function parseJsonObject(value) {
453
- const parsed = JSON.parse(value);
959
+ function parseJsonObject(value, configPath) {
960
+ let parsed;
961
+ try {
962
+ parsed = JSON.parse(value);
963
+ } catch {
964
+ throw new UnreadableRuntimeConfigError(configPath ?? "the runtime config", "it is not valid JSON");
965
+ }
454
966
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
455
- throw new Error("runtime config must be a JSON object");
967
+ throw new UnreadableRuntimeConfigError(configPath ?? "the runtime config", "the top level is not a JSON object");
456
968
  }
457
969
  return parsed;
458
970
  }
@@ -719,10 +1231,11 @@ function configTargetLabel(runtime) {
719
1231
  return "runtime MCP config";
720
1232
  }
721
1233
  }
722
- var HERMES_API_KEY_ENV, HermesConfigRecoveryError, InvalidCodexTomlError;
1234
+ var HERMES_API_KEY_ENV, HermesConfigRecoveryError, InvalidCodexTomlError, REPAIR_COMMAND_PREFIX, UnreadableRuntimeConfigError;
723
1235
  var init_config_writers = __esm({
724
1236
  "src/config-writers.ts"() {
725
1237
  init_runtime_manifest();
1238
+ init_server_names();
726
1239
  HERMES_API_KEY_ENV = "MCP_HAVEN_API_KEY";
727
1240
  HermesConfigRecoveryError = class extends Error {
728
1241
  constructor() {
@@ -736,27 +1249,136 @@ var init_config_writers = __esm({
736
1249
  this.name = "InvalidCodexTomlError";
737
1250
  }
738
1251
  };
1252
+ REPAIR_COMMAND_PREFIX = "npx @haven_ai/connect@alpha --doctor --repair --runtime";
1253
+ UnreadableRuntimeConfigError = class extends Error {
1254
+ configPath;
1255
+ constructor(configPath, detail) {
1256
+ super(`${configPath} is not a config Haven can merge into (${detail})`);
1257
+ this.name = "UnreadableRuntimeConfigError";
1258
+ this.configPath = configPath;
1259
+ }
1260
+ };
739
1261
  }
740
1262
  });
741
- async function probeHostedMcpTools(apiKey, hostedMcpUrl, fetchImpl = fetch) {
742
- let response;
1263
+ async function acknowledgeLocalMcpConsent(identityPath, signerPath, log) {
743
1264
  try {
744
- response = await fetchWithTimeout(fetchImpl, hostedMcpUrl, {
745
- method: "POST",
746
- headers: {
747
- Authorization: `Bearer ${apiKey}`,
748
- "Content-Type": "application/json",
749
- Accept: "application/json, text/event-stream"
750
- },
751
- body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" })
1265
+ const input = await buildLocalMcpConsentInput(identityPath, signerPath);
1266
+ const decision = await ensureConsent(input, {
1267
+ credentialsPath: identityPath,
1268
+ writeAck: true,
1269
+ out: log ? { write: (chunk) => writeLogChunk(log, chunk) } : void 0
752
1270
  });
753
- } catch {
754
- return { status: "network_error" };
1271
+ return {
1272
+ acknowledged: decision.ok,
1273
+ hash: decision.hash,
1274
+ reason: decision.reason
1275
+ };
1276
+ } catch (err) {
1277
+ return {
1278
+ acknowledged: false,
1279
+ error: err instanceof Error ? err.message : String(err)
1280
+ };
755
1281
  }
756
- if (response.status === 401 || response.status === 403) return { status: "unauthorized" };
757
- if (!response.ok) return { status: "bad_response" };
1282
+ }
1283
+ async function getLocalMcpConsentStatus(identityPath, signerPath) {
758
1284
  try {
759
- const payload = parseJsonRpcPayload(await response.text());
1285
+ const input = await buildLocalMcpConsentInput(identityPath, signerPath);
1286
+ const hash = computeConsentHash(input);
1287
+ const stored = await readLocalMcpAckFile(localMcpAckPath(identityPath));
1288
+ if (stored === hash) {
1289
+ return { acknowledged: true, hash, reason: "ack_file_match" };
1290
+ }
1291
+ return {
1292
+ acknowledged: false,
1293
+ hash,
1294
+ reason: stored ? "ack_file_mismatch" : "ack_file_missing"
1295
+ };
1296
+ } catch (err) {
1297
+ return {
1298
+ acknowledged: false,
1299
+ error: err instanceof Error ? err.message : String(err)
1300
+ };
1301
+ }
1302
+ }
1303
+ function localMcpAckPath(identityPath) {
1304
+ return resolve(`${identityPath}.ack.json`);
1305
+ }
1306
+ async function buildLocalMcpConsentInput(identityPath, signerPath) {
1307
+ const credentials = await loadCredentials({ identityPath, signerPath });
1308
+ const unavailableDuringSetup = {
1309
+ getAllowances: async () => {
1310
+ throw new Error("Haven approval is not complete yet.");
1311
+ }
1312
+ };
1313
+ return consentInputFromClient(
1314
+ unavailableDuringSetup,
1315
+ {
1316
+ apiKey: credentials.apiKey,
1317
+ apiUrl: credentials.apiUrl,
1318
+ agentId: credentials.agentId,
1319
+ safeAddress: credentials.safeAddress,
1320
+ delegateAddress: credentials.delegateAddress,
1321
+ chainId: credentials.chainId,
1322
+ allowanceSummary: credentials.allowanceSummary
1323
+ },
1324
+ registeredToolNames()
1325
+ );
1326
+ }
1327
+ async function readLocalMcpAckFile(path) {
1328
+ try {
1329
+ const parsed = JSON.parse(await readFile(path, "utf8"));
1330
+ return typeof parsed.ack === "string" ? parsed.ack : null;
1331
+ } catch {
1332
+ return null;
1333
+ }
1334
+ }
1335
+ function writeLogChunk(log, chunk) {
1336
+ const message = String(chunk).trimEnd();
1337
+ if (message) log(message);
1338
+ }
1339
+ var init_local_mcp_consent = __esm({
1340
+ "src/local-mcp-consent.ts"() {
1341
+ }
1342
+ });
1343
+ async function probeHostedAgentIdentity(apiKey, apiUrl, fetchImpl = fetch) {
1344
+ let response;
1345
+ try {
1346
+ response = await fetchWithTimeout(fetchImpl, `${apiUrl.replace(/\/+$/, "")}/machine-payments/agent`, {
1347
+ method: "GET",
1348
+ headers: { Authorization: `Bearer ${apiKey}`, Accept: "application/json" }
1349
+ });
1350
+ } catch {
1351
+ return { status: "network_error" };
1352
+ }
1353
+ if (response.status === 401 || response.status === 403) return { status: "unauthorized" };
1354
+ if (!response.ok) return { status: "bad_response" };
1355
+ try {
1356
+ const payload = JSON.parse(await response.text());
1357
+ if (typeof payload?.delegate_address !== "string") return { status: "bad_response" };
1358
+ return { status: "ok", agentId: payload.id, delegateAddress: payload.delegate_address };
1359
+ } catch {
1360
+ return { status: "bad_response" };
1361
+ }
1362
+ }
1363
+ async function probeHostedMcpTools(apiKey, hostedMcpUrl, fetchImpl = fetch) {
1364
+ let response;
1365
+ try {
1366
+ response = await fetchWithTimeout(fetchImpl, hostedMcpUrl, {
1367
+ method: "POST",
1368
+ headers: {
1369
+ Authorization: `Bearer ${apiKey}`,
1370
+ "Content-Type": "application/json",
1371
+ Accept: "application/json, text/event-stream"
1372
+ },
1373
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" })
1374
+ });
1375
+ } catch {
1376
+ return { status: "network_error" };
1377
+ }
1378
+ if (response.status === 401 || response.status === 403) return { status: "unauthorized" };
1379
+ if (!response.ok) return { status: "bad_response" };
1380
+ try {
1381
+ const payload = parseJsonRpcPayload(await response.text());
760
1382
  if (!payload || payload.error) return { status: "bad_response" };
761
1383
  const tools = payload.result?.tools;
762
1384
  return { status: "ok", toolCount: Array.isArray(tools) ? tools.length : void 0 };
@@ -775,7 +1397,7 @@ async function probeLocalSignerCredential(signerPath) {
775
1397
  }
776
1398
  }
777
1399
  async function probeLocalMcpTools(command, args, requiredTools, timeoutMs = 1e4) {
778
- return new Promise((resolve8) => {
1400
+ return new Promise((resolve9) => {
779
1401
  const child = spawn(command, args, { stdio: ["pipe", "pipe", "ignore"] });
780
1402
  let stdout = "";
781
1403
  let settled = false;
@@ -787,7 +1409,7 @@ async function probeLocalMcpTools(command, args, requiredTools, timeoutMs = 1e4)
787
1409
  settled = true;
788
1410
  clearTimeout(timeout);
789
1411
  child.kill();
790
- resolve8(result);
1412
+ resolve9(result);
791
1413
  };
792
1414
  const timeout = setTimeout(() => finish({ status: "timeout" }), timeoutMs);
793
1415
  child.on("error", () => finish({ status: "process_error" }));
@@ -901,7 +1523,8 @@ async function prepareSignerRuntime(input, deps = {}) {
901
1523
  wrapperPath,
902
1524
  runtimeDirectory,
903
1525
  npmCacheDirectory,
904
- cliPath
1526
+ cliPath,
1527
+ serverName: input.serverName
905
1528
  });
906
1529
  messages.push(`Prepared stable local Haven signer wrapper: ${wrapperPath}`);
907
1530
  return {
@@ -1002,6 +1625,7 @@ async function readRuntimeSidecar(credentialDirectory) {
1002
1625
  }
1003
1626
  async function writeRuntimeSidecar(input) {
1004
1627
  const value = {
1628
+ ...input.serverName ? { server_name: input.serverName } : {},
1005
1629
  signer_package: MCP_RUNTIME_MANIFEST.signerPackage,
1006
1630
  signer_version: MCP_RUNTIME_MANIFEST.signerVersion,
1007
1631
  sdk_package: MCP_RUNTIME_MANIFEST.sdkPackage,
@@ -1031,61 +1655,391 @@ var init_signer_runtime = __esm({
1031
1655
  SIGNER_INSTALL_HEARTBEAT_MS = 15e3;
1032
1656
  }
1033
1657
  });
1034
-
1035
- // src/runtime-registry.ts
1036
- function runtimeProfile(runtime, env = process.env) {
1037
- return RUNTIME_PROFILES[normalizeRuntime(runtime, env)];
1658
+ async function prepareLocalMcpRuntime(input, deps = {}) {
1659
+ assertSupportedNodeVersion(input.nodeVersion);
1660
+ const homeDir = input.homeDir ?? homedir();
1661
+ const runtimeDirectory = resolve(homeDir, ".haven", "mcp-runtime", MCP_RUNTIME_MANIFEST.mcpVersion);
1662
+ const npmCacheDirectory = resolve(homeDir, ".haven", "npm-cache");
1663
+ const cliPath = join(runtimeDirectory, "node_modules", "@haven_ai", "mcp", "dist", "cli.js");
1664
+ const messages = [];
1665
+ await mkdir(runtimeDirectory, { recursive: true, mode: 448 });
1666
+ await chmod(runtimeDirectory, 448).catch(() => void 0);
1667
+ await mkdir(npmCacheDirectory, { recursive: true, mode: 448 });
1668
+ await chmod(npmCacheDirectory, 448).catch(() => void 0);
1669
+ if (await installedRuntimeMatches2(runtimeDirectory, cliPath)) {
1670
+ messages.push(`Using existing local Haven MCP runtime ${mcpPackageSpec()}.`);
1671
+ } else {
1672
+ await installRuntimePackages2(runtimeDirectory, npmCacheDirectory, deps);
1673
+ messages.push(`Installed local Haven MCP runtime ${mcpPackageSpec()}.`);
1674
+ }
1675
+ await assertFileExists2(cliPath, "local Haven MCP CLI");
1676
+ const wrapperPath = join(input.credentialDirectory, "bin", "haven-mcp");
1677
+ await writeWrapper2({
1678
+ wrapperPath,
1679
+ cliPath,
1680
+ identityPath: input.identityPath,
1681
+ signerPath: input.signerPath
1682
+ });
1683
+ await writeRuntimeSidecar2({
1684
+ path: join(input.credentialDirectory, "mcp-runtime.json"),
1685
+ wrapperPath,
1686
+ runtimeDirectory,
1687
+ npmCacheDirectory,
1688
+ cliPath,
1689
+ serverName: input.serverName
1690
+ });
1691
+ messages.push(`Prepared stable local Haven MCP wrapper: ${wrapperPath}`);
1692
+ return {
1693
+ command: wrapperPath,
1694
+ args: [],
1695
+ wrapperPath,
1696
+ runtimeDirectory,
1697
+ npmCacheDirectory,
1698
+ cliPath,
1699
+ messages
1700
+ };
1038
1701
  }
1039
- function normalizeRuntime(runtime, env = process.env) {
1040
- const explicit = normalizeRuntimeName(runtime);
1041
- if (explicit) return explicit;
1042
- return detectRuntime(env) ?? "other";
1702
+ function assertSupportedNodeVersion(nodeVersion = process.versions.node, minimumNodeVersion = MCP_RUNTIME_MANIFEST.minimumNodeVersion, subject = "Haven setup") {
1703
+ if (!isSupportedNodeVersion(nodeVersion, minimumNodeVersion)) {
1704
+ throw new UnsupportedNodeVersionError(nodeVersion, minimumNodeVersion, subject);
1705
+ }
1043
1706
  }
1044
- function restartRequiredForRuntime(runtime, env = process.env) {
1045
- const mode = runtimeProfile(runtime, env).restartMode;
1046
- return mode === "restart-session" || mode === "restart-app";
1707
+ async function installRuntimePackages2(runtimeDirectory, npmCacheDirectory, deps) {
1708
+ const { runCommand, onProgress } = deps;
1709
+ const baseArgs = [
1710
+ "install",
1711
+ "--prefix",
1712
+ runtimeDirectory,
1713
+ "--no-audit",
1714
+ "--no-fund",
1715
+ "--omit=dev",
1716
+ "--prefer-offline",
1717
+ mcpPackageSpec(),
1718
+ sdkPackageSpec()
1719
+ ];
1720
+ const run = async (args) => {
1721
+ const startedAt = Date.now();
1722
+ const heartbeat = setInterval(() => {
1723
+ const seconds = Math.round((Date.now() - startedAt) / 1e3);
1724
+ onProgress?.(`Still installing the local Haven MCP runtime\u2026 (${seconds}s \u2014 a cold cache can take several minutes)`);
1725
+ }, SIGNER_INSTALL_HEARTBEAT_MS);
1726
+ heartbeat.unref?.();
1727
+ try {
1728
+ if (runCommand) await runCommand("npm", args);
1729
+ else await execFileAsync2("npm", args, { timeout: SIGNER_INSTALL_TIMEOUT_MS, maxBuffer: 1024 * 1024 });
1730
+ } finally {
1731
+ clearInterval(heartbeat);
1732
+ }
1733
+ };
1734
+ try {
1735
+ await run(baseArgs);
1736
+ } catch {
1737
+ try {
1738
+ await run([...baseArgs, "--cache", npmCacheDirectory]);
1739
+ } catch (err) {
1740
+ throw new Error(`Could not install local Haven MCP runtime ${mcpPackageSpec()}: ${err instanceof Error ? err.message : String(err)}`);
1741
+ }
1742
+ }
1047
1743
  }
1048
- function runtimeVerificationInstruction(runtime) {
1049
- const label = RUNTIME_PROFILES[runtime].label;
1050
- return `In ${label}, run the read-only \`haven_get_agent\` and \`haven_get_allowances\` tools to confirm the Haven wallet and live budget. Do not sign, fund, or create a payment to verify setup.`;
1744
+ async function installedRuntimeMatches2(runtimeDirectory, cliPath) {
1745
+ try {
1746
+ await assertFileExists2(cliPath, "local Haven MCP CLI");
1747
+ const [mcpPackage, sdkPackage] = await Promise.all([
1748
+ readPackageJson2(join(runtimeDirectory, "node_modules", "@haven_ai", "mcp", "package.json")),
1749
+ readPackageJson2(join(runtimeDirectory, "node_modules", "@haven_ai", "sdk", "package.json"))
1750
+ ]);
1751
+ return mcpPackage.version === MCP_RUNTIME_MANIFEST.mcpVersion && sdkPackage.version === MCP_RUNTIME_MANIFEST.sdkVersion;
1752
+ } catch {
1753
+ return false;
1754
+ }
1051
1755
  }
1052
- function normalizeRuntimeName(runtime) {
1053
- const key = runtime?.trim().toLowerCase();
1054
- if (!key) return null;
1055
- return RUNTIME_ALIASES[key.replace(/\s+/g, "-")] ?? null;
1756
+ async function readPackageJson2(path) {
1757
+ return JSON.parse(await readFile(path, "utf8"));
1056
1758
  }
1057
- function detectRuntime(env) {
1058
- if (env.CLAUDECODE || env.CLAUDE_CODE || env.CLAUDECODE_CWD) return "claude-code";
1059
- if (env.CODEX_SANDBOX || env.CODEX_HOME || env.CODEX_CWD) return "codex-cli";
1060
- if (env.VSCODE_CWD || env.VSCODE_IPC_HOOK_CLI || env.TERM_PROGRAM === "vscode") return "vscode";
1061
- if (env.HERMES_HOME || env.HERMES_AGENT) return "hermes";
1062
- return null;
1759
+ async function writeWrapper2(input) {
1760
+ await mkdir(dirname(input.wrapperPath), { recursive: true, mode: 448 });
1761
+ await chmod(dirname(input.wrapperPath), 448).catch(() => void 0);
1762
+ const source = [
1763
+ "#!/usr/bin/env node",
1764
+ "import { spawn } from 'node:child_process'",
1765
+ "",
1766
+ `const cliPath = ${JSON.stringify(input.cliPath)}`,
1767
+ `const identityPath = ${JSON.stringify(input.identityPath)}`,
1768
+ `const signerPath = ${JSON.stringify(input.signerPath)}`,
1769
+ "",
1770
+ "const child = spawn(process.execPath, [cliPath, '--identity', identityPath, '--signer', signerPath, ...process.argv.slice(2)], {",
1771
+ " stdio: 'inherit',",
1772
+ "})",
1773
+ "",
1774
+ "child.on('exit', (code, signal) => {",
1775
+ " if (signal) process.kill(process.pid, signal)",
1776
+ " else process.exit(code ?? 1)",
1777
+ "})",
1778
+ ""
1779
+ ].join("\n");
1780
+ await writeFile(input.wrapperPath, source, { mode: 448 });
1781
+ await chmod(input.wrapperPath, 448).catch(() => void 0);
1063
1782
  }
1064
- var RUNTIME_PROFILES, RUNTIME_ALIASES;
1065
- var init_runtime_registry = __esm({
1066
- "src/runtime-registry.ts"() {
1067
- RUNTIME_PROFILES = {
1068
- "claude-code": {
1069
- id: "claude-code",
1070
- label: "Claude Code",
1071
- restartMode: "restart-session",
1072
- canWriteRuntimeConfig: true,
1073
- activationInstruction: "Start a new Claude Code session so it loads the Haven MCP entries."
1074
- },
1075
- "codex-cli": {
1076
- id: "codex-cli",
1077
- label: "Codex CLI",
1078
- restartMode: "restart-session",
1079
- canWriteRuntimeConfig: true,
1080
- activationInstruction: "Start a fresh Codex CLI session (for example, run `codex resume --last`)."
1081
- },
1082
- "codex-desktop": {
1083
- id: "codex-desktop",
1084
- label: "Codex Desktop",
1085
- restartMode: "restart-session",
1086
- canWriteRuntimeConfig: true,
1087
- activationInstruction: "Quit and reopen Codex Desktop so it loads the Haven MCP entries."
1088
- },
1783
+ async function writeRuntimeSidecar2(input) {
1784
+ const value = {
1785
+ ...input.serverName ? { server_name: input.serverName } : {},
1786
+ mcp_package: MCP_RUNTIME_MANIFEST.mcpPackage,
1787
+ mcp_version: MCP_RUNTIME_MANIFEST.mcpVersion,
1788
+ sdk_package: MCP_RUNTIME_MANIFEST.sdkPackage,
1789
+ sdk_version: MCP_RUNTIME_MANIFEST.sdkVersion,
1790
+ minimum_node_version: MCP_RUNTIME_MANIFEST.minimumNodeVersion,
1791
+ wrapper_path: input.wrapperPath,
1792
+ runtime_directory: input.runtimeDirectory,
1793
+ npm_cache_directory: input.npmCacheDirectory,
1794
+ cli_path: input.cliPath
1795
+ };
1796
+ await writeFile(input.path, `${JSON.stringify(value, null, 2)}
1797
+ `, { mode: 384 });
1798
+ await chmod(input.path, 384).catch(() => void 0);
1799
+ }
1800
+ async function assertFileExists2(path, label) {
1801
+ try {
1802
+ await access(path);
1803
+ } catch {
1804
+ throw new Error(`Missing ${label}: ${path}`);
1805
+ }
1806
+ }
1807
+ var execFileAsync2, UnsupportedNodeVersionError;
1808
+ var init_local_mcp_runtime = __esm({
1809
+ "src/local-mcp-runtime.ts"() {
1810
+ init_signer_runtime();
1811
+ init_runtime_manifest();
1812
+ execFileAsync2 = promisify(execFile);
1813
+ UnsupportedNodeVersionError = class extends Error {
1814
+ code = "local_mcp_unsupported_node_version";
1815
+ nodeVersion;
1816
+ minimumNodeVersion;
1817
+ constructor(nodeVersion, minimumNodeVersion, subject = "Haven setup") {
1818
+ super(unsupportedNodeVersionMessage({ subject, nodeVersion, minimumNodeVersion }));
1819
+ this.name = "UnsupportedNodeVersionError";
1820
+ this.nodeVersion = nodeVersion;
1821
+ this.minimumNodeVersion = minimumNodeVersion;
1822
+ }
1823
+ };
1824
+ }
1825
+ });
1826
+ async function installSkillForRuntime(runtime, deps = {}) {
1827
+ switch (runtime) {
1828
+ case "claude-code":
1829
+ return installSkillFile(
1830
+ resolve(deps.homeDir ?? homedir(), ".claude", "skills", SKILL_FOLDER_NAME),
1831
+ "~/.claude/skills/haven-pay"
1832
+ );
1833
+ case "hermes":
1834
+ return installSkillFile(
1835
+ join(hermesHome(deps), "skills", SKILL_FOLDER_NAME),
1836
+ "the Hermes skills folder"
1837
+ );
1838
+ case "codex-cli":
1839
+ case "codex-desktop":
1840
+ return installCodexAgentsSection(deps);
1841
+ default:
1842
+ return void 0;
1843
+ }
1844
+ }
1845
+ async function installSkillFile(skillDir, label) {
1846
+ try {
1847
+ await mkdir(skillDir, { recursive: true });
1848
+ const target = join(skillDir, "SKILL.md");
1849
+ await writeFile(target, HAVEN_SKILL_MD, "utf8");
1850
+ return {
1851
+ installed: true,
1852
+ target,
1853
+ messages: [`Installed the generic Haven payment skill (${label}). It contains no secrets.`]
1854
+ };
1855
+ } catch (err) {
1856
+ return {
1857
+ installed: false,
1858
+ messages: [
1859
+ `Could not install the Haven payment skill: ${err instanceof Error ? err.message : String(err)}. Download it from the Haven dashboard instead.`
1860
+ ]
1861
+ };
1862
+ }
1863
+ }
1864
+ async function installCodexAgentsSection(deps) {
1865
+ try {
1866
+ const codexDir = resolve(deps.homeDir ?? homedir(), ".codex");
1867
+ const target = join(codexDir, "AGENTS.md");
1868
+ await mkdir(codexDir, { recursive: true });
1869
+ const existing = await readFile(target, "utf8").catch(() => null);
1870
+ const next = upsertManagedSection(existing, codexManagedSection());
1871
+ if (next !== existing) {
1872
+ await writeFile(target, next, "utf8");
1873
+ }
1874
+ return {
1875
+ installed: true,
1876
+ target,
1877
+ messages: [
1878
+ "Installed the generic Haven payment guidance as a managed section in ~/.codex/AGENTS.md (Codex reads it as global instructions). It contains no secrets; your own content in that file is untouched."
1879
+ ]
1880
+ };
1881
+ } catch (err) {
1882
+ return {
1883
+ installed: false,
1884
+ messages: [
1885
+ `Could not install the Haven payment guidance into ~/.codex/AGENTS.md: ${err instanceof Error ? err.message : String(err)}. Download the skill from the Haven dashboard instead.`
1886
+ ]
1887
+ };
1888
+ }
1889
+ }
1890
+ function codexManagedSection() {
1891
+ return `${CODEX_AGENTS_BEGIN_MARKER}
1892
+
1893
+ ${HAVEN_SKILL_BODY_MD.trimEnd()}
1894
+
1895
+ ${CODEX_AGENTS_END_MARKER}
1896
+ `;
1897
+ }
1898
+ function upsertManagedSection(existing, section) {
1899
+ if (existing === null || existing.trim() === "") return section;
1900
+ const begins = markerLineIndexes(existing, CODEX_AGENTS_BEGIN_MARKER);
1901
+ const ends = markerLineIndexes(existing, CODEX_AGENTS_END_MARKER);
1902
+ if (begins.length === 1 && ends.length === 1 && ends[0] > begins[0]) {
1903
+ const afterEnd = ends[0] + CODEX_AGENTS_END_MARKER.length;
1904
+ const tail = existing.startsWith("\r\n", afterEnd) ? existing.slice(afterEnd + 2) : existing.startsWith("\n", afterEnd) ? existing.slice(afterEnd + 1) : existing.slice(afterEnd);
1905
+ return existing.slice(0, begins[0]) + section + tail;
1906
+ }
1907
+ if (begins.length > 0 || ends.length > 0) {
1908
+ throw new Error(
1909
+ "found a damaged Haven marker section (orphaned or duplicated markers); remove the leftover marker lines and re-run setup"
1910
+ );
1911
+ }
1912
+ return `${existing.replace(/\n*$/, "\n\n")}${section}`;
1913
+ }
1914
+ function markerLineIndexes(text, marker) {
1915
+ const indexes = [];
1916
+ for (let from = 0; ; ) {
1917
+ const at = text.indexOf(marker, from);
1918
+ if (at === -1) return indexes;
1919
+ if (at === 0 || text[at - 1] === "\n") indexes.push(at);
1920
+ from = at + marker.length;
1921
+ }
1922
+ }
1923
+ function hermesHome(deps) {
1924
+ const env = deps.env ?? process.env;
1925
+ return env.HERMES_HOME ?? join(deps.homeDir ?? homedir(), ".hermes");
1926
+ }
1927
+ var CODEX_AGENTS_BEGIN_MARKER, CODEX_AGENTS_END_MARKER;
1928
+ var init_skill_install = __esm({
1929
+ "src/skill-install.ts"() {
1930
+ CODEX_AGENTS_BEGIN_MARKER = "<!-- BEGIN haven-pay (managed by @haven_ai/connect; edits inside this section are overwritten on re-setup) -->";
1931
+ CODEX_AGENTS_END_MARKER = "<!-- END haven-pay -->";
1932
+ }
1933
+ });
1934
+
1935
+ // src/connect-error.ts
1936
+ var ConnectError;
1937
+ var init_connect_error = __esm({
1938
+ "src/connect-error.ts"() {
1939
+ ConnectError = class extends Error {
1940
+ code;
1941
+ nextAction;
1942
+ constructor(code, message, nextAction2) {
1943
+ super(message);
1944
+ this.name = "ConnectError";
1945
+ this.code = code;
1946
+ this.nextAction = nextAction2;
1947
+ }
1948
+ };
1949
+ }
1950
+ });
1951
+
1952
+ // src/runtime-registry.ts
1953
+ function runtimeProfile(runtime, env = process.env) {
1954
+ return RUNTIME_PROFILES[normalizeRuntime(runtime, env)];
1955
+ }
1956
+ function normalizeRuntime(runtime, env = process.env) {
1957
+ const explicit = normalizeRuntimeName(runtime);
1958
+ if (explicit) return explicit;
1959
+ return detectRuntime(env) ?? "other";
1960
+ }
1961
+ async function resolveRuntimeSelection(explicit, force, options = {}) {
1962
+ const env = options.env ?? process.env;
1963
+ if (force !== void 0) {
1964
+ const forced = normalizeRuntimeName(force);
1965
+ if (!forced) {
1966
+ throw new ConnectError(
1967
+ "runtime_force_unrecognized",
1968
+ `Unknown --runtime-force value "${force}". Valid values: ${RUNTIME_FLAG_VALUES}.`,
1969
+ "rerun_connect_with_a_valid_runtime_name"
1970
+ );
1971
+ }
1972
+ return { runtime: forced, source: "force" };
1973
+ }
1974
+ const detected = detectRuntime(env);
1975
+ const supplied = explicit?.trim() || options.selfReported?.trim() || void 0;
1976
+ const hint = normalizeRuntimeName(supplied);
1977
+ if (supplied && !hint) {
1978
+ if (!detected) {
1979
+ throw new ConnectError(
1980
+ "runtime_unrecognized",
1981
+ `"${supplied}" is not an agent runtime Haven knows. Valid values: ${RUNTIME_FLAG_VALUES} (the aliases cowork, codex and openclaw are accepted too). Re-run with one of those, or --runtime other to store credentials and finish the MCP setup by hand. Nothing was written and the Haven setup token is still unused.`,
1982
+ "rerun_connect_with_a_valid_runtime_name"
1983
+ );
1984
+ }
1985
+ return { runtime: detected, source: "detected", discardedHint: supplied };
1986
+ }
1987
+ if (detected && hint && detected !== hint) {
1988
+ return { runtime: detected, source: "detected", overrodeHint: hint };
1989
+ }
1990
+ if (hint) return { runtime: hint, source: "explicit" };
1991
+ if (detected) return { runtime: detected, source: "detected" };
1992
+ if (options.promptForRuntime) {
1993
+ return { runtime: await options.promptForRuntime(), source: "prompted" };
1994
+ }
1995
+ return { runtime: null, source: "none" };
1996
+ }
1997
+ function restartRequiredForRuntime(runtime, env = process.env) {
1998
+ const mode = runtimeProfile(runtime, env).restartMode;
1999
+ return mode === "restart-session" || mode === "restart-app";
2000
+ }
2001
+ function runtimeVerificationInstruction(runtime) {
2002
+ const label = RUNTIME_PROFILES[runtime].label;
2003
+ return `In ${label}, run the read-only \`haven_get_agent\` and \`haven_get_allowances\` tools to confirm the Haven wallet and live budget. Do not sign, fund, or create a payment to verify setup.`;
2004
+ }
2005
+ function normalizeRuntimeName(runtime) {
2006
+ const key = runtime?.trim().toLowerCase();
2007
+ if (!key) return null;
2008
+ return RUNTIME_ALIASES[key.replace(/\s+/g, "-")] ?? null;
2009
+ }
2010
+ function detectRuntime(env) {
2011
+ if (env.CLAUDECODE || env.CLAUDE_CODE || env.CLAUDECODE_CWD) return "claude-code";
2012
+ if (env.CODEX_SANDBOX || env.CODEX_HOME || env.CODEX_CWD) return "codex-cli";
2013
+ if (env.VSCODE_CWD || env.VSCODE_IPC_HOOK_CLI || env.TERM_PROGRAM === "vscode") return "vscode";
2014
+ if (env.HERMES_HOME || env.HERMES_AGENT) return "hermes";
2015
+ return null;
2016
+ }
2017
+ var RUNTIME_PROFILES, RUNTIME_ALIASES, RUNTIME_FLAG_VALUES;
2018
+ var init_runtime_registry = __esm({
2019
+ "src/runtime-registry.ts"() {
2020
+ init_connect_error();
2021
+ RUNTIME_PROFILES = {
2022
+ "claude-code": {
2023
+ id: "claude-code",
2024
+ label: "Claude Code",
2025
+ restartMode: "restart-session",
2026
+ canWriteRuntimeConfig: true,
2027
+ activationInstruction: "Start a new Claude Code session so it loads the Haven MCP entries."
2028
+ },
2029
+ "codex-cli": {
2030
+ id: "codex-cli",
2031
+ label: "Codex CLI",
2032
+ restartMode: "restart-session",
2033
+ canWriteRuntimeConfig: true,
2034
+ activationInstruction: "Start a fresh Codex CLI session (for example, run `codex resume --last`)."
2035
+ },
2036
+ "codex-desktop": {
2037
+ id: "codex-desktop",
2038
+ label: "Codex Desktop",
2039
+ restartMode: "restart-session",
2040
+ canWriteRuntimeConfig: true,
2041
+ activationInstruction: "Quit and reopen Codex Desktop so it loads the Haven MCP entries."
2042
+ },
1089
2043
  cursor: {
1090
2044
  id: "cursor",
1091
2045
  label: "Cursor",
@@ -1134,6 +2088,11 @@ var init_runtime_registry = __esm({
1134
2088
  "claude-code": "claude-code",
1135
2089
  claudecode: "claude-code",
1136
2090
  "claude_code": "claude-code",
2091
+ // #1682: Cowork runs Claude Code's config, so it resolves to the same
2092
+ // profile. The dashboard's command carries no --runtime for it (it is a
2093
+ // detected, command-path runtime), but an explicit `--runtime cowork` typed
2094
+ // by hand must not fall through to the no-runtime refusal.
2095
+ cowork: "claude-code",
1137
2096
  codex: "codex-cli",
1138
2097
  "codex-cli": "codex-cli",
1139
2098
  codexcli: "codex-cli",
@@ -1163,9 +2122,18 @@ var init_runtime_registry = __esm({
1163
2122
  "hermes-agent": "hermes",
1164
2123
  hermes_agent: "hermes",
1165
2124
  hermesagent: "hermes",
2125
+ // #1682: OpenClaw is a SNIPPET target — the user pastes an mcpServers entry
2126
+ // into ~/.openclaw/openclaw.json and restarts the gateway. That is exactly
2127
+ // the 'other' profile's behaviour (credentials written to disk, no config
2128
+ // auto-written, manual finish), so it resolves there rather than earning a
2129
+ // profile whose only distinguishing feature would be its label.
2130
+ openclaw: "other",
2131
+ "open-claw": "other",
2132
+ "open_claw": "other",
1166
2133
  other: "other",
1167
2134
  manual: "other"
1168
2135
  };
2136
+ RUNTIME_FLAG_VALUES = "claude-code, codex-cli, codex-desktop, cursor, vscode, vscode-insiders, claude-desktop, hermes, other";
1169
2137
  }
1170
2138
  });
1171
2139
  async function acknowledgeLocalSignerConsent(signerPath, log) {
@@ -1241,1254 +2209,1494 @@ var init_signer_consent = __esm({
1241
2209
  "src/signer-consent.ts"() {
1242
2210
  }
1243
2211
  });
1244
-
1245
- // src/doctor.ts
1246
- var doctor_exports = {};
1247
- __export(doctor_exports, {
1248
- runDoctor: () => runDoctor,
1249
- runRepair: () => runRepair
1250
- });
1251
- async function discoverCredentialDirectory(homeDir, explicit) {
1252
- if (explicit) return { directory: explicit };
1253
- const root = join(homeDir, ".haven", "agents");
1254
- let entries = [];
1255
- try {
1256
- entries = await readdir(root);
1257
- } catch {
1258
- return {};
2212
+ async function installRuntime(input, deps = {}) {
2213
+ const runtime = normalizeRuntime(input.runtime, deps.env);
2214
+ const profile = runtimeProfile(runtime, deps.env);
2215
+ const progress = deps.onProgress ?? (() => void 0);
2216
+ const localRuntime = input.localMcp === true && supportsLocalMcp(runtime);
2217
+ const consentMessages = [];
2218
+ const localMcpConsent = localRuntime ? await resolveLocalMcpConsent(input, consentMessages) : void 0;
2219
+ const signerConsent = localRuntime ? void 0 : await resolveSignerConsent(input, consentMessages);
2220
+ if (runtime === "other") {
2221
+ const signerCredentialReady2 = await probeLocalSignerCredential(input.signerPath);
2222
+ const signerReady = signerCredentialReady2 && signerConsent?.acknowledged;
2223
+ return {
2224
+ runtime,
2225
+ runtimeMcpMode: "manual",
2226
+ hostedMcpConfigured: false,
2227
+ localSignerConfigured: false,
2228
+ localMcpConfigured: false,
2229
+ probeResult: signerReady ? "manual_runtime_setup_required_local_signer_ready" : "manual_runtime_setup_required_local_signer_unavailable",
2230
+ restartRequired: true,
2231
+ nextUserAction: "return_to_haven_for_wallet_approval_then_configure_runtime",
2232
+ errorCode: "manual_runtime_setup_required",
2233
+ configTarget: "manual runtime setup",
2234
+ signerAcknowledged: signerConsent?.acknowledged,
2235
+ localMcpAcknowledged: false,
2236
+ messages: [
2237
+ ...consentMessages,
2238
+ "Custom runtime: Haven did not auto-configure it. Your credentials are on disk (chmod 600) \u2014 read them at runtime; never paste a key into the agent prompt, memory, or logs.",
2239
+ ` identity (hosted MCP Bearer): ${input.identityPath}`,
2240
+ ` signer (local signing key): ${input.signerPath}`,
2241
+ "After wallet approval, wire the runtime to Haven by reference:",
2242
+ ` Hosted MCP + local signer: point your MCP client at ${input.hostedMcpUrl} with the api_key from identity.json, then run npx -y ${signerPackageSpec()} --credentials ${input.signerPath}`,
2243
+ ` Fully local MCP (no hosted dependency): npx -y ${mcpPackageSpec()} --identity ${input.identityPath} --signer ${input.signerPath}`
2244
+ ]
2245
+ };
1259
2246
  }
1260
- const candidates = [];
1261
- for (const entry of entries) {
1262
- const directory = join(root, entry);
2247
+ let localRuntimeInstall;
2248
+ let localRuntimeError;
2249
+ if (localRuntime) {
1263
2250
  try {
1264
- const s = await stat(join(directory, "identity.json"));
1265
- candidates.push({ directory, mtimeMs: s.mtimeMs });
1266
- } catch {
1267
- }
1268
- }
1269
- if (candidates.length === 0) return {};
1270
- candidates.sort((a, b) => b.mtimeMs - a.mtimeMs);
1271
- return {
1272
- directory: candidates[0].directory,
1273
- note: candidates.length > 1 ? `${candidates.length} agent credential dirs found; examining the newest.` : void 0
1274
- };
1275
- }
1276
- async function runDoctor(input, deps = {}) {
1277
- const homeDir = deps.homeDir ?? homedir();
1278
- const checks = [];
1279
- let signerCapabilities;
1280
- const { directory, note } = await discoverCredentialDirectory(homeDir, input.credentialsDir);
1281
- let identity;
1282
- let signerParses = false;
1283
- if (!directory) {
1284
- checks.push({
1285
- id: "credentials",
1286
- label: "Agent credentials",
1287
- ok: false,
1288
- detail: "No agent credential directory with an identity.json under ~/.haven/agents.",
1289
- repair: `Run the full setup once: ${RERUN} --setup <token from the Haven dashboard>.`
1290
- });
1291
- } else {
1292
- try {
1293
- identity = JSON.parse(await readFile(join(directory, "identity.json"), "utf8"));
1294
- } catch {
1295
- identity = void 0;
1296
- }
1297
- try {
1298
- const signer = JSON.parse(await readFile(join(directory, "signer.json"), "utf8"));
1299
- signerParses = typeof signer === "object" && signer !== null;
1300
- } catch {
1301
- signerParses = false;
1302
- }
1303
- const ok = Boolean(identity?.api_key) && signerParses;
1304
- checks.push({
1305
- id: "credentials",
1306
- label: "Agent credentials",
1307
- ok,
1308
- detail: ok ? `identity.json and signer.json parse (agent ${identity?.agent_id ?? "unknown"})${note ? ` \u2014 ${note}` : ""}` : "identity.json or signer.json is missing or unparseable.",
1309
- ...ok ? {} : { repair: `Re-run the full setup with a fresh token: ${RERUN} --setup <token>.` }
1310
- });
1311
- }
1312
- let sidecar = null;
1313
- if (directory) {
1314
- sidecar = await readRuntimeSidecar(directory);
1315
- if (!sidecar) {
1316
- checks.push({
1317
- id: "signer_runtime",
1318
- label: "Signer runtime (preinstalled wrapper)",
1319
- ok: false,
1320
- detail: "No signer-runtime.json sidecar \u2014 the pinned signer runtime was never prepared (or a pre-#1586 npx config).",
1321
- repair: `Run: ${RERUN} --doctor --repair --runtime ${input.runtime}`
1322
- });
1323
- } else {
1324
- const matches = await installedRuntimeMatches(sidecar.runtime_directory, sidecar.cli_path);
1325
- const versionOk = sidecar.signer_version === MCP_RUNTIME_MANIFEST.signerVersion;
1326
- const ok = matches && versionOk;
1327
- checks.push({
1328
- id: "signer_runtime",
1329
- label: "Signer runtime (preinstalled wrapper)",
1330
- ok,
1331
- detail: ok ? `Installed ${sidecar.signer_package}@${sidecar.signer_version} at ${sidecar.runtime_directory}` : matches ? `Installed version ${sidecar.signer_version} does not match the connector's pinned ${MCP_RUNTIME_MANIFEST.signerVersion}.` : `Runtime directory is stale or empty (${sidecar.runtime_directory}) \u2014 the CLI or package versions are missing.`,
1332
- ...ok ? {} : { repair: `Run: ${RERUN} --doctor --repair --runtime ${input.runtime}` }
1333
- });
1334
- }
1335
- }
1336
- const configPath = runtimeConfigPathFor(input.runtime, homeDir);
1337
- if (configPath === null) {
1338
- checks.push({
1339
- id: "runtime_config",
1340
- label: "Runtime MCP config",
1341
- ok: true,
1342
- detail: `Runtime '${input.runtime}' has no file-based config the connector owns (CLI-managed) \u2014 skipping the file check.`
1343
- });
1344
- } else {
1345
- let configText = null;
1346
- try {
1347
- configText = await readFile(configPath, "utf8");
1348
- } catch {
1349
- configText = null;
1350
- }
1351
- if (configText === null) {
1352
- checks.push({
1353
- id: "runtime_config",
1354
- label: "Runtime MCP config",
1355
- ok: false,
1356
- detail: `No runtime config at ${configPath}.`,
1357
- repair: `Run: ${RERUN} --doctor --repair --runtime ${input.runtime}`
1358
- });
1359
- } else {
1360
- const hasHaven = identity?.hosted_mcp_url ? configText.includes(identity.hosted_mcp_url) : configText.includes("haven");
1361
- const signerViaNpx = configText.includes("@haven_ai/signer");
1362
- const wrapperReferenced = sidecar ? configText.includes(sidecar.wrapper_path) : false;
1363
- const ok = hasHaven && !signerViaNpx && (sidecar ? wrapperReferenced : true);
1364
- checks.push({
1365
- id: "runtime_config",
1366
- label: "Runtime MCP config",
1367
- ok,
1368
- 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${sidecar && !wrapperReferenced ? " (or references a different signer wrapper)" : ""}.`,
1369
- ...ok ? {} : { repair: `Run: ${RERUN} --doctor --repair --runtime ${input.runtime}` }
1370
- });
1371
- }
1372
- }
1373
- if (identity?.api_key && (identity.hosted_mcp_url || identity.api_url)) {
1374
- const hostedUrl = identity.hosted_mcp_url ?? `${identity.api_url}/mcp`;
1375
- const probe = await (deps.probeHosted ?? probeHostedMcpTools)(identity.api_key, hostedUrl, deps.fetch);
1376
- checks.push({
1377
- id: "hosted_mcp",
1378
- label: "Hosted Haven MCP",
1379
- ok: probe.status === "ok",
1380
- detail: probe.status === "ok" ? `Reachable and authorized (${hostedUrl}).` : `Probe failed: ${probe.status} (${hostedUrl}).`,
1381
- ...probe.status === "ok" ? {} : {
1382
- repair: probe.status === "unauthorized" ? `The stored API key was rejected \u2014 re-run the full setup with a fresh token: ${RERUN} --setup <token>.` : "Check network access to the hosted MCP URL, then re-run --doctor."
1383
- }
1384
- });
1385
- } else {
1386
- checks.push({
1387
- id: "hosted_mcp",
1388
- label: "Hosted Haven MCP",
1389
- ok: false,
1390
- detail: "No stored API key / hosted MCP URL to probe with.",
1391
- repair: `Re-run the full setup: ${RERUN} --setup <token>.`
1392
- });
1393
- }
1394
- if (sidecar && directory) {
1395
- const consent = await getLocalSignerConsentStatus(join(directory, "signer.json"));
1396
- if (!consent.acknowledged) {
1397
- checks.push({
1398
- id: "signer_process",
1399
- label: "Signer stdio handshake",
1400
- ok: false,
1401
- detail: "The local-tools consent is not acknowledged, so the signer refuses to start (by design).",
1402
- repair: `Run: ${RERUN} --ack-local-tools --setup <token> (or re-run your original setup command with --ack-local-tools).`
1403
- });
1404
- } else {
1405
- const probe = await (deps.probeSignerTools ?? probeLocalMcpTools)(
1406
- sidecar.wrapper_path,
1407
- [],
1408
- MCP_RUNTIME_MANIFEST.requiredSignerTools
1409
- );
1410
- const experimental = probe.capabilities?.experimental ?? probe.capabilities;
1411
- const compat = experimental?.["haven/signer-compatibility"];
1412
- signerCapabilities = compat ? { "haven/signer-compatibility": compat } : void 0;
1413
- const compatDetail = compat ? ` Compat: x402 expected-context v${JSON.stringify(compat.x402_expected_context_versions ?? "?")}.` : "";
1414
- checks.push({
1415
- id: "signer_process",
1416
- label: "Signer stdio handshake",
1417
- ok: probe.status === "ok",
1418
- detail: probe.status === "ok" ? `Signer started, listed ${probe.toolNames?.length ?? 0} tools${probe.serverInfo?.version ? ` (v${probe.serverInfo.version})` : ""}.${compatDetail}` : `Handshake failed: ${probe.status}.`,
1419
- ...probe.status === "ok" ? {} : { repair: `Run: ${RERUN} --doctor --repair --runtime ${input.runtime}` }
1420
- });
2251
+ localRuntimeInstall = await prepareRuntimeForLocalMcp(input, deps);
2252
+ } catch (err) {
2253
+ localRuntimeError = err;
1421
2254
  }
1422
- } else if (directory) {
1423
- checks.push({
1424
- id: "signer_process",
1425
- label: "Signer stdio handshake",
1426
- ok: false,
1427
- detail: "Skipped \u2014 no prepared signer runtime to probe.",
1428
- repair: `Run: ${RERUN} --doctor --repair --runtime ${input.runtime}`
1429
- });
1430
2255
  }
1431
- const restart = restartRequiredForRuntime(input.runtime, deps.env);
1432
- checks.push({
1433
- id: "restart",
1434
- label: "Runtime restart",
1435
- ok: true,
1436
- detail: restart ? "This runtime loads MCP config at startup \u2014 restart it after any repair before expecting the tools to appear." : "No restart requirement known for this runtime."
1437
- });
1438
- return {
1439
- version: 1,
1440
- ok: checks.every((check) => check.ok),
1441
- runtime: input.runtime,
1442
- credentialDirectory: directory,
1443
- checks,
1444
- ...signerCapabilities ? { signerCapabilities } : {}
1445
- };
1446
- }
1447
- async function runRepair(input, deps = {}) {
1448
- const homeDir = deps.homeDir ?? homedir();
1449
- const messages = [];
1450
- const { directory, note } = await discoverCredentialDirectory(homeDir, input.credentialsDir);
1451
- if (note) messages.push(`Note: ${note}`);
1452
- if (!directory) {
2256
+ if (localRuntimeError) {
2257
+ const errorCode2 = localRuntimePrepareErrorCode(localRuntimeError);
1453
2258
  return {
1454
- ok: false,
1455
- messages: [`No agent credentials found to repair \u2014 run the full setup: ${RERUN} --setup <token>.`]
2259
+ runtime,
2260
+ runtimeMcpMode: "local_stdio",
2261
+ hostedMcpConfigured: false,
2262
+ localSignerConfigured: false,
2263
+ localMcpConfigured: false,
2264
+ probeResult: errorCode2 === "local_mcp_unsupported_node_version" ? "local_stdio_mcp_unsupported_node_version" : "local_stdio_mcp_runtime_install_failed",
2265
+ restartRequired: true,
2266
+ nextUserAction: nextAction(runtime, profile.restartMode, errorCode2),
2267
+ errorCode: errorCode2,
2268
+ configTarget: profile.label,
2269
+ signerAcknowledged: signerConsent?.acknowledged,
2270
+ localMcpAcknowledged: localMcpConsent?.acknowledged,
2271
+ activationCommand: void 0,
2272
+ messages: [
2273
+ ...consentMessages,
2274
+ `Could not prepare local Haven MCP runtime: ${localRuntimeError instanceof Error ? localRuntimeError.message : String(localRuntimeError)}`
2275
+ ]
1456
2276
  };
1457
2277
  }
1458
- let identity;
1459
- try {
1460
- identity = JSON.parse(await readFile(join(directory, "identity.json"), "utf8"));
1461
- } catch {
1462
- return { ok: false, messages: ["identity.json is unreadable \u2014 re-run the full setup with a fresh token."] };
1463
- }
1464
- if (!identity.api_key || !(identity.hosted_mcp_url || identity.api_url)) {
1465
- return { ok: false, messages: ["identity.json lacks the stored API key / hosted URL \u2014 re-run the full setup."] };
1466
- }
1467
- const configPath = runtimeConfigPathFor(input.runtime, homeDir);
1468
- if (configPath) {
2278
+ let signerCommand;
2279
+ if (!localRuntime) {
2280
+ progress("Getting the signer ready\u2026");
1469
2281
  try {
1470
- const existing = await readFile(configPath, "utf8");
1471
- if (existing.includes("bin/haven-mcp") || existing.includes(".haven/mcp-runtime")) {
1472
- return {
1473
- ok: false,
1474
- messages: [
1475
- `The config at ${configPath} is the LOCAL-stdio topology (--local). Repair currently rewrites only the hosted+signer shape and will not touch it.`,
1476
- "Re-run your original setup command (with --local) to repair a local-stdio install."
1477
- ]
1478
- };
1479
- }
1480
- } catch {
2282
+ const signerRuntime = await prepareSignerForRuntime(input, deps);
2283
+ signerCommand = { command: signerRuntime.command, args: signerRuntime.args };
2284
+ consentMessages.push(...signerRuntime.messages);
2285
+ } catch (err) {
2286
+ return {
2287
+ runtime,
2288
+ runtimeMcpMode: "hosted_plus_signer",
2289
+ hostedMcpConfigured: false,
2290
+ localSignerConfigured: false,
2291
+ localMcpConfigured: false,
2292
+ probeResult: "signer_runtime_install_failed",
2293
+ restartRequired: false,
2294
+ nextUserAction: "The local Haven signer runtime could not be installed, so no configuration was written. Check your network (a cold install downloads the signer package set) and re-run: npx @haven_ai/connect@alpha",
2295
+ errorCode: "signer_runtime_install_failed",
2296
+ configTarget: profile.label,
2297
+ signerAcknowledged: signerConsent?.acknowledged,
2298
+ localMcpAcknowledged: localMcpConsent?.acknowledged,
2299
+ activationCommand: void 0,
2300
+ signerRuntimePrepared: false,
2301
+ messages: [
2302
+ ...consentMessages,
2303
+ `Could not pre-install the local Haven signer: ${err instanceof Error ? err.message : String(err)}`,
2304
+ "No runtime configuration was written (fail-closed): a config pointing at an uninstalled signer looks wired but cannot start.",
2305
+ "Re-run `npx @haven_ai/connect@alpha` to retry the setup."
2306
+ ]
2307
+ };
1481
2308
  }
1482
2309
  }
1483
- const signerPath = join(directory, "signer.json");
1484
- const prepared = await prepareSignerRuntime(
1485
- { credentialDirectory: directory, signerPath, homeDir },
1486
- { runCommand: deps.runCommand }
1487
- );
1488
- messages.push(...prepared.messages);
1489
- const configResult = await writeRuntimeConfig({
1490
- runtime: input.runtime,
1491
- hostedMcpUrl: identity.hosted_mcp_url ?? `${identity.api_url}/mcp`,
1492
- apiKey: identity.api_key,
1493
- identityPath: join(directory, "identity.json"),
1494
- signerPath,
1495
- credentialDirectory: directory,
1496
- signerCommand: { command: prepared.command, args: prepared.args },
1497
- homeDir,
1498
- mode: "hosted"
1499
- });
1500
- messages.push(...configResult.messages);
1501
- messages.push("Repair complete \u2014 restart the runtime, then verify with --doctor.");
1502
- return { ok: true, messages };
1503
- }
1504
- var RERUN;
1505
- var init_doctor = __esm({
1506
- "src/doctor.ts"() {
1507
- init_runtime_manifest();
1508
- init_probes();
1509
- init_signer_runtime();
1510
- init_config_writers();
1511
- init_runtime_registry();
1512
- init_signer_consent();
1513
- RERUN = "npx @haven_ai/connect@alpha";
1514
- }
1515
- });
1516
-
1517
- // src/api.ts
1518
- function createConnectApiClient(baseUrl, fetchImpl = fetch) {
1519
- const root = baseUrl.replace(/\/+$/, "");
1520
- return {
1521
- resolveSetup: (input) => request(fetchImpl, `${root}/agent-connection-setups/resolve`, {
1522
- method: "POST",
1523
- body: JSON.stringify({
1524
- setup_token: input.setupToken,
1525
- connector_version: input.connectorVersion,
1526
- runtime: input.runtime
1527
- })
1528
- }),
1529
- registerSetup: (input) => request(fetchImpl, `${root}/agent-connection-setups/register`, {
1530
- method: "POST",
1531
- body: JSON.stringify({
1532
- setup_token: input.setupToken,
1533
- challenge_id: input.challengeId,
1534
- delegate_address: input.delegateAddress,
1535
- proof_signature: input.proofSignature,
1536
- api_key_hash: input.apiKeyHash,
1537
- api_key_prefix: input.apiKeyPrefix,
1538
- runtime: input.runtime,
1539
- connector_version: input.connectorVersion,
1540
- connector_context: input.connectorContext,
1541
- install_capabilities: input.installCapabilities && {
1542
- can_write_runtime_config: input.installCapabilities.canWriteRuntimeConfig,
1543
- restart_required: input.installCapabilities.restartRequired
1544
- }
1545
- })
1546
- }),
1547
- getConnectorStatus: (setupId, apiKey) => request(fetchImpl, `${root}/agent-connection-setups/${encodeURIComponent(setupId)}/connector-status`, {
1548
- method: "GET",
1549
- headers: { Authorization: `Bearer ${apiKey}` }
1550
- }),
1551
- updateInstallStatus: async (setupId, apiKey, input) => {
1552
- await request(fetchImpl, `${root}/agent-connection-setups/${encodeURIComponent(setupId)}/install-status`, {
1553
- method: "POST",
1554
- headers: { Authorization: `Bearer ${apiKey}` },
1555
- body: JSON.stringify({
1556
- runtime: input.runtime,
1557
- connector_version: input.connectorVersion,
1558
- runtime_mcp_mode: input.runtimeMcpMode,
1559
- hosted_mcp_configured: input.hostedMcpConfigured,
1560
- local_signer_configured: input.localSignerConfigured,
1561
- local_mcp_configured: input.localMcpConfigured,
1562
- credential_files_written: input.credentialFilesWritten,
1563
- signer_acknowledged: input.signerAcknowledged,
1564
- local_mcp_acknowledged: input.localMcpAcknowledged,
1565
- activation_command_available: input.activationCommandAvailable,
1566
- skill_installed: input.skillInstalled,
1567
- probe_result: input.probeResult,
1568
- restart_required: input.restartRequired,
1569
- next_user_action: input.nextUserAction,
1570
- error_code: input.errorCode ?? null,
1571
- environment_label: input.environmentLabel
1572
- })
2310
+ const signerRuntimePrepared = localRuntime ? void 0 : signerCommand !== void 0;
2311
+ progress("Setting up your Haven tools\u2026");
2312
+ const configResult = localRuntime ? runtime === "claude-code" ? await configureClaudeCode(deps, localRuntimeInstall?.command ?? "", input.serverName) : await writeRuntimeConfig({
2313
+ runtime,
2314
+ hostedMcpUrl: input.hostedMcpUrl,
2315
+ apiKey: input.apiKey,
2316
+ identityPath: input.identityPath,
2317
+ signerPath: input.signerPath,
2318
+ serverName: input.serverName,
2319
+ credentialDirectory: input.credentialDirectory,
2320
+ localMcpCommand: localRuntimeInstall?.command,
2321
+ signerCommand,
2322
+ homeDir: deps.homeDir,
2323
+ mode: "local"
2324
+ }) : await writeHostedRuntimeConfig(deps, { ...input, runtime }, signerCommand);
2325
+ if (deps.onRuntimeConfigured) {
2326
+ const signerCredentialOnDisk = await probeLocalSignerCredential(input.signerPath);
2327
+ const earlyLocalMcpOk = configResult.runtimeMcpMode === "local_stdio" && configResult.localMcpConfigured && signerCredentialOnDisk && Boolean(localMcpConsent?.acknowledged);
2328
+ const earlySignerOk = configResult.runtimeMcpMode === "local_stdio" ? earlyLocalMcpOk : configResult.signerConfigured && signerCredentialOnDisk && Boolean(signerConsent?.acknowledged);
2329
+ try {
2330
+ await deps.onRuntimeConfigured({
2331
+ runtime,
2332
+ runtimeMcpMode: configResult.runtimeMcpMode,
2333
+ hostedMcpConfigured: configResult.hostedConfigured,
2334
+ localSignerConfigured: earlySignerOk,
2335
+ localMcpConfigured: earlyLocalMcpOk,
2336
+ signerAcknowledged: signerConsent?.acknowledged,
2337
+ localMcpAcknowledged: localMcpConsent?.acknowledged,
2338
+ restartRequired: configResult.restartRequired || restartRequiredForRuntime(runtime, deps.env),
2339
+ nextUserAction: nextAction(runtime, profile.restartMode, configResult.errorCode),
2340
+ errorCode: configResult.errorCode
1573
2341
  });
2342
+ } catch {
1574
2343
  }
1575
- };
1576
- }
1577
- var ConnectRequestError = class extends Error {
1578
- constructor(message, status) {
1579
- super(message);
1580
- this.status = status;
1581
- this.name = "ConnectRequestError";
1582
- }
1583
- status;
1584
- };
1585
- async function request(fetchImpl, url, init) {
1586
- const response = await fetchImpl(url, {
1587
- ...init,
1588
- headers: {
1589
- "Content-Type": "application/json",
1590
- ...init.headers ?? {}
1591
- }
1592
- });
1593
- const text = await response.text();
1594
- const body = text ? JSON.parse(text) : null;
1595
- if (!response.ok) {
1596
- const message = body?.error ?? body?.message ?? `${response.status} ${response.statusText}`;
1597
- throw new ConnectRequestError(`Haven setup request failed: ${message}`, response.status);
1598
- }
1599
- return body;
1600
- }
1601
- function generateDelegateKey() {
1602
- return delegateKeyFromPrivateKey(Wallet.createRandom().privateKey);
1603
- }
1604
- function delegateKeyFromPrivateKey(privateKey) {
1605
- const wallet = new Wallet(privateKey);
1606
- return {
1607
- privateKey: wallet.privateKey,
1608
- address: wallet.address,
1609
- signChallenge: (message) => wallet.signMessage(message)
1610
- };
1611
- }
1612
- function generateAgentApiKey() {
1613
- return `sk_agent_${crypto.randomBytes(24).toString("hex")}`;
1614
- }
1615
- function hashAgentApiKey(apiKey) {
1616
- return crypto.createHash("sha256").update(apiKey).digest("hex");
1617
- }
1618
- function agentApiKeyPrefix(apiKey) {
1619
- return apiKey.slice(0, 12);
1620
- }
1621
-
1622
- // src/redact.ts
1623
- var API_KEY_RE = /sk_agent_[A-Za-z0-9]+/g;
1624
- var PRIVATE_KEY_RE = /0x[0-9a-fA-F]{64}/g;
1625
- function redactSecrets(value) {
1626
- return value.replace(API_KEY_RE, "sk_agent_[redacted]").replace(PRIVATE_KEY_RE, "0x[redacted-private-key]");
1627
- }
1628
- function shortAddress(address) {
1629
- if (!/^0x[0-9a-fA-F]{40}$/.test(address)) return address;
1630
- return `${address.slice(0, 6)}...${address.slice(-4)}`;
1631
- }
1632
- async function preflightCredentialStorage(input = {}) {
1633
- const directory = defaultCredentialRoot(input.baseDir);
1634
- await mkdir(directory, { recursive: true, mode: 448 });
1635
- await restrictPermissions(directory, 448, input.warn);
1636
- const probePath = join(directory, `.haven-connect-preflight-${crypto.randomBytes(8).toString("hex")}`);
1637
- try {
1638
- await writeOwnerOnlyJson(probePath, { ok: true }, input.warn);
1639
- } finally {
1640
- await rm(probePath, { force: true }).catch(() => void 0);
1641
2344
  }
1642
- return directory;
1643
- }
1644
- async function writeCredentialFiles(input) {
1645
- const directory = defaultAgentDirectory(input.agentId, input.baseDir);
1646
- await mkdir(directory, { recursive: true, mode: 448 });
1647
- await restrictPermissions(directory, 448, input.warn);
1648
- const identityPath = join(directory, "identity.json");
1649
- const signerPath = join(directory, "signer.json");
1650
- const agentPath = join(directory, "agent.json");
1651
- await assertDoesNotExist(identityPath);
1652
- await assertDoesNotExist(signerPath);
1653
- await assertDoesNotExist(agentPath);
1654
- await writeOwnerOnlyJson(
1655
- signerPath,
1656
- {
1657
- delegate_key: input.delegateKey,
1658
- delegate_address: input.delegateAddress,
1659
- agent_id: input.agentId,
1660
- safe_address: input.safeAddress,
1661
- chain_id: input.chainId,
1662
- network: input.network,
1663
- x402_binding_signer: input.x402BindingSigner,
1664
- note: "Local signer credential. Haven backend never receives this private key."
1665
- },
1666
- input.warn
1667
- );
1668
- try {
1669
- await writeOwnerOnlyJson(
1670
- identityPath,
1671
- {
1672
- api_key: input.apiKey,
1673
- agent_id: input.agentId,
1674
- safe_address: input.safeAddress,
1675
- chain_id: input.chainId,
1676
- network: input.network,
1677
- api_url: input.apiUrl,
1678
- hosted_mcp_url: input.hostedMcpUrl,
1679
- agent_budget: input.agentBudget,
1680
- note: "Haven API key identifies the agent only. It cannot spend without the local signer key and on-chain Haven wallet rules."
1681
- },
1682
- input.warn
1683
- );
1684
- } catch (err) {
1685
- await rm(signerPath, { force: true }).catch(() => void 0);
1686
- throw err;
1687
- }
1688
- try {
1689
- await writeOwnerOnlyJson(
1690
- agentPath,
1691
- {
1692
- agent_id: input.agentId,
1693
- delegate_address: input.delegateAddress,
1694
- safe_address: input.safeAddress,
1695
- chain_id: input.chainId,
1696
- network: input.network,
1697
- agent_budget: input.agentBudget,
1698
- note: "Non-secret orientation for the agent: public delegate/Haven wallet identity + configured budget. Contains no API key or signing key. For the live remaining budget, call haven_get_allowances."
1699
- },
1700
- input.warn
1701
- );
1702
- } catch (err) {
1703
- await rm(signerPath, { force: true }).catch(() => void 0);
1704
- await rm(identityPath, { force: true }).catch(() => void 0);
1705
- await rm(agentPath, { force: true }).catch(() => void 0);
1706
- throw err;
1707
- }
1708
- return { directory, identityPath, signerPath, agentPath };
1709
- }
1710
- function defaultAgentDirectory(agentId, baseDir = join(homedir(), ".haven", "agents")) {
1711
- return resolve(defaultCredentialRoot(baseDir), safePathPart(agentId));
1712
- }
1713
- function defaultCredentialRoot(baseDir = join(homedir(), ".haven", "agents")) {
1714
- return resolve(baseDir);
1715
- }
1716
- async function writeOwnerOnlyJson(path, value, warn) {
1717
- const json = JSON.stringify(dropUndefined(value), null, 2);
1718
- await writeFile(path, `${json}
1719
- `, { mode: 384, flag: "wx" });
1720
- await restrictPermissions(path, 384, warn);
1721
- }
1722
- function safePathPart(value) {
1723
- return value.replace(/[^A-Za-z0-9_.-]/g, "_");
1724
- }
1725
- function dropUndefined(value) {
1726
- return Object.fromEntries(Object.entries(value).filter(([, field]) => field !== void 0));
1727
- }
1728
- async function assertDoesNotExist(path) {
1729
- try {
1730
- await access(path);
1731
- } catch (err) {
1732
- if (err && typeof err === "object" && "code" in err && err.code === "ENOENT") return;
1733
- throw err;
1734
- }
1735
- throw new Error(`Refusing to overwrite existing Haven credential file: ${path}`);
2345
+ progress("Almost there \u2014 just confirming everything connects\u2026");
2346
+ const localProbePromise = configResult.runtimeMcpMode === "local_stdio" && localRuntimeInstall ? runLocalMcpProbe(localRuntimeInstall, deps) : Promise.resolve(void 0);
2347
+ const signerProbePromise = configResult.runtimeMcpMode !== "local_stdio" && signerCommand ? (deps.probeSignerTools ?? probeLocalMcpTools)(
2348
+ signerCommand.command,
2349
+ signerCommand.args,
2350
+ MCP_RUNTIME_MANIFEST.requiredSignerTools
2351
+ ) : Promise.resolve(void 0);
2352
+ const [hostedProbe, signerCredentialReady, localMcpProbe, signerProbe] = await Promise.all([
2353
+ configResult.hostedConfigured ? probeHostedMcpTools(input.apiKey, input.hostedMcpUrl, deps.fetch) : Promise.resolve({ status: "bad_response" }),
2354
+ probeLocalSignerCredential(input.signerPath),
2355
+ localProbePromise,
2356
+ signerProbePromise
2357
+ ]);
2358
+ const hostedOk = configResult.hostedConfigured && hostedProbe.status === "ok";
2359
+ const localMcpOk = configResult.runtimeMcpMode === "local_stdio" && configResult.localMcpConfigured && signerCredentialReady && Boolean(localMcpConsent?.acknowledged) && localMcpProbe?.status === "ok";
2360
+ const signerOk = configResult.runtimeMcpMode === "local_stdio" ? localMcpOk : configResult.signerConfigured && signerCredentialReady && Boolean(signerConsent?.acknowledged) && // #1587: no handshake, no green. A signer command that was registered
2361
+ // but not probed (manual topology) keeps the old semantics.
2362
+ (signerProbe === void 0 || signerProbe.status === "ok");
2363
+ const restartRequired = configResult.restartRequired || restartRequiredForRuntime(runtime, deps.env);
2364
+ const errorCode = configResult.errorCode ?? (configResult.runtimeMcpMode === "local_stdio" ? localMcpErrorCode(signerCredentialReady, localMcpConsent, localMcpProbe?.status) : hostedMcpErrorCode(configResult.hostedConfigured, hostedProbe.status) ?? signerConsentErrorCode(signerCredentialReady, signerConsent) ?? signerProbeErrorCode(signerProbe));
2365
+ const hostedProbeMessages = configResult.hostedConfigured && hostedProbe.status !== "ok" ? [`Hosted Haven MCP probe failed: ${hostedProbe.status}.`] : configResult.hostedConfigured ? ["Verified hosted Haven MCP tools with a read-only handshake."] : [];
2366
+ const signerProbeMessages = signerProbe ? signerProbe.status === "ok" ? ["Verified local Haven signer with a stdio handshake."] : [
2367
+ `Local Haven signer handshake failed: ${signerProbe.status}.`,
2368
+ "Re-run `npx @haven_ai/connect@alpha` to repair the signer setup."
2369
+ ] : [];
2370
+ const localProbeMessages = localMcpProbe && localMcpProbe.status !== "ok" ? [`Local Haven MCP handshake failed: ${localMcpProbe.status}.`] : localMcpProbe?.status === "ok" ? ["Verified local Haven MCP tools with a stdio handshake."] : [];
2371
+ const skillInstall = !configResult.errorCode ? await installSkillForRuntime(runtime, { homeDir: deps.homeDir, env: deps.env }) : void 0;
2372
+ return {
2373
+ runtime,
2374
+ runtimeMcpMode: configResult.runtimeMcpMode,
2375
+ hostedMcpConfigured: hostedOk,
2376
+ localSignerConfigured: signerOk,
2377
+ localMcpConfigured: localMcpOk,
2378
+ probeResult: buildProbeResult(configResult.runtimeMcpMode, configResult.hostedConfigured, hostedProbe.status, signerOk, localMcpOk, localMcpProbe?.status),
2379
+ restartRequired,
2380
+ nextUserAction: nextAction(runtime, profile.restartMode, errorCode),
2381
+ errorCode,
2382
+ configTarget: configResult.target,
2383
+ signerAcknowledged: signerConsent?.acknowledged,
2384
+ localMcpAcknowledged: localMcpConsent?.acknowledged,
2385
+ activationCommand: configResult.activationCommand,
2386
+ skillInstalled: skillInstall?.installed,
2387
+ signerRuntimePrepared,
2388
+ messages: [...consentMessages, ...localRuntimeInstall?.messages ?? [], ...configResult.messages, ...hostedProbeMessages, ...signerProbeMessages, ...localProbeMessages, ...skillInstall?.messages ?? []]
2389
+ };
1736
2390
  }
1737
- async function restrictPermissions(path, mode, warn) {
1738
- try {
1739
- await chmod(path, mode);
1740
- } catch (err) {
1741
- warn?.(
1742
- `Warning: could not restrict permissions on ${path} to ${mode.toString(8)}. Move this credential to a private location or run chmod ${mode.toString(8)} ${path}. ${err instanceof Error ? err.message : String(err)}`
1743
- );
1744
- }
2391
+ function runtimeInstallCapabilities(runtime, env = process.env) {
2392
+ const profile = runtimeProfile(runtime, env);
2393
+ return {
2394
+ canWriteRuntimeConfig: profile.canWriteRuntimeConfig,
2395
+ restartRequired: restartRequiredForRuntime(runtime, env)
2396
+ };
1745
2397
  }
1746
-
1747
- // src/runtime-install.ts
1748
- init_config_writers();
1749
- async function acknowledgeLocalMcpConsent(identityPath, signerPath, log) {
2398
+ async function configureClaudeCode(deps, localMcpCommand, serverName) {
2399
+ const runCommand = deps.runCommand ?? defaultRunCommand;
2400
+ const serverJson = JSON.stringify({
2401
+ type: "stdio",
2402
+ command: localMcpCommand,
2403
+ args: [],
2404
+ env: {}
2405
+ });
1750
2406
  try {
1751
- const input = await buildLocalMcpConsentInput(identityPath, signerPath);
1752
- const decision = await ensureConsent(input, {
1753
- credentialsPath: identityPath,
1754
- writeAck: true,
1755
- out: log ? { write: (chunk) => writeLogChunk(log, chunk) } : void 0
2407
+ if (!localMcpCommand) throw new Error("local MCP wrapper command is required");
2408
+ const names = serverNamesFor(serverName);
2409
+ await runCommand("claude", ["mcp", "remove", names.hosted]).catch(() => void 0);
2410
+ await runCommand("claude", ["mcp", "remove", names.signer]).catch(() => void 0);
2411
+ await runCommand("claude", ["mcp", "add-json", names.hosted, serverJson, "--scope", "user"]).catch(async () => {
2412
+ await runCommand("claude", ["mcp", "add", names.hosted, "--scope", "user", "--", localMcpCommand]);
1756
2413
  });
2414
+ const verified = await runCommand("claude", ["mcp", "get", names.hosted]).then(() => true).catch(() => false);
1757
2415
  return {
1758
- acknowledged: decision.ok,
1759
- hash: decision.hash,
1760
- reason: decision.reason
2416
+ hostedConfigured: false,
2417
+ signerConfigured: true,
2418
+ localMcpConfigured: true,
2419
+ runtimeMcpMode: "local_stdio",
2420
+ target: "Claude Code MCP config",
2421
+ changed: true,
2422
+ restartRequired: true,
2423
+ messages: [
2424
+ "Updated local Haven MCP entry with Claude Code.",
2425
+ ...verified ? ["Verified Claude Code MCP entry."] : []
2426
+ ]
1761
2427
  };
1762
2428
  } catch (err) {
1763
2429
  return {
1764
- acknowledged: false,
1765
- error: err instanceof Error ? err.message : String(err)
2430
+ hostedConfigured: false,
2431
+ signerConfigured: false,
2432
+ localMcpConfigured: false,
2433
+ runtimeMcpMode: "local_stdio",
2434
+ target: "Claude Code MCP config",
2435
+ changed: false,
2436
+ restartRequired: true,
2437
+ messages: [
2438
+ `Could not update Claude Code MCP config: ${err instanceof Error ? err.message : String(err)}`,
2439
+ "Install Claude Code or rerun the Haven setup command inside a Claude Code terminal."
2440
+ ],
2441
+ errorCode: "claude_code_config_failed"
1766
2442
  };
1767
2443
  }
1768
2444
  }
1769
- async function getLocalMcpConsentStatus(identityPath, signerPath) {
2445
+ async function writeHostedRuntimeConfig(deps, input, signerCommand) {
2446
+ if (input.runtime === "claude-code") {
2447
+ return configureClaudeCodeHosted(deps, input, signerCommand);
2448
+ }
2449
+ return writeRuntimeConfig({
2450
+ runtime: input.runtime,
2451
+ hostedMcpUrl: input.hostedMcpUrl,
2452
+ apiKey: input.apiKey,
2453
+ identityPath: input.identityPath,
2454
+ signerPath: input.signerPath,
2455
+ serverName: input.serverName,
2456
+ credentialDirectory: input.credentialDirectory,
2457
+ signerCommand,
2458
+ homeDir: deps.homeDir,
2459
+ mode: "hosted"
2460
+ });
2461
+ }
2462
+ async function configureClaudeCodeHosted(deps, input, signerCommand) {
2463
+ const runCommand = deps.runCommand ?? defaultRunCommand;
2464
+ const hostedJson = JSON.stringify({
2465
+ type: "http",
2466
+ url: input.hostedMcpUrl,
2467
+ headers: { Authorization: `Bearer ${input.apiKey}` }
2468
+ });
2469
+ const signerJson = JSON.stringify({
2470
+ type: "stdio",
2471
+ command: signerCommand?.command ?? "npx",
2472
+ args: signerCommand?.args ?? ["-y", signerPackageSpec(), "--credentials", input.signerPath],
2473
+ env: {}
2474
+ });
1770
2475
  try {
1771
- const input = await buildLocalMcpConsentInput(identityPath, signerPath);
1772
- const hash = computeConsentHash(input);
1773
- const stored = await readLocalMcpAckFile(localMcpAckPath(identityPath));
1774
- if (stored === hash) {
1775
- return { acknowledged: true, hash, reason: "ack_file_match" };
1776
- }
2476
+ const names = serverNamesFor(input.serverName);
2477
+ await runCommand("claude", ["mcp", "remove", names.hosted]).catch(() => void 0);
2478
+ await runCommand("claude", ["mcp", "remove", names.signer]).catch(() => void 0);
2479
+ await runCommand("claude", ["mcp", "add-json", names.hosted, hostedJson, "--scope", "user"]);
2480
+ await runCommand("claude", ["mcp", "add-json", names.signer, signerJson, "--scope", "user"]);
2481
+ const verified = await runCommand("claude", ["mcp", "get", names.hosted]).then(() => true).catch(() => false);
1777
2482
  return {
1778
- acknowledged: false,
1779
- hash,
1780
- reason: stored ? "ack_file_mismatch" : "ack_file_missing"
2483
+ hostedConfigured: true,
2484
+ signerConfigured: true,
2485
+ localMcpConfigured: false,
2486
+ runtimeMcpMode: "hosted_plus_signer",
2487
+ target: "Claude Code MCP config",
2488
+ changed: true,
2489
+ restartRequired: true,
2490
+ messages: [
2491
+ "Updated hosted Haven MCP and local signer entries with Claude Code.",
2492
+ ...verified ? ["Verified Claude Code MCP entry."] : []
2493
+ ]
1781
2494
  };
1782
2495
  } catch (err) {
1783
2496
  return {
1784
- acknowledged: false,
1785
- error: err instanceof Error ? err.message : String(err)
2497
+ hostedConfigured: false,
2498
+ signerConfigured: false,
2499
+ localMcpConfigured: false,
2500
+ runtimeMcpMode: "hosted_plus_signer",
2501
+ target: "Claude Code MCP config",
2502
+ changed: false,
2503
+ restartRequired: true,
2504
+ messages: [
2505
+ `Could not update Claude Code MCP config: ${err instanceof Error ? err.message : String(err)}`,
2506
+ "Install Claude Code or rerun the Haven setup command inside a Claude Code terminal."
2507
+ ],
2508
+ errorCode: "claude_code_config_failed"
1786
2509
  };
1787
2510
  }
1788
2511
  }
1789
- function localMcpAckPath(identityPath) {
1790
- return resolve(`${identityPath}.ack.json`);
2512
+ async function defaultRunCommand(command, args) {
2513
+ await execFileAsync3(command, args, { timeout: 1e4 });
1791
2514
  }
1792
- async function buildLocalMcpConsentInput(identityPath, signerPath) {
1793
- const credentials = await loadCredentials({ identityPath, signerPath });
1794
- const unavailableDuringSetup = {
1795
- getAllowances: async () => {
1796
- throw new Error("Haven approval is not complete yet.");
2515
+ function buildProbeResult(mode, hostedConfigured, hostedStatus, signerReady, localMcpReady, localMcpProbeStatus) {
2516
+ if (mode === "local_stdio") {
2517
+ if (localMcpReady) return "local_stdio_mcp_ready";
2518
+ return localMcpProbeStatus ? `local_stdio_mcp_${localMcpProbeStatus}` : "local_stdio_mcp_unavailable";
2519
+ }
2520
+ const hostedPart = hostedConfigured ? `hosted_${hostedStatus}` : "hosted_not_configured";
2521
+ const signerPart = signerReady ? "local_signer_ready" : "local_signer_unavailable";
2522
+ return `${hostedPart}_${signerPart}`.slice(0, 120);
2523
+ }
2524
+ async function resolveLocalMcpConsent(input, messages) {
2525
+ if (input.ackLocalTools || input.ackSigner) {
2526
+ const status = await acknowledgeLocalMcpConsent(input.identityPath, input.signerPath, (message) => messages.push(message));
2527
+ if (status.acknowledged) {
2528
+ messages.push("Prepared the local Haven tools acknowledgement.");
2529
+ } else {
2530
+ messages.push("Local Haven tools acknowledgement still needs attention.");
1797
2531
  }
1798
- };
1799
- return consentInputFromClient(
1800
- unavailableDuringSetup,
1801
- {
1802
- apiKey: credentials.apiKey,
1803
- apiUrl: credentials.apiUrl,
1804
- agentId: credentials.agentId,
1805
- safeAddress: credentials.safeAddress,
1806
- delegateAddress: credentials.delegateAddress,
1807
- chainId: credentials.chainId,
1808
- allowanceSummary: credentials.allowanceSummary
1809
- },
1810
- registeredToolNames()
1811
- );
2532
+ return status;
2533
+ }
2534
+ return getLocalMcpConsentStatus(input.identityPath, input.signerPath);
1812
2535
  }
1813
- async function readLocalMcpAckFile(path) {
1814
- try {
1815
- const parsed = JSON.parse(await readFile(path, "utf8"));
1816
- return typeof parsed.ack === "string" ? parsed.ack : null;
1817
- } catch {
1818
- return null;
2536
+ async function resolveSignerConsent(input, messages) {
2537
+ if (input.ackSigner || input.ackLocalTools) {
2538
+ const status = await acknowledgeLocalSignerConsent(input.signerPath, (message) => messages.push(message));
2539
+ if (status.acknowledged) {
2540
+ messages.push("Prepared the local Haven signer acknowledgement.");
2541
+ } else {
2542
+ messages.push("Local Haven signer acknowledgement still needs attention.");
2543
+ }
2544
+ return status;
1819
2545
  }
2546
+ return getLocalSignerConsentStatus(input.signerPath);
1820
2547
  }
1821
- function writeLogChunk(log, chunk) {
1822
- const message = String(chunk).trimEnd();
1823
- if (message) log(message);
2548
+ function signerConsentErrorCode(signerCredentialReady, signerConsent) {
2549
+ if (!signerCredentialReady) return "local_signer_credential_unavailable";
2550
+ if (!signerConsent?.acknowledged) return "local_signer_ack_required";
2551
+ return void 0;
1824
2552
  }
1825
-
1826
- // src/runtime-install.ts
1827
- init_probes();
1828
-
1829
- // src/local-mcp-runtime.ts
1830
- init_signer_runtime();
1831
- init_runtime_manifest();
1832
- var execFileAsync2 = promisify(execFile);
1833
- var UnsupportedNodeVersionError = class extends Error {
1834
- code = "local_mcp_unsupported_node_version";
1835
- nodeVersion;
1836
- minimumNodeVersion;
1837
- constructor(nodeVersion, minimumNodeVersion, subject = "Haven setup") {
1838
- super(unsupportedNodeVersionMessage({ subject, nodeVersion, minimumNodeVersion }));
1839
- this.name = "UnsupportedNodeVersionError";
1840
- this.nodeVersion = nodeVersion;
1841
- this.minimumNodeVersion = minimumNodeVersion;
1842
- }
1843
- };
1844
- async function prepareLocalMcpRuntime(input, deps = {}) {
1845
- assertSupportedNodeVersion(input.nodeVersion);
1846
- const homeDir = input.homeDir ?? homedir();
1847
- const runtimeDirectory = resolve(homeDir, ".haven", "mcp-runtime", MCP_RUNTIME_MANIFEST.mcpVersion);
1848
- const npmCacheDirectory = resolve(homeDir, ".haven", "npm-cache");
1849
- const cliPath = join(runtimeDirectory, "node_modules", "@haven_ai", "mcp", "dist", "cli.js");
1850
- const messages = [];
1851
- await mkdir(runtimeDirectory, { recursive: true, mode: 448 });
1852
- await chmod(runtimeDirectory, 448).catch(() => void 0);
1853
- await mkdir(npmCacheDirectory, { recursive: true, mode: 448 });
1854
- await chmod(npmCacheDirectory, 448).catch(() => void 0);
1855
- if (await installedRuntimeMatches2(runtimeDirectory, cliPath)) {
1856
- messages.push(`Using existing local Haven MCP runtime ${mcpPackageSpec()}.`);
1857
- } else {
1858
- await installRuntimePackages2(runtimeDirectory, npmCacheDirectory, deps);
1859
- messages.push(`Installed local Haven MCP runtime ${mcpPackageSpec()}.`);
1860
- }
1861
- await assertFileExists2(cliPath, "local Haven MCP CLI");
1862
- const wrapperPath = join(input.credentialDirectory, "bin", "haven-mcp");
1863
- await writeWrapper2({
1864
- wrapperPath,
1865
- cliPath,
2553
+ function signerProbeErrorCode(probe) {
2554
+ if (!probe || probe.status === "ok") return void 0;
2555
+ return `local_signer_probe_${probe.status}`;
2556
+ }
2557
+ function hostedMcpErrorCode(hostedConfigured, hostedProbeStatus) {
2558
+ if (!hostedConfigured || hostedProbeStatus === "ok") return void 0;
2559
+ return `hosted_mcp_probe_${hostedProbeStatus}`;
2560
+ }
2561
+ function localMcpErrorCode(signerCredentialReady, localMcpConsent, localMcpProbeStatus) {
2562
+ if (!signerCredentialReady) return "local_signer_credential_unavailable";
2563
+ if (!localMcpConsent?.acknowledged) return "local_mcp_ack_required";
2564
+ if (localMcpProbeStatus && localMcpProbeStatus !== "ok") return `local_mcp_probe_${localMcpProbeStatus}`;
2565
+ return void 0;
2566
+ }
2567
+ function nextAction(runtime, restartMode, errorCode) {
2568
+ if (errorCode) return "return_to_haven_for_wallet_approval_then_finish_runtime_setup";
2569
+ if (restartMode === "hot-reload") return "return_to_haven_for_wallet_approval";
2570
+ if (runtime === "codex-cli" || runtime === "codex-desktop") return "return_to_haven_for_wallet_approval_then_restart_codex";
2571
+ if (runtime === "claude-code") return "return_to_haven_for_wallet_approval_then_restart_claude_code";
2572
+ if (restartMode === "restart-app") return "return_to_haven_for_wallet_approval_then_restart_app";
2573
+ if (restartMode === "restart-session") return "return_to_haven_for_wallet_approval_then_restart_agent_session";
2574
+ return "return_to_haven_for_wallet_approval_then_configure_runtime";
2575
+ }
2576
+ function supportsLocalMcp(runtime) {
2577
+ return runtime === "codex-cli" || runtime === "codex-desktop" || runtime === "claude-code";
2578
+ }
2579
+ async function prepareRuntimeForLocalMcp(input, deps) {
2580
+ const prepare = deps.prepareLocalMcpRuntime ?? ((runtimeInput) => prepareLocalMcpRuntime(runtimeInput, { runCommand: deps.runCommand, onProgress: deps.onProgress }));
2581
+ return prepare({
2582
+ credentialDirectory: input.credentialDirectory,
1866
2583
  identityPath: input.identityPath,
1867
- signerPath: input.signerPath
1868
- });
1869
- await writeRuntimeSidecar2({
1870
- path: join(input.credentialDirectory, "mcp-runtime.json"),
1871
- wrapperPath,
1872
- runtimeDirectory,
1873
- npmCacheDirectory,
1874
- cliPath
2584
+ signerPath: input.signerPath,
2585
+ homeDir: deps.homeDir,
2586
+ serverName: input.serverName
1875
2587
  });
1876
- messages.push(`Prepared stable local Haven MCP wrapper: ${wrapperPath}`);
1877
- return {
1878
- command: wrapperPath,
1879
- args: [],
1880
- wrapperPath,
1881
- runtimeDirectory,
1882
- npmCacheDirectory,
1883
- cliPath,
1884
- messages
1885
- };
1886
2588
  }
1887
- function assertSupportedNodeVersion(nodeVersion = process.versions.node, minimumNodeVersion = MCP_RUNTIME_MANIFEST.minimumNodeVersion, subject = "Haven setup") {
1888
- if (!isSupportedNodeVersion(nodeVersion, minimumNodeVersion)) {
1889
- throw new UnsupportedNodeVersionError(nodeVersion, minimumNodeVersion, subject);
1890
- }
2589
+ async function prepareSignerForRuntime(input, deps) {
2590
+ const prepare = deps.prepareSignerRuntime ?? ((runtimeInput) => (
2591
+ // onProgress threaded through on purpose (#1586 review): without it the
2592
+ // install heartbeat was dead code in production and the console still
2593
+ // went silent for the whole cold install — the exact symptom the issue
2594
+ // set out to remove, at a longer timeout.
2595
+ prepareSignerRuntime(runtimeInput, { runCommand: deps.runCommand, onProgress: deps.onProgress })
2596
+ ));
2597
+ return prepare({
2598
+ credentialDirectory: input.credentialDirectory,
2599
+ signerPath: input.signerPath,
2600
+ homeDir: deps.homeDir,
2601
+ serverName: input.serverName
2602
+ });
1891
2603
  }
1892
- async function installRuntimePackages2(runtimeDirectory, npmCacheDirectory, deps) {
1893
- const { runCommand, onProgress } = deps;
1894
- const baseArgs = [
1895
- "install",
1896
- "--prefix",
1897
- runtimeDirectory,
1898
- "--no-audit",
1899
- "--no-fund",
1900
- "--omit=dev",
1901
- "--prefer-offline",
1902
- mcpPackageSpec(),
1903
- sdkPackageSpec()
1904
- ];
1905
- const run = async (args) => {
1906
- const startedAt = Date.now();
1907
- const heartbeat = setInterval(() => {
1908
- const seconds = Math.round((Date.now() - startedAt) / 1e3);
1909
- onProgress?.(`Still installing the local Haven MCP runtime\u2026 (${seconds}s \u2014 a cold cache can take several minutes)`);
1910
- }, SIGNER_INSTALL_HEARTBEAT_MS);
1911
- heartbeat.unref?.();
1912
- try {
1913
- if (runCommand) await runCommand("npm", args);
1914
- else await execFileAsync2("npm", args, { timeout: SIGNER_INSTALL_TIMEOUT_MS, maxBuffer: 1024 * 1024 });
1915
- } finally {
1916
- clearInterval(heartbeat);
1917
- }
1918
- };
2604
+ async function runLocalMcpProbe(runtimeInstall, deps) {
2605
+ const probe = deps.probeLocalMcpTools ?? probeLocalMcpTools;
1919
2606
  try {
1920
- await run(baseArgs);
2607
+ return await probe(runtimeInstall.command, runtimeInstall.args, MCP_RUNTIME_MANIFEST.requiredTools);
1921
2608
  } catch {
1922
- try {
1923
- await run([...baseArgs, "--cache", npmCacheDirectory]);
1924
- } catch (err) {
1925
- throw new Error(`Could not install local Haven MCP runtime ${mcpPackageSpec()}: ${err instanceof Error ? err.message : String(err)}`);
1926
- }
2609
+ return { status: "process_error" };
1927
2610
  }
1928
2611
  }
1929
- async function installedRuntimeMatches2(runtimeDirectory, cliPath) {
1930
- try {
1931
- await assertFileExists2(cliPath, "local Haven MCP CLI");
1932
- const [mcpPackage, sdkPackage] = await Promise.all([
1933
- readPackageJson2(join(runtimeDirectory, "node_modules", "@haven_ai", "mcp", "package.json")),
1934
- readPackageJson2(join(runtimeDirectory, "node_modules", "@haven_ai", "sdk", "package.json"))
1935
- ]);
1936
- return mcpPackage.version === MCP_RUNTIME_MANIFEST.mcpVersion && sdkPackage.version === MCP_RUNTIME_MANIFEST.sdkVersion;
1937
- } catch {
1938
- return false;
2612
+ function localRuntimePrepareErrorCode(err) {
2613
+ if (err && typeof err === "object" && "code" in err && err.code === "local_mcp_unsupported_node_version") {
2614
+ return "local_mcp_unsupported_node_version";
1939
2615
  }
2616
+ return "local_mcp_runtime_install_failed";
1940
2617
  }
1941
- async function readPackageJson2(path) {
1942
- return JSON.parse(await readFile(path, "utf8"));
1943
- }
1944
- async function writeWrapper2(input) {
1945
- await mkdir(dirname(input.wrapperPath), { recursive: true, mode: 448 });
1946
- await chmod(dirname(input.wrapperPath), 448).catch(() => void 0);
1947
- const source = [
1948
- "#!/usr/bin/env node",
1949
- "import { spawn } from 'node:child_process'",
2618
+ var execFileAsync3;
2619
+ var init_runtime_install = __esm({
2620
+ "src/runtime-install.ts"() {
2621
+ init_config_writers();
2622
+ init_server_names();
2623
+ init_local_mcp_consent();
2624
+ init_probes();
2625
+ init_local_mcp_runtime();
2626
+ init_signer_runtime();
2627
+ init_runtime_manifest();
2628
+ init_skill_install();
2629
+ init_runtime_registry();
2630
+ init_signer_consent();
2631
+ execFileAsync3 = promisify(execFile);
2632
+ }
2633
+ });
2634
+
2635
+ // src/tombstone.ts
2636
+ var tombstone_exports = {};
2637
+ __export(tombstone_exports, {
2638
+ TOMBSTONE_FILENAME: () => TOMBSTONE_FILENAME,
2639
+ TOMBSTONE_MARKER: () => TOMBSTONE_MARKER,
2640
+ readAgentTombstone: () => readAgentTombstone,
2641
+ writeAgentTombstone: () => writeAgentTombstone
2642
+ });
2643
+ function tombstoneScript(info) {
2644
+ const lines = [
2645
+ `${TOMBSTONE_MARKER}: this Haven agent was retired.`,
1950
2646
  "",
1951
- `const cliPath = ${JSON.stringify(input.cliPath)}`,
1952
- `const identityPath = ${JSON.stringify(input.identityPath)}`,
1953
- `const signerPath = ${JSON.stringify(input.signerPath)}`,
2647
+ ` agent: ${info.agent_id}`,
2648
+ ` retired at: ${info.retired_at}`,
2649
+ ` reason: ${info.reason}`,
2650
+ ...info.replaced_by ? [` replaced by: ${info.replaced_by}`] : [],
1954
2651
  "",
1955
- "const child = spawn(process.execPath, [cliPath, '--identity', identityPath, '--signer', signerPath, ...process.argv.slice(2)], {",
1956
- " stdio: 'inherit',",
1957
- "})",
2652
+ "This process is running with a wiring snapshot that predates the",
2653
+ "retirement \u2014 it loaded its MCP config at startup and has kept it since.",
2654
+ "Restart THIS host to pick up the current wiring. If several long-lived",
2655
+ "hosts are running (a gateway, a TUI worker, an editor), restart EVERY",
2656
+ "one of them: each holds the snapshot from its own start time, so after",
2657
+ "a chain of recreations each can be parked on a DIFFERENT old agent.",
1958
2658
  "",
1959
- "child.on('exit', (code, signal) => {",
1960
- " if (signal) process.kill(process.pid, signal)",
1961
- " else process.exit(code ?? 1)",
1962
- "})",
2659
+ "Then verify with: npx @haven_ai/connect@alpha --doctor --runtime <runtime>"
2660
+ ];
2661
+ return [
2662
+ "#!/usr/bin/env node",
2663
+ `// ${TOMBSTONE_MARKER} \u2014 written by @haven_ai/connect (#1681). Safe to delete`,
2664
+ "// once every long-lived MCP host on this machine has been restarted.",
2665
+ `process.stderr.write(${JSON.stringify(lines.join("\n") + "\n")})`,
2666
+ "process.exit(1)",
1963
2667
  ""
1964
2668
  ].join("\n");
1965
- await writeFile(input.wrapperPath, source, { mode: 448 });
1966
- await chmod(input.wrapperPath, 448).catch(() => void 0);
1967
2669
  }
1968
- async function writeRuntimeSidecar2(input) {
1969
- const value = {
1970
- mcp_package: MCP_RUNTIME_MANIFEST.mcpPackage,
1971
- mcp_version: MCP_RUNTIME_MANIFEST.mcpVersion,
1972
- sdk_package: MCP_RUNTIME_MANIFEST.sdkPackage,
1973
- sdk_version: MCP_RUNTIME_MANIFEST.sdkVersion,
1974
- minimum_node_version: MCP_RUNTIME_MANIFEST.minimumNodeVersion,
1975
- wrapper_path: input.wrapperPath,
1976
- runtime_directory: input.runtimeDirectory,
1977
- npm_cache_directory: input.npmCacheDirectory,
1978
- cli_path: input.cliPath
2670
+ async function writeAgentTombstone(input) {
2671
+ const dirStat = await stat(input.directory).catch(() => null);
2672
+ if (!dirStat?.isDirectory()) {
2673
+ throw new Error(`Not a directory: ${input.directory} \u2014 nothing to tombstone.`);
2674
+ }
2675
+ const info = {
2676
+ // reason / replaced_by are persisted to disk and re-emitted to the host's
2677
+ // MCP stderr log on EVERY stale probe, potentially for months — redact
2678
+ // like every other output path, at the write layer so any future caller
2679
+ // inherits it. (#1681 review, finding 1)
2680
+ agent_id: input.agentId,
2681
+ retired_at: input.retiredAt ?? (/* @__PURE__ */ new Date()).toISOString(),
2682
+ reason: redactSecrets(input.reason),
2683
+ ...input.replacedBy ? { replaced_by: redactSecrets(input.replacedBy) } : {}
1979
2684
  };
1980
- await writeFile(input.path, `${JSON.stringify(value, null, 2)}
1981
- `, { mode: 384 });
1982
- await chmod(input.path, 384).catch(() => void 0);
1983
- }
1984
- async function assertFileExists2(path, label) {
2685
+ const binDir = join(input.directory, "bin");
2686
+ await mkdir(binDir, { recursive: true });
2687
+ const wrapperPath = join(binDir, "haven-signer.mjs");
2688
+ await writeFile(wrapperPath, tombstoneScript(info), "utf8");
2689
+ await chmod(wrapperPath, 493);
2690
+ await writeFile(join(input.directory, TOMBSTONE_FILENAME), JSON.stringify(info, null, 2) + "\n", "utf8");
2691
+ return info;
2692
+ }
2693
+ async function readAgentTombstone(directory) {
1985
2694
  try {
1986
- await access(path);
2695
+ const parsed = JSON.parse(await readFile(join(directory, TOMBSTONE_FILENAME), "utf8"));
2696
+ if (typeof parsed?.agent_id !== "string") return null;
2697
+ return parsed;
1987
2698
  } catch {
1988
- throw new Error(`Missing ${label}: ${path}`);
2699
+ return null;
1989
2700
  }
1990
2701
  }
2702
+ var TOMBSTONE_FILENAME, TOMBSTONE_MARKER;
2703
+ var init_tombstone = __esm({
2704
+ "src/tombstone.ts"() {
2705
+ init_redact();
2706
+ TOMBSTONE_FILENAME = "TOMBSTONE.json";
2707
+ TOMBSTONE_MARKER = "HAVEN-TOMBSTONE";
2708
+ }
2709
+ });
1991
2710
 
1992
- // src/runtime-install.ts
1993
- init_signer_runtime();
1994
- init_runtime_manifest();
1995
- var CODEX_AGENTS_BEGIN_MARKER = "<!-- BEGIN haven-pay (managed by @haven_ai/connect; edits inside this section are overwritten on re-setup) -->";
1996
- var CODEX_AGENTS_END_MARKER = "<!-- END haven-pay -->";
1997
- async function installSkillForRuntime(runtime, deps = {}) {
1998
- switch (runtime) {
1999
- case "claude-code":
2000
- return installSkillFile(
2001
- resolve(deps.homeDir ?? homedir(), ".claude", "skills", SKILL_FOLDER_NAME),
2002
- "~/.claude/skills/haven-pay"
2003
- );
2004
- case "hermes":
2005
- return installSkillFile(
2006
- join(hermesHome(deps), "skills", SKILL_FOLDER_NAME),
2007
- "the Hermes skills folder"
2711
+ // src/rekey.ts
2712
+ var rekey_exports = {};
2713
+ __export(rekey_exports, {
2714
+ finishRekey: () => finishRekey,
2715
+ startRekey: () => startRekey
2716
+ });
2717
+ async function startRekey(options, deps = {}) {
2718
+ const now = deps.now ?? (() => Date.now());
2719
+ const stored = await readStoredCredentials(
2720
+ options.serverName,
2721
+ options.agentId,
2722
+ options.credentialsDir
2723
+ );
2724
+ const api = (deps.createApi ?? ((url) => createConnectApiClient(url)))(stored.apiUrl);
2725
+ const identity = await probeIdentity(api, stored.apiKey, "current");
2726
+ assertRekeyable(identity, stored);
2727
+ const key = (deps.generateKey ?? generateDelegateKey)();
2728
+ const startedAt = new Date(now()).toISOString();
2729
+ const expiresAt = new Date(now() + REKEY_PENDING_TTL_MS).toISOString();
2730
+ await writeRekeyPending(stored.directory, {
2731
+ agent_id: stored.agentId,
2732
+ new_delegate_address: key.address,
2733
+ new_delegate_key: key.privateKey,
2734
+ started_at: startedAt,
2735
+ expires_at: expiresAt
2736
+ });
2737
+ const finishCommand = [
2738
+ "npx @haven_ai/connect@alpha --rekey-finish",
2739
+ options.serverName ? `--name ${options.serverName}` : void 0,
2740
+ "--api-key <the key the dashboard showed you>",
2741
+ options.runtime ? `--runtime ${options.runtime}` : "--runtime <your runtime>"
2742
+ ].filter(Boolean).join(" ");
2743
+ return {
2744
+ started: true,
2745
+ agentId: stored.agentId,
2746
+ directory: stored.directory,
2747
+ newDelegateAddress: key.address,
2748
+ expiresAt,
2749
+ messages: [
2750
+ `New signing key generated on this machine for agent ${identity.name || stored.agentId}.`,
2751
+ "",
2752
+ ` New signing address: ${key.address}`,
2753
+ "",
2754
+ "The private half stays here \u2014 Haven never receives it, and there is no way to move it",
2755
+ "between machines. That is what keeps the account non-custodial.",
2756
+ "",
2757
+ 'Next, on the Haven agent page: choose "Replace signing key" and paste that address.',
2758
+ "When it finishes it shows a new API key ONCE. Come back here and run:",
2759
+ "",
2760
+ ` ${finishCommand}`,
2761
+ "",
2762
+ `Nothing has changed yet \u2014 the agent keeps working on its old key until you finish.`,
2763
+ `This pending re-key expires ${expiresAt}.`
2764
+ ]
2765
+ };
2766
+ }
2767
+ async function finishRekey(options, deps = {}) {
2768
+ const now = deps.now ?? (() => Date.now());
2769
+ if (!options.newApiKey) {
2770
+ throw new Error("--rekey-finish needs --api-key <key> \u2014 the one the Haven agent page showed once.");
2771
+ }
2772
+ const stored = await readStoredCredentials(
2773
+ options.serverName,
2774
+ options.agentId,
2775
+ options.credentialsDir
2776
+ );
2777
+ const pending = await readRekeyPending(stored.directory, now());
2778
+ if (pending.agent_id !== stored.agentId) {
2779
+ throw new Error(
2780
+ `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.`
2781
+ );
2782
+ }
2783
+ const api = (deps.createApi ?? ((url) => createConnectApiClient(url)))(stored.apiUrl);
2784
+ const identity = await probeIdentity(api, options.newApiKey, "new");
2785
+ if (identity.id !== stored.agentId) {
2786
+ throw new Error(
2787
+ `That API key belongs to agent ${identity.id}, not ${stored.agentId}. Nothing was changed.`
2788
+ );
2789
+ }
2790
+ const onChain = (identity.delegate_address ?? "").toLowerCase();
2791
+ const expected = pending.new_delegate_address.toLowerCase();
2792
+ if (onChain !== expected) {
2793
+ throw new Error(
2794
+ `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.`
2795
+ );
2796
+ }
2797
+ await rewriteCredentialFiles({
2798
+ baseDir: options.credentialsDir,
2799
+ agentId: stored.agentId,
2800
+ serverName: options.serverName,
2801
+ apiKey: options.newApiKey,
2802
+ delegateKey: pending.new_delegate_key,
2803
+ delegateAddress: pending.new_delegate_address,
2804
+ safeAddress: stored.safeAddress ?? identity.safe_address ?? void 0,
2805
+ chainId: stored.chainId ?? identity.chain_id ?? void 0,
2806
+ network: stored.network,
2807
+ agentBudget: stored.agentBudget,
2808
+ apiUrl: stored.apiUrl,
2809
+ hostedMcpUrl: stored.hostedMcpUrl,
2810
+ x402BindingSigner: stored.x402BindingSigner,
2811
+ warn: deps.log
2812
+ });
2813
+ await clearRekeyPending(stored.directory);
2814
+ const names = serverNamesFor(options.serverName);
2815
+ const messages = [
2816
+ `Agent ${identity.name || stored.agentId} is now on its new signing key.`,
2817
+ ` Signing address: ${pending.new_delegate_address}`,
2818
+ ` Credentials: ${stored.directory} (rewritten in place)`,
2819
+ ` MCP servers: ${names.hosted} / ${names.signer} (unchanged names)`
2820
+ ];
2821
+ let configRewritten = false;
2822
+ if (options.runtime) {
2823
+ const prepared = await (deps.prepareSigner ?? prepareSignerRuntime)(
2824
+ {
2825
+ credentialDirectory: stored.directory,
2826
+ signerPath: `${stored.directory}/signer.json`,
2827
+ homeDir: options.homeDir
2828
+ },
2829
+ { runCommand: deps.runCommand }
2830
+ );
2831
+ const result = await (deps.writeConfig ?? writeHostedRuntimeConfig)(
2832
+ { runCommand: deps.runCommand, homeDir: options.homeDir },
2833
+ {
2834
+ runtime: options.runtime,
2835
+ hostedMcpUrl: stored.hostedMcpUrl,
2836
+ apiKey: options.newApiKey,
2837
+ identityPath: `${stored.directory}/identity.json`,
2838
+ signerPath: `${stored.directory}/signer.json`,
2839
+ credentialDirectory: stored.directory,
2840
+ serverName: options.serverName
2841
+ },
2842
+ { command: prepared.command, args: prepared.args }
2843
+ );
2844
+ configRewritten = result.hostedConfigured;
2845
+ messages.push(` Config: ${result.target}`);
2846
+ messages.push(...result.messages.map((line) => ` ${line}`));
2847
+ if (!configRewritten) {
2848
+ messages.push(
2849
+ "",
2850
+ "WARNING: the MCP config was NOT updated, so it still carries the OLD API key and every",
2851
+ `wired host will fail with 401. Fix the cause above and re-run with --runtime ${options.runtime},`,
2852
+ "or update the config by hand. The credential files on disk are already on the new key."
2008
2853
  );
2009
- case "codex-cli":
2010
- case "codex-desktop":
2011
- return installCodexAgentsSection(deps);
2012
- default:
2013
- return void 0;
2854
+ }
2855
+ } else {
2856
+ messages.push(
2857
+ "",
2858
+ "NOTE: no --runtime was given, so the MCP config still carries the OLD API key and every",
2859
+ "wired host will fail with 401. Re-run with --runtime <name> to rewrite it."
2860
+ );
2014
2861
  }
2862
+ return {
2863
+ finished: true,
2864
+ agentId: stored.agentId,
2865
+ directory: stored.directory,
2866
+ newDelegateAddress: pending.new_delegate_address,
2867
+ serverNames: { hosted: names.hosted, signer: names.signer },
2868
+ configRewritten,
2869
+ messages
2870
+ };
2015
2871
  }
2016
- async function installSkillFile(skillDir, label) {
2872
+ async function probeIdentity(api, apiKey, which) {
2017
2873
  try {
2018
- await mkdir(skillDir, { recursive: true });
2019
- const target = join(skillDir, "SKILL.md");
2020
- await writeFile(target, HAVEN_SKILL_MD, "utf8");
2021
- return {
2022
- installed: true,
2023
- target,
2024
- messages: [`Installed the generic Haven payment skill (${label}). It contains no secrets.`]
2874
+ return await api.getAgentIdentity(apiKey);
2875
+ } catch (err) {
2876
+ const status = err?.status;
2877
+ if (status === 401 || status === 403) {
2878
+ throw new Error(
2879
+ 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."
2880
+ );
2881
+ }
2882
+ throw new Error(
2883
+ `Could not reach Haven to check this agent (${redactSecrets(
2884
+ err instanceof Error ? err.message : String(err)
2885
+ )}). Nothing was changed.`
2886
+ );
2887
+ }
2888
+ }
2889
+ function assertRekeyable(identity, stored) {
2890
+ if (identity.id !== stored.agentId) {
2891
+ throw new Error(
2892
+ `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.`
2893
+ );
2894
+ }
2895
+ if (identity.execution_rail === "legacy") {
2896
+ throw new Error(
2897
+ `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.`
2898
+ );
2899
+ }
2900
+ if (identity.status === "revoked") {
2901
+ throw new Error(
2902
+ `Agent ${identity.name || identity.id} is revoked. Re-keying would hand a revoked agent fresh credentials \u2014 create a new agent instead.`
2903
+ );
2904
+ }
2905
+ }
2906
+ var init_rekey = __esm({
2907
+ "src/rekey.ts"() {
2908
+ init_api();
2909
+ init_runtime_install();
2910
+ init_signer_runtime();
2911
+ init_key();
2912
+ init_redact();
2913
+ init_server_names();
2914
+ init_storage();
2915
+ }
2916
+ });
2917
+
2918
+ // src/rekey-restart.ts
2919
+ var rekey_restart_exports = {};
2920
+ __export(rekey_restart_exports, {
2921
+ restartGuidance: () => restartGuidance
2922
+ });
2923
+ function restartGuidance(runtime) {
2924
+ const profile = runtime ? BY_RUNTIME[runtime] : void 0;
2925
+ const lines = ["The new key is only live in a process that started after now.", ""];
2926
+ if (profile) {
2927
+ lines.push(profile.how);
2928
+ for (const command of profile.commands) lines.push(` ${command}`);
2929
+ if (profile.commands.length > 0) lines.push("");
2930
+ } else {
2931
+ lines.push(
2932
+ 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."
2933
+ );
2934
+ lines.push("");
2935
+ }
2936
+ lines.push(SWEEP);
2937
+ return { commands: profile?.commands ?? [], lines };
2938
+ }
2939
+ var SWEEP, BY_RUNTIME;
2940
+ var init_rekey_restart = __esm({
2941
+ "src/rekey-restart.ts"() {
2942
+ 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.";
2943
+ BY_RUNTIME = {
2944
+ "claude-code": {
2945
+ commands: ["claude --continue"],
2946
+ how: "Exit this Claude Code session and start a new one:"
2947
+ },
2948
+ "codex-cli": {
2949
+ commands: ["codex resume --last"],
2950
+ how: "Start a fresh Codex CLI session:"
2951
+ },
2952
+ "codex-desktop": {
2953
+ commands: [],
2954
+ how: "Quit Codex Desktop completely (not just the window) and reopen it."
2955
+ },
2956
+ "claude-desktop": {
2957
+ commands: [],
2958
+ how: "Quit Claude Desktop completely (not just the window) and reopen it."
2959
+ },
2960
+ hermes: {
2961
+ commands: ["systemctl --user restart hermes-gateway", "/restart"],
2962
+ 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:"
2963
+ },
2964
+ cursor: {
2965
+ commands: [],
2966
+ 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").'
2967
+ },
2968
+ vscode: {
2969
+ commands: [],
2970
+ 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").'
2971
+ },
2972
+ "vscode-insiders": {
2973
+ commands: [],
2974
+ 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").'
2975
+ }
2025
2976
  };
2026
- } catch (err) {
2977
+ }
2978
+ });
2979
+
2980
+ // src/doctor.ts
2981
+ var doctor_exports = {};
2982
+ __export(doctor_exports, {
2983
+ runDoctor: () => runDoctor,
2984
+ runRepair: () => runRepair
2985
+ });
2986
+ async function discoverCredentialDirectory(homeDir, explicit) {
2987
+ const root = explicit ? dirname(explicit) : join(homeDir, ".haven", "agents");
2988
+ let entries = [];
2989
+ try {
2990
+ entries = await readdir(root);
2991
+ } catch {
2992
+ return explicit ? { directory: explicit, others: [], parkedOnly: /* @__PURE__ */ new Set() } : { others: [], parkedOnly: /* @__PURE__ */ new Set() };
2993
+ }
2994
+ const candidates = [];
2995
+ const tombstonedOnly = [];
2996
+ const parkedOnly = [];
2997
+ for (const entry of entries) {
2998
+ const directory = join(root, entry);
2999
+ try {
3000
+ const s = await stat(join(directory, "identity.json"));
3001
+ candidates.push({ directory, mtimeMs: s.mtimeMs });
3002
+ } catch {
3003
+ try {
3004
+ await stat(join(directory, TOMBSTONE_FILENAME));
3005
+ tombstonedOnly.push(directory);
3006
+ } catch {
3007
+ try {
3008
+ await stat(join(directory, REKEY_PENDING_FILENAME));
3009
+ parkedOnly.push(directory);
3010
+ } catch {
3011
+ }
3012
+ }
3013
+ }
3014
+ }
3015
+ const parkedOnlySet = new Set(parkedOnly);
3016
+ candidates.sort((a, b) => b.mtimeMs - a.mtimeMs);
3017
+ if (explicit) {
2027
3018
  return {
2028
- installed: false,
2029
- messages: [
2030
- `Could not install the Haven payment skill: ${err instanceof Error ? err.message : String(err)}. Download it from the Haven dashboard instead.`
2031
- ]
3019
+ directory: explicit,
3020
+ others: [...candidates.map((c) => c.directory), ...tombstonedOnly, ...parkedOnly].filter((d) => d !== explicit),
3021
+ parkedOnly: parkedOnlySet
2032
3022
  };
2033
3023
  }
3024
+ if (candidates.length === 0 && tombstonedOnly.length === 0 && parkedOnly.length === 0) {
3025
+ return { others: [], parkedOnly: parkedOnlySet };
3026
+ }
3027
+ return {
3028
+ directory: candidates[0]?.directory,
3029
+ others: [...candidates.slice(1).map((c) => c.directory), ...tombstonedOnly, ...parkedOnly],
3030
+ parkedOnly: parkedOnlySet
3031
+ };
2034
3032
  }
2035
- async function installCodexAgentsSection(deps) {
2036
- try {
2037
- const codexDir = resolve(deps.homeDir ?? homedir(), ".codex");
2038
- const target = join(codexDir, "AGENTS.md");
2039
- await mkdir(codexDir, { recursive: true });
2040
- const existing = await readFile(target, "utf8").catch(() => null);
2041
- const next = upsertManagedSection(existing, codexManagedSection());
2042
- if (next !== existing) {
2043
- await writeFile(target, next, "utf8");
3033
+ function agentIsWired(configText, names, slug, identity, sidecar, isPrimary, bareOwnerExists) {
3034
+ if (configText === null) return isPrimary;
3035
+ if (slug) {
3036
+ for (const name of [names.hosted, names.codexHosted, names.signer, names.codexSigner]) {
3037
+ if (new RegExp(`(^|[."'\\s\\[])${name}(["'\\]:\\s]|$)`, "m").test(configText)) return true;
2044
3038
  }
3039
+ return false;
3040
+ }
3041
+ if (sidecar?.wrapper_path && configText.includes(sidecar.wrapper_path)) return true;
3042
+ if (bareOwnerExists) return false;
3043
+ return isPrimary && Boolean(identity?.hosted_mcp_url && configText.includes(identity.hosted_mcp_url));
3044
+ }
3045
+ function rekeyPendingCheck(status, hostedDelegateAddress, runtime, slug) {
3046
+ const label = "Pending re-key";
3047
+ const nameFlag = slug ? ` --name ${slug}` : "";
3048
+ if (status.state === "unreadable") {
2045
3049
  return {
2046
- installed: true,
2047
- target,
2048
- messages: [
2049
- "Installed the generic Haven payment guidance as a managed section in ~/.codex/AGENTS.md (Codex reads it as global instructions). It contains no secrets; your own content in that file is untouched."
2050
- ]
3050
+ id: "rekey_pending",
3051
+ label,
3052
+ ok: false,
3053
+ 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.`,
3054
+ repair: `Delete ${status.path}, then start again: ${RERUN} --rekey${nameFlag}`
2051
3055
  };
2052
- } catch (err) {
3056
+ }
3057
+ const started = status.startedAt ?? "an unknown time";
3058
+ const address = status.newDelegateAddress ?? "unknown";
3059
+ const completedOnHaven = hostedDelegateAddress !== void 0 && status.newDelegateAddress !== void 0 && hostedDelegateAddress.toLowerCase() === status.newDelegateAddress.toLowerCase();
3060
+ if (completedOnHaven) {
2053
3061
  return {
2054
- installed: false,
2055
- messages: [
2056
- `Could not install the Haven payment guidance into ~/.codex/AGENTS.md: ${err instanceof Error ? err.message : String(err)}. Download the skill from the Haven dashboard instead.`
2057
- ]
3062
+ id: "rekey_pending",
3063
+ label,
3064
+ ok: false,
3065
+ 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." : ""),
3066
+ 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> --runtime ${runtime}`
2058
3067
  };
2059
3068
  }
2060
- }
2061
- function codexManagedSection() {
2062
- return `${CODEX_AGENTS_BEGIN_MARKER}
2063
-
2064
- ${HAVEN_SKILL_BODY_MD.trimEnd()}
2065
-
2066
- ${CODEX_AGENTS_END_MARKER}
2067
- `;
2068
- }
2069
- function upsertManagedSection(existing, section) {
2070
- if (existing === null || existing.trim() === "") return section;
2071
- const begins = markerLineIndexes(existing, CODEX_AGENTS_BEGIN_MARKER);
2072
- const ends = markerLineIndexes(existing, CODEX_AGENTS_END_MARKER);
2073
- if (begins.length === 1 && ends.length === 1 && ends[0] > begins[0]) {
2074
- const afterEnd = ends[0] + CODEX_AGENTS_END_MARKER.length;
2075
- const tail = existing.startsWith("\r\n", afterEnd) ? existing.slice(afterEnd + 2) : existing.startsWith("\n", afterEnd) ? existing.slice(afterEnd + 1) : existing.slice(afterEnd);
2076
- return existing.slice(0, begins[0]) + section + tail;
2077
- }
2078
- if (begins.length > 0 || ends.length > 0) {
2079
- throw new Error(
2080
- "found a damaged Haven marker section (orphaned or duplicated markers); remove the leftover marker lines and re-run setup"
2081
- );
3069
+ 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.";
3070
+ if (status.state === "expired") {
3071
+ return {
3072
+ id: "rekey_pending",
3073
+ label,
3074
+ ok: false,
3075
+ 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,
3076
+ 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.`
3077
+ };
2082
3078
  }
2083
- return `${existing.replace(/\n*$/, "\n\n")}${section}`;
3079
+ return {
3080
+ id: "rekey_pending",
3081
+ label,
3082
+ ok: true,
3083
+ 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
3084
+ };
2084
3085
  }
2085
- function markerLineIndexes(text, marker) {
2086
- const indexes = [];
2087
- for (let from = 0; ; ) {
2088
- const at = text.indexOf(marker, from);
2089
- if (at === -1) return indexes;
2090
- if (at === 0 || text[at - 1] === "\n") indexes.push(at);
2091
- from = at + marker.length;
3086
+ async function readIdentity(directory) {
3087
+ try {
3088
+ return JSON.parse(await readFile(join(directory, "identity.json"), "utf8"));
3089
+ } catch {
3090
+ return void 0;
2092
3091
  }
2093
3092
  }
2094
- function hermesHome(deps) {
2095
- const env = deps.env ?? process.env;
2096
- return env.HERMES_HOME ?? join(deps.homeDir ?? homedir(), ".hermes");
2097
- }
2098
-
2099
- // src/runtime-install.ts
2100
- init_runtime_registry();
2101
- init_signer_consent();
2102
- var execFileAsync3 = promisify(execFile);
2103
- async function installRuntime(input, deps = {}) {
2104
- const runtime = normalizeRuntime(input.runtime, deps.env);
2105
- const profile = runtimeProfile(runtime, deps.env);
2106
- const progress = deps.onProgress ?? (() => void 0);
2107
- const localRuntime = input.localMcp === true && supportsLocalMcp(runtime);
2108
- const consentMessages = [];
2109
- const localMcpConsent = localRuntime ? await resolveLocalMcpConsent(input, consentMessages) : void 0;
2110
- const signerConsent = localRuntime ? void 0 : await resolveSignerConsent(input, consentMessages);
2111
- if (runtime === "other") {
2112
- const signerCredentialReady2 = await probeLocalSignerCredential(input.signerPath);
2113
- const signerReady = signerCredentialReady2 && signerConsent?.acknowledged;
2114
- return {
2115
- runtime,
2116
- runtimeMcpMode: "manual",
2117
- hostedMcpConfigured: false,
2118
- localSignerConfigured: false,
2119
- localMcpConfigured: false,
2120
- probeResult: signerReady ? "manual_runtime_setup_required_local_signer_ready" : "manual_runtime_setup_required_local_signer_unavailable",
2121
- restartRequired: true,
2122
- nextUserAction: "return_to_haven_for_wallet_approval_then_configure_runtime",
2123
- errorCode: "manual_runtime_setup_required",
2124
- configTarget: "manual runtime setup",
2125
- signerAcknowledged: signerConsent?.acknowledged,
2126
- localMcpAcknowledged: false,
2127
- messages: [
2128
- ...consentMessages,
2129
- "Custom runtime: Haven did not auto-configure it. Your credentials are on disk (chmod 600) \u2014 read them at runtime; never paste a key into the agent prompt, memory, or logs.",
2130
- ` identity (hosted MCP Bearer): ${input.identityPath}`,
2131
- ` signer (local signing key): ${input.signerPath}`,
2132
- "After wallet approval, wire the runtime to Haven by reference:",
2133
- ` Hosted MCP + local signer: point your MCP client at ${input.hostedMcpUrl} with the api_key from identity.json, then run npx -y ${signerPackageSpec()} --credentials ${input.signerPath}`,
2134
- ` Fully local MCP (no hosted dependency): npx -y ${mcpPackageSpec()} --identity ${input.identityPath} --signer ${input.signerPath}`
2135
- ]
2136
- };
3093
+ async function checksForAgent(entry, input, deps) {
3094
+ const { directory, identity, sidecar } = entry;
3095
+ const checks = [];
3096
+ let signerCapabilities;
3097
+ let signerFile;
3098
+ try {
3099
+ const parsed = JSON.parse(await readFile(join(directory, "signer.json"), "utf8"));
3100
+ signerFile = typeof parsed === "object" && parsed !== null ? parsed : void 0;
3101
+ } catch {
3102
+ signerFile = void 0;
2137
3103
  }
2138
- let localRuntimeInstall;
2139
- let localRuntimeError;
2140
- if (localRuntime) {
2141
- try {
2142
- localRuntimeInstall = await prepareRuntimeForLocalMcp(input, deps);
2143
- } catch (err) {
2144
- localRuntimeError = err;
3104
+ const credentialsOk = Boolean(identity?.api_key) && signerFile !== void 0;
3105
+ checks.push({
3106
+ id: "credentials",
3107
+ label: "Agent credentials",
3108
+ ok: credentialsOk,
3109
+ detail: credentialsOk ? `identity.json and signer.json parse (agent ${identity?.agent_id ?? "unknown"})` : "identity.json or signer.json is missing or unparseable.",
3110
+ ...credentialsOk ? {} : { repair: `Re-run the full setup with a fresh token: ${RERUN} --setup <token>.` }
3111
+ });
3112
+ if (!sidecar) {
3113
+ checks.push({
3114
+ id: "signer_runtime",
3115
+ label: "Signer runtime (preinstalled wrapper)",
3116
+ ok: false,
3117
+ detail: "No signer-runtime.json sidecar \u2014 the pinned signer runtime was never prepared (or a pre-#1586 npx config).",
3118
+ repair: `Run: ${RERUN} --doctor --repair --runtime ${input.runtime}`
3119
+ });
3120
+ } else {
3121
+ const matches = await installedRuntimeMatches(sidecar.runtime_directory, sidecar.cli_path);
3122
+ const versionOk = sidecar.signer_version === MCP_RUNTIME_MANIFEST.signerVersion;
3123
+ const ok = matches && versionOk;
3124
+ checks.push({
3125
+ id: "signer_runtime",
3126
+ label: "Signer runtime (preinstalled wrapper)",
3127
+ ok,
3128
+ detail: ok ? `Installed ${sidecar.signer_package}@${sidecar.signer_version} at ${sidecar.runtime_directory}` : matches ? `Installed version ${sidecar.signer_version} does not match the connector's pinned ${MCP_RUNTIME_MANIFEST.signerVersion}.` : `Runtime directory is stale or empty (${sidecar.runtime_directory}) \u2014 the CLI or package versions are missing.`,
3129
+ ...ok ? {} : { repair: `Run: ${RERUN} --doctor --repair --runtime ${input.runtime}` }
3130
+ });
3131
+ }
3132
+ const hostedUrl = identity?.hosted_mcp_url ?? (identity?.api_url ? `${identity.api_url}/mcp` : void 0);
3133
+ if (identity?.api_key && hostedUrl) {
3134
+ const probe = await (deps.probeHosted ?? probeHostedMcpTools)(identity.api_key, hostedUrl, deps.fetch);
3135
+ checks.push({
3136
+ id: "hosted_mcp",
3137
+ label: "Hosted Haven MCP",
3138
+ ok: probe.status === "ok",
3139
+ detail: probe.status === "ok" ? `Reachable and authorized (${hostedUrl}).` : `Probe failed: ${probe.status} (${hostedUrl}).`,
3140
+ ...probe.status === "ok" ? {} : {
3141
+ repair: probe.status === "unauthorized" ? `The stored API key was rejected \u2014 re-run the full setup with a fresh token: ${RERUN} --setup <token>.` : "Check network access to the hosted MCP URL, then re-run --doctor."
3142
+ }
3143
+ });
3144
+ } else {
3145
+ checks.push({
3146
+ id: "hosted_mcp",
3147
+ label: "Hosted Haven MCP",
3148
+ ok: false,
3149
+ detail: "No stored API key / hosted MCP URL to probe with.",
3150
+ repair: `Re-run the full setup: ${RERUN} --setup <token>.`
3151
+ });
3152
+ }
3153
+ const localDelegate = typeof signerFile?.delegate_address === "string" ? signerFile.delegate_address : void 0;
3154
+ let hostedDelegateAddress;
3155
+ if (identity?.api_key && identity.api_url) {
3156
+ const probe = await (deps.probeHostedIdentity ?? probeHostedAgentIdentity)(
3157
+ identity.api_key,
3158
+ identity.api_url,
3159
+ deps.fetch
3160
+ );
3161
+ if (probe.status === "ok") hostedDelegateAddress = probe.delegateAddress;
3162
+ if (probe.status !== "ok") {
3163
+ checks.push({
3164
+ id: "identity_match",
3165
+ label: "Hosted identity matches the local signing key",
3166
+ ok: false,
3167
+ 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.`,
3168
+ 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 --runtime ${input.runtime}`
3169
+ });
3170
+ } else if (!localDelegate) {
3171
+ checks.push({
3172
+ id: "identity_match",
3173
+ label: "Hosted identity matches the local signing key",
3174
+ ok: false,
3175
+ detail: "signer.json holds no delegate_address to compare against the hosted identity.",
3176
+ repair: `Re-run the full setup with a fresh token: ${RERUN} --setup <token>.`
3177
+ });
3178
+ } else {
3179
+ const same = probe.delegateAddress?.toLowerCase() === localDelegate.toLowerCase();
3180
+ checks.push({
3181
+ id: "identity_match",
3182
+ label: "Hosted identity matches the local signing key",
3183
+ ok: same,
3184
+ 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.`,
3185
+ ...same ? {} : {
3186
+ 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.`
3187
+ }
3188
+ });
2145
3189
  }
2146
3190
  }
2147
- if (localRuntimeError) {
2148
- const errorCode2 = localRuntimePrepareErrorCode(localRuntimeError);
2149
- return {
2150
- runtime,
2151
- runtimeMcpMode: "local_stdio",
2152
- hostedMcpConfigured: false,
2153
- localSignerConfigured: false,
2154
- localMcpConfigured: false,
2155
- probeResult: errorCode2 === "local_mcp_unsupported_node_version" ? "local_stdio_mcp_unsupported_node_version" : "local_stdio_mcp_runtime_install_failed",
2156
- restartRequired: true,
2157
- nextUserAction: nextAction(runtime, profile.restartMode, errorCode2),
2158
- errorCode: errorCode2,
2159
- configTarget: profile.label,
2160
- signerAcknowledged: signerConsent?.acknowledged,
2161
- localMcpAcknowledged: localMcpConsent?.acknowledged,
2162
- activationCommand: void 0,
2163
- messages: [
2164
- ...consentMessages,
2165
- `Could not prepare local Haven MCP runtime: ${localRuntimeError instanceof Error ? localRuntimeError.message : String(localRuntimeError)}`
2166
- ]
2167
- };
3191
+ const pending = await inspectRekeyPending(directory, deps.now?.() ?? Date.now());
3192
+ if (pending) {
3193
+ checks.push(rekeyPendingCheck(pending, hostedDelegateAddress, input.runtime, sidecar?.server_name));
2168
3194
  }
2169
- let signerCommand;
2170
- if (!localRuntime) {
2171
- progress("Getting the signer ready\u2026");
2172
- try {
2173
- const signerRuntime = await prepareSignerForRuntime(input, deps);
2174
- signerCommand = { command: signerRuntime.command, args: signerRuntime.args };
2175
- consentMessages.push(...signerRuntime.messages);
2176
- } catch (err) {
2177
- return {
2178
- runtime,
2179
- runtimeMcpMode: "hosted_plus_signer",
2180
- hostedMcpConfigured: false,
2181
- localSignerConfigured: false,
2182
- localMcpConfigured: false,
2183
- probeResult: "signer_runtime_install_failed",
2184
- restartRequired: false,
2185
- nextUserAction: "The local Haven signer runtime could not be installed, so no configuration was written. Check your network (a cold install downloads the signer package set) and re-run: npx @haven_ai/connect@alpha",
2186
- errorCode: "signer_runtime_install_failed",
2187
- configTarget: profile.label,
2188
- signerAcknowledged: signerConsent?.acknowledged,
2189
- localMcpAcknowledged: localMcpConsent?.acknowledged,
2190
- activationCommand: void 0,
2191
- signerRuntimePrepared: false,
2192
- messages: [
2193
- ...consentMessages,
2194
- `Could not pre-install the local Haven signer: ${err instanceof Error ? err.message : String(err)}`,
2195
- "No runtime configuration was written (fail-closed): a config pointing at an uninstalled signer looks wired but cannot start.",
2196
- "Re-run `npx @haven_ai/connect@alpha` to retry the setup."
2197
- ]
2198
- };
3195
+ if (sidecar) {
3196
+ const consent = await getLocalSignerConsentStatus(join(directory, "signer.json"));
3197
+ if (!consent.acknowledged) {
3198
+ checks.push({
3199
+ id: "signer_process",
3200
+ label: "Signer stdio handshake",
3201
+ ok: false,
3202
+ detail: "The local-tools consent is not acknowledged, so the signer refuses to start (by design).",
3203
+ repair: `Run: ${RERUN} --ack-local-tools --setup <token> (or re-run your original setup command with --ack-local-tools).`
3204
+ });
3205
+ } else {
3206
+ const probe = await (deps.probeSignerTools ?? probeLocalMcpTools)(
3207
+ sidecar.wrapper_path,
3208
+ [],
3209
+ MCP_RUNTIME_MANIFEST.requiredSignerTools
3210
+ );
3211
+ const experimental = probe.capabilities?.experimental ?? probe.capabilities;
3212
+ const compat = experimental?.["haven/signer-compatibility"];
3213
+ signerCapabilities = compat ? { "haven/signer-compatibility": compat } : void 0;
3214
+ const compatDetail = compat ? ` Compat: x402 expected-context v${JSON.stringify(compat.x402_expected_context_versions ?? "?")}.` : "";
3215
+ checks.push({
3216
+ id: "signer_process",
3217
+ label: "Signer stdio handshake",
3218
+ ok: probe.status === "ok",
3219
+ detail: probe.status === "ok" ? `Signer started, listed ${probe.toolNames?.length ?? 0} tools${probe.serverInfo?.version ? ` (v${probe.serverInfo.version})` : ""}.${compatDetail}` : `Handshake failed: ${probe.status}.`,
3220
+ ...probe.status === "ok" ? {} : { repair: `Run: ${RERUN} --doctor --repair --runtime ${input.runtime}` }
3221
+ });
2199
3222
  }
3223
+ } else {
3224
+ checks.push({
3225
+ id: "signer_process",
3226
+ label: "Signer stdio handshake",
3227
+ ok: false,
3228
+ detail: "Skipped \u2014 no prepared signer runtime to probe.",
3229
+ repair: `Run: ${RERUN} --doctor --repair --runtime ${input.runtime}`
3230
+ });
2200
3231
  }
2201
- const signerRuntimePrepared = localRuntime ? void 0 : signerCommand !== void 0;
2202
- progress("Setting up your Haven tools\u2026");
2203
- const configResult = runtime === "claude-code" ? localRuntime ? await configureClaudeCode(deps, localRuntimeInstall?.command ?? "") : await configureClaudeCodeHosted(deps, input, signerCommand) : await writeRuntimeConfig({
2204
- runtime,
2205
- hostedMcpUrl: input.hostedMcpUrl,
2206
- apiKey: input.apiKey,
2207
- identityPath: input.identityPath,
2208
- signerPath: input.signerPath,
2209
- credentialDirectory: input.credentialDirectory,
2210
- localMcpCommand: localRuntimeInstall?.command,
2211
- signerCommand,
2212
- homeDir: deps.homeDir,
2213
- mode: localRuntime ? "local" : "hosted"
2214
- });
2215
- if (deps.onRuntimeConfigured) {
2216
- const signerCredentialOnDisk = await probeLocalSignerCredential(input.signerPath);
2217
- const earlyLocalMcpOk = configResult.runtimeMcpMode === "local_stdio" && configResult.localMcpConfigured && signerCredentialOnDisk && Boolean(localMcpConsent?.acknowledged);
2218
- const earlySignerOk = configResult.runtimeMcpMode === "local_stdio" ? earlyLocalMcpOk : configResult.signerConfigured && signerCredentialOnDisk && Boolean(signerConsent?.acknowledged);
3232
+ return { checks, ...signerCapabilities ? { signerCapabilities } : {} };
3233
+ }
3234
+ async function runDoctor(input, deps = {}) {
3235
+ const homeDir = deps.homeDir ?? homedir();
3236
+ const checks = [];
3237
+ let signerCapabilities;
3238
+ const { directory, others, parkedOnly } = await discoverCredentialDirectory(homeDir, input.credentialsDir);
3239
+ const configPath = runtimeConfigPathFor(input.runtime, homeDir);
3240
+ let configText = null;
3241
+ if (configPath !== null) {
2219
3242
  try {
2220
- await deps.onRuntimeConfigured({
2221
- runtime,
2222
- runtimeMcpMode: configResult.runtimeMcpMode,
2223
- hostedMcpConfigured: configResult.hostedConfigured,
2224
- localSignerConfigured: earlySignerOk,
2225
- localMcpConfigured: earlyLocalMcpOk,
2226
- signerAcknowledged: signerConsent?.acknowledged,
2227
- localMcpAcknowledged: localMcpConsent?.acknowledged,
2228
- restartRequired: configResult.restartRequired || restartRequiredForRuntime(runtime, deps.env),
2229
- nextUserAction: nextAction(runtime, profile.restartMode, configResult.errorCode),
2230
- errorCode: configResult.errorCode
2231
- });
3243
+ configText = await readFile(configPath, "utf8");
2232
3244
  } catch {
3245
+ configText = null;
2233
3246
  }
2234
3247
  }
2235
- progress("Almost there \u2014 just confirming everything connects\u2026");
2236
- const localProbePromise = configResult.runtimeMcpMode === "local_stdio" && localRuntimeInstall ? runLocalMcpProbe(localRuntimeInstall, deps) : Promise.resolve(void 0);
2237
- const signerProbePromise = configResult.runtimeMcpMode !== "local_stdio" && signerCommand ? (deps.probeSignerTools ?? probeLocalMcpTools)(
2238
- signerCommand.command,
2239
- signerCommand.args,
2240
- MCP_RUNTIME_MANIFEST.requiredSignerTools
2241
- ) : Promise.resolve(void 0);
2242
- const [hostedProbe, signerCredentialReady, localMcpProbe, signerProbe] = await Promise.all([
2243
- configResult.hostedConfigured ? probeHostedMcpTools(input.apiKey, input.hostedMcpUrl, deps.fetch) : Promise.resolve({ status: "bad_response" }),
2244
- probeLocalSignerCredential(input.signerPath),
2245
- localProbePromise,
2246
- signerProbePromise
2247
- ]);
2248
- const hostedOk = configResult.hostedConfigured && hostedProbe.status === "ok";
2249
- const localMcpOk = configResult.runtimeMcpMode === "local_stdio" && configResult.localMcpConfigured && signerCredentialReady && Boolean(localMcpConsent?.acknowledged) && localMcpProbe?.status === "ok";
2250
- const signerOk = configResult.runtimeMcpMode === "local_stdio" ? localMcpOk : configResult.signerConfigured && signerCredentialReady && Boolean(signerConsent?.acknowledged) && // #1587: no handshake, no green. A signer command that was registered
2251
- // but not probed (manual topology) keeps the old semantics.
2252
- (signerProbe === void 0 || signerProbe.status === "ok");
2253
- const restartRequired = configResult.restartRequired || restartRequiredForRuntime(runtime, deps.env);
2254
- const errorCode = configResult.errorCode ?? (configResult.runtimeMcpMode === "local_stdio" ? localMcpErrorCode(signerCredentialReady, localMcpConsent, localMcpProbe?.status) : hostedMcpErrorCode(configResult.hostedConfigured, hostedProbe.status) ?? signerConsentErrorCode(signerCredentialReady, signerConsent) ?? signerProbeErrorCode(signerProbe));
2255
- const hostedProbeMessages = configResult.hostedConfigured && hostedProbe.status !== "ok" ? [`Hosted Haven MCP probe failed: ${hostedProbe.status}.`] : configResult.hostedConfigured ? ["Verified hosted Haven MCP tools with a read-only handshake."] : [];
2256
- const signerProbeMessages = signerProbe ? signerProbe.status === "ok" ? ["Verified local Haven signer with a stdio handshake."] : [
2257
- `Local Haven signer handshake failed: ${signerProbe.status}.`,
2258
- "Re-run `npx @haven_ai/connect@alpha` to repair the signer setup."
2259
- ] : [];
2260
- const localProbeMessages = localMcpProbe && localMcpProbe.status !== "ok" ? [`Local Haven MCP handshake failed: ${localMcpProbe.status}.`] : localMcpProbe?.status === "ok" ? ["Verified local Haven MCP tools with a stdio handshake."] : [];
2261
- const skillInstall = !configResult.errorCode ? await installSkillForRuntime(runtime, { homeDir: deps.homeDir, env: deps.env }) : void 0;
2262
- return {
2263
- runtime,
2264
- runtimeMcpMode: configResult.runtimeMcpMode,
2265
- hostedMcpConfigured: hostedOk,
2266
- localSignerConfigured: signerOk,
2267
- localMcpConfigured: localMcpOk,
2268
- probeResult: buildProbeResult(configResult.runtimeMcpMode, configResult.hostedConfigured, hostedProbe.status, signerOk, localMcpOk, localMcpProbe?.status),
2269
- restartRequired,
2270
- nextUserAction: nextAction(runtime, profile.restartMode, errorCode),
2271
- errorCode,
2272
- configTarget: configResult.target,
2273
- signerAcknowledged: signerConsent?.acknowledged,
2274
- localMcpAcknowledged: localMcpConsent?.acknowledged,
2275
- activationCommand: configResult.activationCommand,
2276
- skillInstalled: skillInstall?.installed,
2277
- signerRuntimePrepared,
2278
- messages: [...consentMessages, ...localRuntimeInstall?.messages ?? [], ...configResult.messages, ...hostedProbeMessages, ...signerProbeMessages, ...localProbeMessages, ...skillInstall?.messages ?? []]
2279
- };
2280
- }
2281
- function runtimeInstallCapabilities(runtime, env = process.env) {
2282
- const profile = runtimeProfile(runtime, env);
3248
+ const allDirectories = directory ? [directory, ...others] : others;
3249
+ let bareOwnerExists = false;
3250
+ for (const dir of allDirectories) {
3251
+ const sidecar = await readRuntimeSidecar(dir);
3252
+ if (!sidecar?.server_name && sidecar?.wrapper_path && configText?.includes(sidecar.wrapper_path)) {
3253
+ bareOwnerExists = true;
3254
+ break;
3255
+ }
3256
+ }
3257
+ const inventory = [];
3258
+ const capabilitiesByDirectory = /* @__PURE__ */ new Map();
3259
+ const primaryChecksById = /* @__PURE__ */ new Map();
3260
+ for (const dir of allDirectories) {
3261
+ const identity = await readIdentity(dir);
3262
+ const sidecar = await readRuntimeSidecar(dir);
3263
+ const tombstone = await readAgentTombstone(dir);
3264
+ const slug = sidecar?.server_name;
3265
+ const names = serverNamesFor(slug);
3266
+ const rekeyPending = await inspectRekeyPending(dir, deps.now?.() ?? Date.now());
3267
+ if (!identity?.api_key) {
3268
+ const agentId = tombstone?.agent_id ?? rekeyPending?.agentId;
3269
+ inventory.push({
3270
+ ...slug ? { slug } : {},
3271
+ ...agentId ? { agentId } : {},
3272
+ directory: dir,
3273
+ // A tombstone is a deliberate record and outranks the discovery tell:
3274
+ // a retired directory that also holds a parked key stays `retired`.
3275
+ classification: tombstone ? "retired" : parkedOnly.has(dir) ? "parked" : "orphaned",
3276
+ checks: rekeyPending ? [rekeyPendingCheck(rekeyPending, void 0, input.runtime, slug)] : [],
3277
+ ...rekeyPending ? { rekeyPending } : {}
3278
+ });
3279
+ continue;
3280
+ }
3281
+ const wired = agentIsWired(configText, names, slug, identity, sidecar, dir === directory, bareOwnerExists);
3282
+ const entry = {
3283
+ ...slug ? { slug } : {},
3284
+ ...identity.agent_id ? { agentId: identity.agent_id } : {},
3285
+ directory: dir,
3286
+ classification: wired ? "wired" : "superseded",
3287
+ checks: [],
3288
+ ...rekeyPending ? { rekeyPending } : {}
3289
+ };
3290
+ if (wired) {
3291
+ const result = await checksForAgent({ directory: dir, identity, sidecar }, input, deps);
3292
+ entry.checks = result.checks;
3293
+ capabilitiesByDirectory.set(dir, result.signerCapabilities);
3294
+ } else if (rekeyPending) {
3295
+ entry.checks = [rekeyPendingCheck(rekeyPending, void 0, input.runtime, slug)];
3296
+ }
3297
+ inventory.push(entry);
3298
+ }
3299
+ const wiredDirectories = inventory.filter((entry) => entry.classification === "wired").map((entry) => entry.directory);
3300
+ const primaryDirectory = input.credentialsDir ? directory : wiredDirectories.includes(directory ?? "") ? directory : wiredDirectories[0] ?? directory;
3301
+ if (primaryDirectory) {
3302
+ const primaryEntry = inventory.find((entry) => entry.directory === primaryDirectory);
3303
+ signerCapabilities = capabilitiesByDirectory.get(primaryDirectory);
3304
+ for (const check of primaryEntry?.checks ?? []) primaryChecksById.set(check.id, check);
3305
+ }
3306
+ if (!primaryDirectory) {
3307
+ checks.push({
3308
+ id: "credentials",
3309
+ label: "Agent credentials",
3310
+ ok: false,
3311
+ detail: "No agent credential directory with an identity.json under ~/.haven/agents.",
3312
+ repair: `Run the full setup once: ${RERUN} --setup <token from the Haven dashboard>.`
3313
+ });
3314
+ } else {
3315
+ const primaryIdentity = await readIdentity(primaryDirectory);
3316
+ const primarySidecar = await readRuntimeSidecar(primaryDirectory);
3317
+ if (!primaryChecksById.has("credentials")) {
3318
+ const result = await checksForAgent(
3319
+ { directory: primaryDirectory, identity: primaryIdentity, sidecar: primarySidecar },
3320
+ input,
3321
+ deps
3322
+ );
3323
+ signerCapabilities = result.signerCapabilities;
3324
+ for (const check of result.checks) primaryChecksById.set(check.id, check);
3325
+ }
3326
+ for (const id of ["credentials", "signer_runtime"]) {
3327
+ const check = primaryChecksById.get(id);
3328
+ if (check) checks.push(check);
3329
+ }
3330
+ }
3331
+ if (configPath === null) {
3332
+ checks.push({
3333
+ id: "runtime_config",
3334
+ label: "Runtime MCP config",
3335
+ ok: true,
3336
+ detail: `Runtime '${input.runtime}' has no file-based config the connector owns (CLI-managed) \u2014 skipping the file check.`
3337
+ });
3338
+ } else if (configText === null) {
3339
+ checks.push({
3340
+ id: "runtime_config",
3341
+ label: "Runtime MCP config",
3342
+ ok: false,
3343
+ detail: `No runtime config at ${configPath}.`,
3344
+ repair: `Run: ${RERUN} --doctor --repair --runtime ${input.runtime}`
3345
+ });
3346
+ } else {
3347
+ const primaryIdentity = await readIdentity(primaryDirectory ?? "");
3348
+ const primarySidecar = primaryDirectory ? await readRuntimeSidecar(primaryDirectory) : null;
3349
+ const hasHaven = primaryIdentity?.hosted_mcp_url ? configText.includes(primaryIdentity.hosted_mcp_url) : configText.includes("haven");
3350
+ const signerViaNpx = configText.includes("@haven_ai/signer");
3351
+ const wrapperReferenced = primarySidecar ? configText.includes(primarySidecar.wrapper_path) : false;
3352
+ const ok = hasHaven && !signerViaNpx && (primarySidecar ? wrapperReferenced : true);
3353
+ checks.push({
3354
+ id: "runtime_config",
3355
+ label: "Runtime MCP config",
3356
+ ok,
3357
+ 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)" : ""}.`,
3358
+ ...ok ? {} : { repair: `Run: ${RERUN} --doctor --repair --runtime ${input.runtime}` }
3359
+ });
3360
+ }
3361
+ for (const id of ["hosted_mcp", "identity_match", "rekey_pending"]) {
3362
+ const check = primaryChecksById.get(id);
3363
+ if (check) checks.push(check);
3364
+ }
3365
+ const otherEntries = inventory.filter((entry) => entry.directory !== primaryDirectory);
3366
+ if (otherEntries.length > 0) {
3367
+ const live = [];
3368
+ const revoked = [];
3369
+ const unverifiable = [];
3370
+ const retired = [];
3371
+ for (const entry of otherEntries) {
3372
+ const identity = await readIdentity(entry.directory);
3373
+ const tombstone = await readAgentTombstone(entry.directory);
3374
+ const otherAgent = entry.agentId ?? basename(entry.directory);
3375
+ const otherUrl = identity?.hosted_mcp_url ?? (identity?.api_url ? `${identity.api_url}/mcp` : void 0);
3376
+ if (!identity?.api_key || !otherUrl) {
3377
+ if (tombstone) retired.push(`${otherAgent} (retired ${tombstone.retired_at})`);
3378
+ else unverifiable.push(`${otherAgent} (no stored key/URL to probe)`);
3379
+ continue;
3380
+ }
3381
+ const suffix = tombstone ? " [tombstoned \u2014 key material still present]" : "";
3382
+ const probe = await (deps.probeHosted ?? probeHostedMcpTools)(identity.api_key, otherUrl, deps.fetch);
3383
+ if (probe.status === "ok") live.push({ label: `${otherAgent}${suffix}`, entry });
3384
+ else if (probe.status === "unauthorized") revoked.push(`${otherAgent}${suffix}`);
3385
+ else unverifiable.push(`${otherAgent} (${probe.status})${suffix}`);
3386
+ }
3387
+ const parts = [];
3388
+ if (live.length > 0) parts.push(`STILL SPEND-CAPABLE: ${live.map((item) => item.label).join(", ")}`);
3389
+ if (revoked.length > 0) parts.push(`already revoked: ${revoked.join(", ")}`);
3390
+ if (retired.length > 0) parts.push(`tombstoned (keys removed): ${retired.join(", ")}`);
3391
+ if (unverifiable.length > 0) parts.push(`could not verify: ${unverifiable.join(", ")}`);
3392
+ const supersededLive = live.filter((item) => item.entry.classification !== "wired").map((item) => item.label);
3393
+ checks.push({
3394
+ id: "superseded_agents",
3395
+ label: "Superseded agent credentials",
3396
+ ok: supersededLive.length === 0,
3397
+ detail: supersededLive.length > 0 ? `${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.` : `${otherEntries.length} other credential dir(s) found \u2014 ${parts.join("; ")}.`,
3398
+ ...supersededLive.length > 0 ? {
3399
+ 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.`
3400
+ } : {}
3401
+ });
3402
+ }
3403
+ const parkedElsewhere = inventory.filter((entry) => entry.directory !== primaryDirectory && entry.rekeyPending).map((entry) => ({ entry, pending: entry.rekeyPending }));
3404
+ if (parkedElsewhere.length > 0) {
3405
+ const abandoned = parkedElsewhere.filter((item) => item.pending.state !== "pending");
3406
+ const describe = (item) => `${item.entry.slug ?? item.entry.agentId ?? basename(item.entry.directory)} (${item.pending.state}, ${item.pending.path})`;
3407
+ checks.push({
3408
+ id: "rekey_pending_elsewhere",
3409
+ label: "Parked re-keys in other credential directories",
3410
+ ok: abandoned.length === 0,
3411
+ 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(", ")}.`,
3412
+ ...abandoned.length > 0 ? {
3413
+ 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."
3414
+ } : {}
3415
+ });
3416
+ }
3417
+ const signerProcess = primaryChecksById.get("signer_process");
3418
+ if (signerProcess) checks.push(signerProcess);
3419
+ const restart = restartRequiredForRuntime(input.runtime, deps.env);
3420
+ checks.push({
3421
+ id: "restart",
3422
+ label: "Runtime restart",
3423
+ ok: true,
3424
+ detail: restart ? "This runtime loads MCP config at startup \u2014 restart it after any repair before expecting the tools to appear." : "No restart requirement known for this runtime."
3425
+ });
3426
+ const wiredOk = inventory.filter((entry) => entry.classification === "wired").every((entry) => entry.checks.every((check) => check.ok));
2283
3427
  return {
2284
- canWriteRuntimeConfig: profile.canWriteRuntimeConfig,
2285
- restartRequired: restartRequiredForRuntime(runtime, env)
3428
+ version: 1,
3429
+ ok: checks.every((check) => check.ok) && wiredOk,
3430
+ runtime: input.runtime,
3431
+ credentialDirectory: primaryDirectory,
3432
+ checks,
3433
+ agents: inventory,
3434
+ ...signerCapabilities ? { signerCapabilities } : {}
2286
3435
  };
2287
3436
  }
2288
- async function configureClaudeCode(deps, localMcpCommand) {
2289
- const runCommand = deps.runCommand ?? defaultRunCommand;
2290
- const serverJson = JSON.stringify({
2291
- type: "stdio",
2292
- command: localMcpCommand,
2293
- args: [],
2294
- env: {}
2295
- });
2296
- try {
2297
- if (!localMcpCommand) throw new Error("local MCP wrapper command is required");
2298
- await runCommand("claude", ["mcp", "remove", "haven"]).catch(() => void 0);
2299
- await runCommand("claude", ["mcp", "remove", "haven-signer"]).catch(() => void 0);
2300
- await runCommand("claude", ["mcp", "add-json", "haven", serverJson, "--scope", "user"]).catch(async () => {
2301
- await runCommand("claude", ["mcp", "add", "haven", "--scope", "user", "--", localMcpCommand]);
2302
- });
2303
- const verified = await runCommand("claude", ["mcp", "get", "haven"]).then(() => true).catch(() => false);
2304
- return {
2305
- hostedConfigured: false,
2306
- signerConfigured: true,
2307
- localMcpConfigured: true,
2308
- runtimeMcpMode: "local_stdio",
2309
- target: "Claude Code MCP config",
2310
- changed: true,
2311
- restartRequired: true,
2312
- messages: [
2313
- "Updated local Haven MCP entry with Claude Code.",
2314
- ...verified ? ["Verified Claude Code MCP entry."] : []
2315
- ]
2316
- };
2317
- } catch (err) {
3437
+ async function runRepair(input, deps = {}) {
3438
+ const homeDir = deps.homeDir ?? homedir();
3439
+ const messages = [];
3440
+ const { directory, others } = await discoverCredentialDirectory(homeDir, input.credentialsDir);
3441
+ if (others.length > 0) {
3442
+ messages.push(`Note: ${others.length} other agent credential dir(s) exist \u2014 run --doctor for their status.`);
3443
+ }
3444
+ if (!directory) {
2318
3445
  return {
2319
- hostedConfigured: false,
2320
- signerConfigured: false,
2321
- localMcpConfigured: false,
2322
- runtimeMcpMode: "local_stdio",
2323
- target: "Claude Code MCP config",
2324
- changed: false,
2325
- restartRequired: true,
2326
- messages: [
2327
- `Could not update Claude Code MCP config: ${err instanceof Error ? err.message : String(err)}`,
2328
- "Install Claude Code or rerun the Haven setup command inside a Claude Code terminal."
2329
- ],
2330
- errorCode: "claude_code_config_failed"
3446
+ ok: false,
3447
+ messages: [`No agent credentials found to repair \u2014 run the full setup: ${RERUN} --setup <token>.`]
2331
3448
  };
2332
3449
  }
2333
- }
2334
- async function configureClaudeCodeHosted(deps, input, signerCommand) {
2335
- const runCommand = deps.runCommand ?? defaultRunCommand;
2336
- const hostedJson = JSON.stringify({
2337
- type: "http",
2338
- url: input.hostedMcpUrl,
2339
- headers: { Authorization: `Bearer ${input.apiKey}` }
2340
- });
2341
- const signerJson = JSON.stringify({
2342
- type: "stdio",
2343
- command: signerCommand?.command ?? "npx",
2344
- args: signerCommand?.args ?? ["-y", signerPackageSpec(), "--credentials", input.signerPath],
2345
- env: {}
2346
- });
3450
+ let identity;
2347
3451
  try {
2348
- await runCommand("claude", ["mcp", "remove", "haven"]).catch(() => void 0);
2349
- await runCommand("claude", ["mcp", "remove", "haven-signer"]).catch(() => void 0);
2350
- await runCommand("claude", ["mcp", "add-json", "haven", hostedJson, "--scope", "user"]);
2351
- await runCommand("claude", ["mcp", "add-json", "haven-signer", signerJson, "--scope", "user"]);
2352
- const verified = await runCommand("claude", ["mcp", "get", "haven"]).then(() => true).catch(() => false);
2353
- return {
2354
- hostedConfigured: true,
2355
- signerConfigured: true,
2356
- localMcpConfigured: false,
2357
- runtimeMcpMode: "hosted_plus_signer",
2358
- target: "Claude Code MCP config",
2359
- changed: true,
2360
- restartRequired: true,
2361
- messages: [
2362
- "Updated hosted Haven MCP and local signer entries with Claude Code.",
2363
- ...verified ? ["Verified Claude Code MCP entry."] : []
2364
- ]
2365
- };
2366
- } catch (err) {
2367
- return {
2368
- hostedConfigured: false,
2369
- signerConfigured: false,
2370
- localMcpConfigured: false,
2371
- runtimeMcpMode: "hosted_plus_signer",
2372
- target: "Claude Code MCP config",
2373
- changed: false,
2374
- restartRequired: true,
2375
- messages: [
2376
- `Could not update Claude Code MCP config: ${err instanceof Error ? err.message : String(err)}`,
2377
- "Install Claude Code or rerun the Haven setup command inside a Claude Code terminal."
2378
- ],
2379
- errorCode: "claude_code_config_failed"
2380
- };
3452
+ identity = JSON.parse(await readFile(join(directory, "identity.json"), "utf8"));
3453
+ } catch {
3454
+ return { ok: false, messages: ["identity.json is unreadable \u2014 re-run the full setup with a fresh token."] };
2381
3455
  }
2382
- }
2383
- async function defaultRunCommand(command, args) {
2384
- await execFileAsync3(command, args, { timeout: 1e4 });
2385
- }
2386
- function buildProbeResult(mode, hostedConfigured, hostedStatus, signerReady, localMcpReady, localMcpProbeStatus) {
2387
- if (mode === "local_stdio") {
2388
- if (localMcpReady) return "local_stdio_mcp_ready";
2389
- return localMcpProbeStatus ? `local_stdio_mcp_${localMcpProbeStatus}` : "local_stdio_mcp_unavailable";
3456
+ if (!identity.api_key || !(identity.hosted_mcp_url || identity.api_url)) {
3457
+ return { ok: false, messages: ["identity.json lacks the stored API key / hosted URL \u2014 re-run the full setup."] };
2390
3458
  }
2391
- const hostedPart = hostedConfigured ? `hosted_${hostedStatus}` : "hosted_not_configured";
2392
- const signerPart = signerReady ? "local_signer_ready" : "local_signer_unavailable";
2393
- return `${hostedPart}_${signerPart}`.slice(0, 120);
2394
- }
2395
- async function resolveLocalMcpConsent(input, messages) {
2396
- if (input.ackLocalTools || input.ackSigner) {
2397
- const status = await acknowledgeLocalMcpConsent(input.identityPath, input.signerPath, (message) => messages.push(message));
2398
- if (status.acknowledged) {
2399
- messages.push("Prepared the local Haven tools acknowledgement.");
2400
- } else {
2401
- messages.push("Local Haven tools acknowledgement still needs attention.");
3459
+ const configPath = runtimeConfigPathFor(input.runtime, homeDir);
3460
+ if (configPath) {
3461
+ try {
3462
+ const existing = await readFile(configPath, "utf8");
3463
+ if (existing.includes("bin/haven-mcp") || existing.includes(".haven/mcp-runtime")) {
3464
+ return {
3465
+ ok: false,
3466
+ messages: [
3467
+ `The config at ${configPath} is the LOCAL-stdio topology (--local). Repair currently rewrites only the hosted+signer shape and will not touch it.`,
3468
+ "Re-run your original setup command (with --local) to repair a local-stdio install."
3469
+ ]
3470
+ };
3471
+ }
3472
+ } catch {
2402
3473
  }
2403
- return status;
2404
3474
  }
2405
- return getLocalMcpConsentStatus(input.identityPath, input.signerPath);
3475
+ const existingSidecar = await readRuntimeSidecar(directory);
3476
+ const serverName = existingSidecar?.server_name;
3477
+ const signerPath = join(directory, "signer.json");
3478
+ const prepared = await prepareSignerRuntime(
3479
+ { credentialDirectory: directory, signerPath, homeDir, serverName },
3480
+ { runCommand: deps.runCommand }
3481
+ );
3482
+ messages.push(...prepared.messages);
3483
+ const names = serverNamesFor(serverName);
3484
+ messages.push(`Rewriting MCP entries ${names.hosted} / ${names.signer}${serverName ? ` (agent "${serverName}")` : " (unnamed pair)"} \u2014 no other pair is touched.`);
3485
+ const configResult = await writeRuntimeConfig({
3486
+ runtime: input.runtime,
3487
+ hostedMcpUrl: identity.hosted_mcp_url ?? `${identity.api_url}/mcp`,
3488
+ apiKey: identity.api_key,
3489
+ identityPath: join(directory, "identity.json"),
3490
+ signerPath,
3491
+ credentialDirectory: directory,
3492
+ signerCommand: { command: prepared.command, args: prepared.args },
3493
+ homeDir,
3494
+ mode: "hosted",
3495
+ serverName
3496
+ });
3497
+ messages.push(...configResult.messages);
3498
+ messages.push("Repair complete \u2014 restart the runtime, then verify with --doctor.");
3499
+ return { ok: true, messages };
2406
3500
  }
2407
- async function resolveSignerConsent(input, messages) {
2408
- if (input.ackSigner || input.ackLocalTools) {
2409
- const status = await acknowledgeLocalSignerConsent(input.signerPath, (message) => messages.push(message));
2410
- if (status.acknowledged) {
2411
- messages.push("Prepared the local Haven signer acknowledgement.");
2412
- } else {
2413
- messages.push("Local Haven signer acknowledgement still needs attention.");
3501
+ var RERUN;
3502
+ var init_doctor = __esm({
3503
+ "src/doctor.ts"() {
3504
+ init_runtime_manifest();
3505
+ init_probes();
3506
+ init_signer_runtime();
3507
+ init_config_writers();
3508
+ init_runtime_registry();
3509
+ init_signer_consent();
3510
+ init_tombstone();
3511
+ init_server_names();
3512
+ init_storage();
3513
+ init_redact();
3514
+ RERUN = "npx @haven_ai/connect@alpha";
3515
+ }
3516
+ });
3517
+
3518
+ // src/runtime.ts
3519
+ init_api();
3520
+ init_key();
3521
+ init_redact();
3522
+ init_server_names();
3523
+ init_storage();
3524
+ init_runtime_install();
3525
+ init_runtime_registry();
3526
+ init_connect_error();
3527
+
3528
+ // src/installed-clients.ts
3529
+ init_connect_error();
3530
+ init_config_writers();
3531
+ init_runtime_registry();
3532
+ var SCAN_ORDER = [
3533
+ "claude-code",
3534
+ "codex-cli",
3535
+ "cursor",
3536
+ "vscode",
3537
+ "vscode-insiders",
3538
+ "claude-desktop",
3539
+ "hermes"
3540
+ ];
3541
+ function installedClientTargets(homeDir = homedir(), cwd = process.cwd(), env = process.env) {
3542
+ const targets = [
3543
+ {
3544
+ runtime: "claude-code",
3545
+ label: "Claude Code",
3546
+ // Claude Code is configured through its own CLI (`claude mcp add-json`),
3547
+ // not by writing a file this module owns — so its evidence is the
3548
+ // client directory, never a config path.
3549
+ configPath: null,
3550
+ markers: [join(homeDir, ".claude"), join(homeDir, ".claude.json")]
3551
+ },
3552
+ {
3553
+ runtime: "codex-cli",
3554
+ // Both Codex surfaces write the same ~/.codex/config.toml, so they are
3555
+ // ONE candidate. Splitting them would ask the user to answer a question
3556
+ // whose answers are the same write.
3557
+ label: "Codex (CLI or Desktop)",
3558
+ configPath: runtimeConfigPathFor("codex-cli", homeDir),
3559
+ markers: [join(homeDir, ".codex")]
3560
+ },
3561
+ {
3562
+ runtime: "cursor",
3563
+ label: "Cursor",
3564
+ configPath: runtimeConfigPathFor("cursor", homeDir),
3565
+ markers: [join(homeDir, ".cursor")]
3566
+ },
3567
+ {
3568
+ runtime: "vscode",
3569
+ label: "VS Code",
3570
+ configPath: runtimeConfigPathFor("vscode", homeDir),
3571
+ markers: [resolve(cwd, ".vscode")]
3572
+ },
3573
+ {
3574
+ runtime: "vscode-insiders",
3575
+ label: "VS Code Insiders",
3576
+ configPath: runtimeConfigPathFor("vscode-insiders", homeDir),
3577
+ markers: []
3578
+ },
3579
+ {
3580
+ runtime: "claude-desktop",
3581
+ label: "Claude Desktop",
3582
+ configPath: runtimeConfigPathFor("claude-desktop", homeDir),
3583
+ markers: []
3584
+ },
3585
+ {
3586
+ runtime: "hermes",
3587
+ label: "Hermes Agent",
3588
+ configPath: runtimeConfigPathFor("hermes", homeDir),
3589
+ markers: [env.HERMES_HOME ?? join(homeDir, ".hermes")]
3590
+ }
3591
+ ];
3592
+ return targets.filter((target) => runtimeProfile(target.runtime, {}).canWriteRuntimeConfig);
3593
+ }
3594
+ async function scanInstalledClients(options = {}) {
3595
+ const exists = options.exists ?? pathExists;
3596
+ const targets = installedClientTargets(options.homeDir, options.cwd, options.env ?? process.env);
3597
+ const found = [];
3598
+ for (const target of targets) {
3599
+ if (target.configPath && await exists(target.configPath)) {
3600
+ found.push({
3601
+ runtime: target.runtime,
3602
+ label: target.label,
3603
+ detail: `MCP config found at ${target.configPath}`,
3604
+ configPath: target.configPath,
3605
+ evidence: "config-file"
3606
+ });
3607
+ continue;
3608
+ }
3609
+ for (const marker of target.markers) {
3610
+ if (!await exists(marker)) continue;
3611
+ found.push({
3612
+ runtime: target.runtime,
3613
+ label: target.label,
3614
+ detail: `installed (${marker})`,
3615
+ configPath: target.configPath,
3616
+ evidence: "client-directory"
3617
+ });
3618
+ break;
2414
3619
  }
2415
- return status;
2416
3620
  }
2417
- return getLocalSignerConsentStatus(input.signerPath);
2418
- }
2419
- function signerConsentErrorCode(signerCredentialReady, signerConsent) {
2420
- if (!signerCredentialReady) return "local_signer_credential_unavailable";
2421
- if (!signerConsent?.acknowledged) return "local_signer_ack_required";
2422
- return void 0;
2423
- }
2424
- function signerProbeErrorCode(probe) {
2425
- if (!probe || probe.status === "ok") return void 0;
2426
- return `local_signer_probe_${probe.status}`;
2427
- }
2428
- function hostedMcpErrorCode(hostedConfigured, hostedProbeStatus) {
2429
- if (!hostedConfigured || hostedProbeStatus === "ok") return void 0;
2430
- return `hosted_mcp_probe_${hostedProbeStatus}`;
2431
- }
2432
- function localMcpErrorCode(signerCredentialReady, localMcpConsent, localMcpProbeStatus) {
2433
- if (!signerCredentialReady) return "local_signer_credential_unavailable";
2434
- if (!localMcpConsent?.acknowledged) return "local_mcp_ack_required";
2435
- if (localMcpProbeStatus && localMcpProbeStatus !== "ok") return `local_mcp_probe_${localMcpProbeStatus}`;
2436
- return void 0;
2437
- }
2438
- function nextAction(runtime, restartMode, errorCode) {
2439
- if (errorCode) return "return_to_haven_for_wallet_approval_then_finish_runtime_setup";
2440
- if (restartMode === "hot-reload") return "return_to_haven_for_wallet_approval";
2441
- if (runtime === "codex-cli" || runtime === "codex-desktop") return "return_to_haven_for_wallet_approval_then_restart_codex";
2442
- if (runtime === "claude-code") return "return_to_haven_for_wallet_approval_then_restart_claude_code";
2443
- if (restartMode === "restart-app") return "return_to_haven_for_wallet_approval_then_restart_app";
2444
- if (restartMode === "restart-session") return "return_to_haven_for_wallet_approval_then_restart_agent_session";
2445
- return "return_to_haven_for_wallet_approval_then_configure_runtime";
2446
- }
2447
- function supportsLocalMcp(runtime) {
2448
- return runtime === "codex-cli" || runtime === "codex-desktop" || runtime === "claude-code";
2449
- }
2450
- async function prepareRuntimeForLocalMcp(input, deps) {
2451
- const prepare = deps.prepareLocalMcpRuntime ?? ((runtimeInput) => prepareLocalMcpRuntime(runtimeInput, { runCommand: deps.runCommand, onProgress: deps.onProgress }));
2452
- return prepare({
2453
- credentialDirectory: input.credentialDirectory,
2454
- identityPath: input.identityPath,
2455
- signerPath: input.signerPath,
2456
- homeDir: deps.homeDir
3621
+ return found.sort((a, b) => {
3622
+ if (a.evidence !== b.evidence) return a.evidence === "config-file" ? -1 : 1;
3623
+ return SCAN_ORDER.indexOf(a.runtime) - SCAN_ORDER.indexOf(b.runtime);
2457
3624
  });
2458
3625
  }
2459
- async function prepareSignerForRuntime(input, deps) {
2460
- const prepare = deps.prepareSignerRuntime ?? ((runtimeInput) => (
2461
- // onProgress threaded through on purpose (#1586 review): without it the
2462
- // install heartbeat was dead code in production and the console still
2463
- // went silent for the whole cold install — the exact symptom the issue
2464
- // set out to remove, at a longer timeout.
2465
- prepareSignerRuntime(runtimeInput, { runCommand: deps.runCommand, onProgress: deps.onProgress })
2466
- ));
2467
- return prepare({
2468
- credentialDirectory: input.credentialDirectory,
2469
- signerPath: input.signerPath,
2470
- homeDir: deps.homeDir
3626
+ var MAX_PROMPT_ATTEMPTS = 3;
3627
+ async function promptForInstalledClient(candidates, io = defaultPromptIo()) {
3628
+ if (candidates.length === 0) throw noInstalledClientsError();
3629
+ io.write("Haven could not detect which agent runtime this is.\n");
3630
+ io.write("These agent clients are installed on this machine:\n");
3631
+ candidates.forEach((candidate, index) => {
3632
+ io.write(` ${index + 1}) ${candidate.label} \u2014 ${candidate.detail}
3633
+ `);
2471
3634
  });
3635
+ 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");
3636
+ for (let attempt = 0; attempt < MAX_PROMPT_ATTEMPTS; attempt += 1) {
3637
+ const answer = await io.question(`Which one? [1-${candidates.length}] (default 1 \u2014 ${candidates[0].label}): `);
3638
+ if (answer === null) throw promptAbortedError("the prompt was cancelled");
3639
+ const trimmed = answer.trim();
3640
+ if (trimmed === "") return candidates[0].runtime;
3641
+ const picked = Number.parseInt(trimmed, 10);
3642
+ if (Number.isInteger(picked) && picked >= 1 && picked <= candidates.length) {
3643
+ return candidates[picked - 1].runtime;
3644
+ }
3645
+ io.write(`"${trimmed}" is not one of 1-${candidates.length}.
3646
+ `);
3647
+ }
3648
+ throw promptAbortedError(`no valid choice after ${MAX_PROMPT_ATTEMPTS} attempts`);
3649
+ }
3650
+ async function resolveRuntimeByInstalledClientPrompt(options = {}) {
3651
+ const candidates = await scanInstalledClients(options);
3652
+ if (candidates.length === 0) throw noInstalledClientsError();
3653
+ return promptForInstalledClient(candidates, options.io ?? defaultPromptIo());
3654
+ }
3655
+ function noInstalledClientsError() {
3656
+ return new ConnectError(
3657
+ "runtime_no_installed_clients",
3658
+ "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.",
3659
+ "rerun_connect_with_explicit_runtime"
3660
+ );
2472
3661
  }
2473
- async function runLocalMcpProbe(runtimeInstall, deps) {
2474
- const probe = deps.probeLocalMcpTools ?? probeLocalMcpTools;
3662
+ function promptAbortedError(reason) {
3663
+ return new ConnectError(
3664
+ "runtime_prompt_aborted",
3665
+ `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 setup command again, or pass --runtime <name> to skip the prompt.`,
3666
+ "rerun_connect_and_choose_a_runtime"
3667
+ );
3668
+ }
3669
+ async function pathExists(path) {
2475
3670
  try {
2476
- return await probe(runtimeInstall.command, runtimeInstall.args, MCP_RUNTIME_MANIFEST.requiredTools);
3671
+ await access(path);
3672
+ return true;
2477
3673
  } catch {
2478
- return { status: "process_error" };
3674
+ return false;
2479
3675
  }
2480
3676
  }
2481
- function localRuntimePrepareErrorCode(err) {
2482
- if (err && typeof err === "object" && "code" in err && err.code === "local_mcp_unsupported_node_version") {
2483
- return "local_mcp_unsupported_node_version";
2484
- }
2485
- return "local_mcp_runtime_install_failed";
3677
+ function defaultPromptIo() {
3678
+ return {
3679
+ write: (text) => process.stdout.write(text),
3680
+ question: (query) => new Promise((resolvePromise) => {
3681
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
3682
+ let settled = false;
3683
+ const settle = (value) => {
3684
+ if (settled) return;
3685
+ settled = true;
3686
+ rl.close();
3687
+ resolvePromise(value);
3688
+ };
3689
+ rl.once("SIGINT", () => settle(null));
3690
+ rl.once("close", () => settle(null));
3691
+ rl.question(query, (answer) => settle(answer));
3692
+ })
3693
+ };
2486
3694
  }
2487
3695
 
2488
3696
  // src/runtime.ts
2489
- init_runtime_registry();
3697
+ init_local_mcp_runtime();
2490
3698
  init_runtime_manifest();
2491
- var CONNECTOR_VERSION = "0.1.28-alpha.0";
3699
+ var CONNECTOR_VERSION = "0.1.30-alpha.0";
2492
3700
  var CONNECT_OUTCOME_SCHEMA_VERSION = 1;
2493
3701
  async function runConnect(options, deps = {}) {
2494
3702
  assertSupportedNodeVersion(deps.nodeVersion, MCP_RUNTIME_MANIFEST.minimumNodeVersion);
@@ -2504,24 +3712,49 @@ async function runConnect(options, deps = {}) {
2504
3712
  const runRuntimeInstall = deps.installRuntime ?? installRuntime;
2505
3713
  const generateKey = deps.generateKey ?? generateDelegateKey;
2506
3714
  const generateLocalApiKey = deps.generateApiKey ?? generateAgentApiKey;
2507
- const installCapabilities = runtimeInstallCapabilities(options.runtime);
3715
+ const selection = await resolveRuntimeSelection(options.runtime, options.runtimeForce, {
3716
+ env: deps.env ?? process.env,
3717
+ selfReported: options.runtimeSelfReport,
3718
+ promptForRuntime: runtimeSelectionPrompt(options, deps)
3719
+ });
3720
+ if (!selection.runtime) {
3721
+ throw new ConnectError(
3722
+ "runtime_undetermined",
3723
+ `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. Nothing was written and the Haven setup token is still unused.`,
3724
+ "rerun_connect_with_explicit_runtime"
3725
+ );
3726
+ }
3727
+ const runtime = selection.runtime;
3728
+ const installCapabilities = runtimeInstallCapabilities(runtime);
2508
3729
  if (options.localMcp) {
2509
- const resolvedRuntime = normalizeRuntime(options.runtime);
2510
- if (!supportsLocalMcp(resolvedRuntime)) {
3730
+ if (!supportsLocalMcp(runtime)) {
2511
3731
  throw new Error(
2512
- `--local (fully-local Haven MCP) is only available for Claude Code and Codex. The detected runtime is ${runtimeProfile(resolvedRuntime).label}. Re-run without --local to use the default hosted MCP + local signer setup.`
3732
+ `--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.`
2513
3733
  );
2514
3734
  }
2515
3735
  }
3736
+ if (selection.overrodeHint) {
3737
+ log(`runtime: ${runtime} (detected; ignoring the ${selection.overrodeHint} hint \u2014 pass --runtime-force ${selection.overrodeHint} to override)`);
3738
+ }
3739
+ if (selection.discardedHint) {
3740
+ log(`runtime: ${runtime} (detected; "${selection.discardedHint}" is not a runtime Haven knows \u2014 valid values: ${RUNTIME_FLAG_VALUES})`);
3741
+ }
3742
+ if (selection.source === "prompted") {
3743
+ log(`runtime: ${runtime} (chosen at the prompt \u2014 nothing was detected in this environment)`);
3744
+ }
2516
3745
  log("Warming up your connection to Haven\u2026");
2517
3746
  const setup = await api.resolveSetup({
2518
3747
  setupToken: options.setupToken,
2519
3748
  connectorVersion,
2520
- runtime: options.runtime
3749
+ runtime
2521
3750
  });
2522
3751
  assertSetupChallengeIsUsable(setup.challenge.expires_at);
2523
3752
  printSetupSummary(setup, log);
2524
3753
  await preflightStorage({ baseDir: options.credentialsDir, warn: log });
3754
+ if (options.serverName) {
3755
+ assertValidServerSlug(options.serverName);
3756
+ await assertServerSlugAvailable(options.serverName, options.credentialsDir);
3757
+ }
2525
3758
  log("Checked local credential storage \u2014 all clear.");
2526
3759
  const localKey = generateKey();
2527
3760
  const localApiKey = generateLocalApiKey();
@@ -2533,12 +3766,17 @@ async function runConnect(options, deps = {}) {
2533
3766
  registration = await api.registerSetup({
2534
3767
  setupToken: options.setupToken,
2535
3768
  connectorVersion,
2536
- runtime: options.runtime,
3769
+ runtime,
2537
3770
  challengeId: setup.challenge.id,
2538
3771
  delegateAddress: localKey.address,
2539
3772
  proofSignature,
2540
3773
  apiKeyHash: hashAgentApiKey(localApiKey),
2541
3774
  apiKeyPrefix: agentApiKeyPrefix(localApiKey),
3775
+ // #1878: report the pair we are ACTUALLY wiring, bare pair included, so
3776
+ // the dashboard can name it. Derived here rather than sent as the raw
3777
+ // slug — `serverNamesFor` is the one place the naming rule lives, and
3778
+ // the hosted name is what a user pastes into an MCP config.
3779
+ mcpServerName: serverNamesFor(options.serverName).hosted,
2542
3780
  connectorContext: {
2543
3781
  environment_label: options.environmentLabel ?? "Local workspace",
2544
3782
  config_target: installCapabilities.canWriteRuntimeConfig ? "agent runtime MCP config" : "local credential files"
@@ -2558,6 +3796,7 @@ async function runConnect(options, deps = {}) {
2558
3796
  const credentialPaths = await writeCredentials({
2559
3797
  baseDir: options.credentialsDir,
2560
3798
  agentId: registration.agent_id,
3799
+ serverName: options.serverName,
2561
3800
  apiKey: localApiKey,
2562
3801
  delegateKey: localKey.privateKey,
2563
3802
  delegateAddress: localKey.address,
@@ -2585,7 +3824,7 @@ async function runConnect(options, deps = {}) {
2585
3824
  );
2586
3825
  }
2587
3826
  const runtimeInstall = await runRuntimeInstall({
2588
- runtime: options.runtime,
3827
+ runtime,
2589
3828
  hostedMcpUrl: registration.hosted_mcp_url,
2590
3829
  apiKey: localApiKey,
2591
3830
  signerPath: credentialPaths.signerPath,
@@ -2594,7 +3833,8 @@ async function runConnect(options, deps = {}) {
2594
3833
  environmentLabel: options.environmentLabel ?? "Local workspace",
2595
3834
  ackSigner: options.ackSigner,
2596
3835
  ackLocalTools: options.ackLocalTools,
2597
- localMcp: options.localMcp
3836
+ localMcp: options.localMcp,
3837
+ serverName: options.serverName
2598
3838
  }, {
2599
3839
  onProgress: log,
2600
3840
  // #1543: report "runtime configured" the moment the config write settles,
@@ -2630,6 +3870,19 @@ async function runConnect(options, deps = {}) {
2630
3870
  } else {
2631
3871
  log("Haven setup on this machine is complete.");
2632
3872
  }
3873
+ try {
3874
+ const supersededIds = await listOtherAgentIds(options.credentialsDir, credentialPaths.directory);
3875
+ if (supersededIds.length > 0) {
3876
+ log("");
3877
+ log(
3878
+ `Heads-up: this setup created a NEW agent. Your previous agent(s) \u2014 ${supersededIds.join(", ")} \u2014 still exist with their own keys, and any host that was already running keeps acting as them.`
3879
+ );
3880
+ log(
3881
+ `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.`
3882
+ );
3883
+ }
3884
+ } catch {
3885
+ }
2633
3886
  try {
2634
3887
  await api.updateInstallStatus(registration.setup_id, localApiKey, {
2635
3888
  runtime: runtimeInstall.runtime,
@@ -2704,11 +3957,16 @@ function completionOutcome(input) {
2704
3957
  };
2705
3958
  return outcome;
2706
3959
  }
3960
+ function runtimeSelectionPrompt(options, deps) {
3961
+ if (options.interactive !== true) return void 0;
3962
+ if (!(deps.isTty ?? Boolean(process.stdin.isTTY))) return void 0;
3963
+ return deps.promptRuntime ?? (() => resolveRuntimeByInstalledClientPrompt());
3964
+ }
2707
3965
  function failedConnectOutcome(runtimeHint, error) {
2708
3966
  const message = error instanceof Error ? error.message : "";
2709
- const 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";
3967
+ 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";
2710
3968
  const runtime = normalizeRuntime(runtimeHint);
2711
- const nextAction2 = 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";
3969
+ 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";
2712
3970
  return {
2713
3971
  schema_version: CONNECT_OUTCOME_SCHEMA_VERSION,
2714
3972
  outcome: "failed",
@@ -2794,7 +4052,7 @@ function describeApprovedBudget(budget) {
2794
4052
  async function waitForBudgetApproval(api, setupId, apiKey, log, options = {}) {
2795
4053
  const intervalMs = options.intervalMs ?? 5e3;
2796
4054
  const timeoutMs = options.timeoutMs ?? 18e4;
2797
- const sleep = options.sleep ?? ((ms) => new Promise((resolve8) => setTimeout(resolve8, ms)));
4055
+ const sleep = options.sleep ?? ((ms) => new Promise((resolve9) => setTimeout(resolve9, ms)));
2798
4056
  const maxPolls = Math.max(1, Math.floor(timeoutMs / intervalMs));
2799
4057
  const remindEvery = Math.max(1, Math.floor(3e4 / intervalMs));
2800
4058
  let waitingAnnounced = false;
@@ -2880,11 +4138,39 @@ function activationInstructionWithWhy(profile) {
2880
4138
  }
2881
4139
  return profile.activationInstruction;
2882
4140
  }
4141
+ var RERUN_HINT = "npx @haven_ai/connect@alpha";
4142
+ async function listOtherAgentIds(baseDir, currentDirectory) {
4143
+ const root = defaultCredentialRoot(baseDir);
4144
+ let entries = [];
4145
+ try {
4146
+ entries = await readdir(root);
4147
+ } catch {
4148
+ return [];
4149
+ }
4150
+ const ids = [];
4151
+ for (const entry of entries) {
4152
+ if (join(root, entry) === currentDirectory) continue;
4153
+ const identityPath = join(root, entry, "identity.json");
4154
+ try {
4155
+ await stat(identityPath);
4156
+ } catch {
4157
+ continue;
4158
+ }
4159
+ try {
4160
+ const identity = JSON.parse(await readFile(identityPath, "utf8"));
4161
+ ids.push(identity.agent_id ?? entry);
4162
+ } catch {
4163
+ ids.push(entry);
4164
+ }
4165
+ }
4166
+ return ids;
4167
+ }
2883
4168
  function printNextSteps(result, log, approval) {
2884
4169
  for (const line of completionHandoffLines(result, approval)) log(line);
2885
4170
  }
2886
4171
 
2887
4172
  // src/args.ts
4173
+ init_server_names();
2888
4174
  function parseArgs(argv, env = process.env) {
2889
4175
  const options = {
2890
4176
  apiBaseUrl: env.HAVEN_API_URL ?? "http://localhost:3001",
@@ -2894,6 +4180,11 @@ function parseArgs(argv, env = process.env) {
2894
4180
  let json = false;
2895
4181
  let doctor = false;
2896
4182
  let repair = false;
4183
+ let rekeyPhase;
4184
+ let newApiKey;
4185
+ let tombstoneDir;
4186
+ let tombstoneReason;
4187
+ let tombstoneReplacedBy;
2897
4188
  for (let i = 0; i < argv.length; i += 1) {
2898
4189
  const arg = argv[i];
2899
4190
  if (arg === "--help" || arg === "-h") {
@@ -2904,14 +4195,31 @@ function parseArgs(argv, env = process.env) {
2904
4195
  doctor = true;
2905
4196
  } else if (arg === "--repair") {
2906
4197
  repair = true;
4198
+ } else if (arg === "--rekey") {
4199
+ rekeyPhase = "start";
4200
+ } else if (arg === "--rekey-finish") {
4201
+ rekeyPhase = "finish";
4202
+ } else if (arg === "--api-key") {
4203
+ newApiKey = requireValue(argv, ++i, arg);
4204
+ } else if (arg === "--tombstone") {
4205
+ tombstoneDir = requireValue(argv, ++i, arg);
4206
+ } else if (arg === "--reason") {
4207
+ tombstoneReason = requireValue(argv, ++i, arg);
4208
+ } else if (arg === "--replaced-by") {
4209
+ tombstoneReplacedBy = requireValue(argv, ++i, arg);
2907
4210
  } else if (arg === "--setup" || arg === "--setup-token") {
2908
4211
  options.setupToken = requireValue(argv, ++i, arg);
2909
4212
  } else if (arg === "--api" || arg === "--api-url") {
2910
4213
  options.apiBaseUrl = requireValue(argv, ++i, arg);
2911
4214
  } else if (arg === "--runtime") {
2912
4215
  options.runtime = requireValue(argv, ++i, arg);
4216
+ } else if (arg === "--runtime-force") {
4217
+ options.runtimeForce = requireValue(argv, ++i, arg);
2913
4218
  } else if (arg === "--credentials-dir") {
2914
4219
  options.credentialsDir = requireValue(argv, ++i, arg);
4220
+ } else if (arg === "--name") {
4221
+ options.serverName = requireValue(argv, ++i, arg);
4222
+ assertValidServerSlug(options.serverName);
2915
4223
  } else if (arg === "--environment-label") {
2916
4224
  options.environmentLabel = requireValue(argv, ++i, arg);
2917
4225
  } else if (arg === "--ack-local-tools") {
@@ -2929,14 +4237,39 @@ function parseArgs(argv, env = process.env) {
2929
4237
  throw new Error(`Unknown option: ${arg}`);
2930
4238
  }
2931
4239
  }
4240
+ const tombstone = tombstoneDir ? { directory: tombstoneDir, reason: tombstoneReason, replacedBy: tombstoneReplacedBy } : void 0;
4241
+ const rekey = rekeyPhase ? { phase: rekeyPhase, newApiKey } : void 0;
2932
4242
  if (help) {
2933
- return { options, help, json, doctor, repair };
4243
+ return { options, help, json, doctor, repair, tombstone, rekey };
4244
+ }
4245
+ if (rekey) {
4246
+ if (options.setupToken) {
4247
+ throw new Error("--rekey replaces an existing agent's key; it does not take --setup. Drop one of them.");
4248
+ }
4249
+ if (rekey.phase === "start" && newApiKey !== void 0) {
4250
+ throw new Error(
4251
+ "--api-key belongs to --rekey-finish. --rekey generates the new key here and prints the address to paste into Haven; the API key does not exist yet."
4252
+ );
4253
+ }
4254
+ if (rekey.phase === "finish" && !newApiKey) {
4255
+ throw new Error("--rekey-finish needs --api-key <key> \u2014 the one the Haven agent page showed once.");
4256
+ }
4257
+ return { options, help, json, doctor, repair, tombstone, rekey };
4258
+ }
4259
+ if (newApiKey !== void 0) {
4260
+ throw new Error("--api-key requires --rekey-finish.");
4261
+ }
4262
+ if (!tombstoneDir && (tombstoneReason !== void 0 || tombstoneReplacedBy !== void 0)) {
4263
+ throw new Error("--reason and --replaced-by require --tombstone <dir>.");
4264
+ }
4265
+ if (tombstone) {
4266
+ return { options, help, json, doctor, repair, tombstone, rekey };
2934
4267
  }
2935
4268
  if (doctor || repair) {
2936
4269
  if (!options.runtime) {
2937
4270
  throw new Error("--doctor/--repair need --runtime <runtime> (which config to examine).");
2938
4271
  }
2939
- return { options, help, json, doctor, repair };
4272
+ return { options, help, json, doctor, repair, tombstone, rekey };
2940
4273
  }
2941
4274
  if (!options.setupToken) {
2942
4275
  throw new Error("Missing --setup <hv_setup_...> setup token.");
@@ -2945,7 +4278,7 @@ function parseArgs(argv, env = process.env) {
2945
4278
  throw new Error("Missing --api <Haven API URL>.");
2946
4279
  }
2947
4280
  options.apiBaseUrl = options.apiBaseUrl.replace(/\/+$/, "");
2948
- return { options, help, json, doctor, repair };
4281
+ return { options, help, json, doctor, repair, tombstone, rekey };
2949
4282
  }
2950
4283
  function helpText() {
2951
4284
  return [
@@ -2955,14 +4288,23 @@ function helpText() {
2955
4288
  "sends Haven only the public signing address plus a proof signature.",
2956
4289
  "",
2957
4290
  "Usage:",
2958
- " npx -y @haven_ai/connect --setup hv_setup_... --api https://api.haven.example --ack-local-tools --runtime claude-code",
4291
+ " npx -y @haven_ai/connect --setup hv_setup_... --api https://api.haven.example --ack-local-tools",
2959
4292
  "",
2960
4293
  "Options:",
2961
4294
  " --setup <token> Short-lived setup token from Haven.",
2962
4295
  " --api <url> Haven backend API URL. Defaults to HAVEN_API_URL or http://localhost:3001.",
2963
4296
  " --runtime <name> Agent runtime hint, such as claude-code, codex-cli, codex-desktop, cursor, vscode, claude-desktop, or hermes.",
4297
+ " Usually unnecessary: the connector detects the runtime it runs inside, and a detection",
4298
+ " that contradicts this hint wins (with a printed notice). When nothing is detected, an",
4299
+ " interactive terminal is offered the agent clients installed on this machine; this flag is",
4300
+ " how an agent, or a non-interactive run, answers instead. An unknown name is refused, never guessed.",
4301
+ " --runtime-force <name> Escape hatch: use exactly this runtime, ignoring environment detection.",
2964
4302
  " --credentials-dir <path> Credential directory fallback. Defaults to ~/.haven/agents.",
2965
4303
  " --environment-label <text> Non-sensitive label shown in Haven setup review.",
4304
+ " --name <slug> Wiring slug for a NAMED agent: writes haven-<slug> / haven-signer-<slug>",
4305
+ " MCP entries and stores credentials at ~/.haven/agents/<slug>/, so several",
4306
+ " agents can run side by side in one runtime. 1-32 lowercase letters, digits,",
4307
+ " single hyphens; immutable once wired. Omit for the bare haven / haven-signer pair.",
2966
4308
  " --ack-local-tools Write the one-time local Haven tools acknowledgement during setup.",
2967
4309
  " --ack-signer Backward-compatible alias for --ack-local-tools.",
2968
4310
  " --local Advanced: install the fully-local Haven MCP (no hosted dependency).",
@@ -2973,6 +4315,19 @@ function helpText() {
2973
4315
  " --repair Repair, then re-diagnose (implies --doctor): reinstall the pinned signer",
2974
4316
  " runtime, rewrite the wrapper and runtime config from stored credentials.",
2975
4317
  " Hosted topology only (refuses to touch a --local config). No keys, no token.",
4318
+ " --rekey Replace this agent's signing key (no token). Generates a fresh keypair HERE and",
4319
+ " prints its public address to paste into the Haven agent page. Nothing changes",
4320
+ " until you finish; the agent keeps working on its old key throughout.",
4321
+ " Add --name <slug> for a named agent. Refuses a legacy-rail or revoked agent.",
4322
+ " --rekey-finish Second half of --rekey: writes the new key and the API key the agent page",
4323
+ " showed once, in place at the same path, and rewrites only this agent's MCP",
4324
+ " config pair. Server names do not change, so wired hosts need only a restart.",
4325
+ " --api-key <key> The new API key, for --rekey-finish.",
4326
+ " --tombstone <dir> Retire an agent credential directory in place (no token): replaces its signer",
4327
+ " wrapper with a diagnostic that names the retirement in MCP stderr logs, and",
4328
+ " writes TOMBSTONE.json. Touches NO key material and revokes nothing.",
4329
+ " --reason <text> Reason recorded in the tombstone (with --tombstone).",
4330
+ " --replaced-by <agent-id> Successor agent recorded in the tombstone (with --tombstone).",
2976
4331
  " --help Show this help.",
2977
4332
  "",
2978
4333
  "The connector never prints the private key and never sends it to Haven. JSON output never includes credential contents or full credential paths."
@@ -2987,6 +4342,7 @@ function requireValue(argv, index, option) {
2987
4342
  }
2988
4343
 
2989
4344
  // src/cli.ts
4345
+ init_redact();
2990
4346
  async function runCli(argv, io = {
2991
4347
  stdout: (message) => process.stdout.write(message),
2992
4348
  stderr: (message) => process.stderr.write(message)
@@ -3010,6 +4366,103 @@ async function runCli(argv, io = {
3010
4366
  `);
3011
4367
  return 0;
3012
4368
  }
4369
+ if (parsed.tombstone) {
4370
+ const { writeAgentTombstone: writeAgentTombstone2 } = await Promise.resolve().then(() => (init_tombstone(), tombstone_exports));
4371
+ const { readFile: readFile12 } = await import('fs/promises');
4372
+ const { join: join10 } = await import('path');
4373
+ try {
4374
+ let agentId = "unknown";
4375
+ try {
4376
+ const identity = JSON.parse(
4377
+ await readFile12(join10(parsed.tombstone.directory, "identity.json"), "utf8")
4378
+ );
4379
+ agentId = identity.agent_id ?? "unknown";
4380
+ } catch {
4381
+ }
4382
+ const info = await writeAgentTombstone2({
4383
+ directory: parsed.tombstone.directory,
4384
+ agentId,
4385
+ reason: parsed.tombstone.reason ?? "retired by operator via --tombstone",
4386
+ replacedBy: parsed.tombstone.replacedBy
4387
+ });
4388
+ if (parsed.json) {
4389
+ io.stdout(`${redactSecrets(JSON.stringify({ tombstoned: true, ...info }))}
4390
+ `);
4391
+ } else {
4392
+ io.stdout(redactSecrets(`Tombstoned agent ${info.agent_id} at ${parsed.tombstone.directory}.
4393
+ `));
4394
+ io.stdout(
4395
+ "Key files were NOT touched and nothing was revoked \u2014 revoke the agent on the Haven agent page if you have not already.\n"
4396
+ );
4397
+ io.stdout(
4398
+ "Restart EVERY long-lived MCP host (gateway, TUI workers, editors): each holds the wiring snapshot from its own start time, and the tombstone only speaks when a stale host next probes the old path.\n"
4399
+ );
4400
+ }
4401
+ return 0;
4402
+ } catch (err) {
4403
+ io.stderr(`${redactSecrets(err instanceof Error ? err.message : String(err))}
4404
+ `);
4405
+ return 1;
4406
+ }
4407
+ }
4408
+ if (parsed.rekey) {
4409
+ const { startRekey: startRekey2, finishRekey: finishRekey2 } = await Promise.resolve().then(() => (init_rekey(), rekey_exports));
4410
+ const { restartGuidance: restartGuidance2 } = await Promise.resolve().then(() => (init_rekey_restart(), rekey_restart_exports));
4411
+ const common = {
4412
+ serverName: parsed.options.serverName,
4413
+ credentialsDir: parsed.options.credentialsDir,
4414
+ runtime: parsed.options.runtime
4415
+ };
4416
+ try {
4417
+ if (parsed.rekey.phase === "start") {
4418
+ const result2 = await startRekey2(common);
4419
+ if (parsed.json) {
4420
+ io.stdout(
4421
+ `${redactSecrets(
4422
+ JSON.stringify({
4423
+ rekey: "started",
4424
+ agent_id: result2.agentId,
4425
+ new_delegate_address: result2.newDelegateAddress,
4426
+ expires_at: result2.expiresAt
4427
+ })
4428
+ )}
4429
+ `
4430
+ );
4431
+ } else {
4432
+ for (const line of result2.messages) io.stdout(redactSecrets(`${line}
4433
+ `));
4434
+ }
4435
+ return 0;
4436
+ }
4437
+ const result = await finishRekey2({ ...common, newApiKey: parsed.rekey.newApiKey });
4438
+ const restart = restartGuidance2(parsed.options.runtime);
4439
+ if (parsed.json) {
4440
+ io.stdout(
4441
+ `${redactSecrets(
4442
+ JSON.stringify({
4443
+ rekey: "finished",
4444
+ agent_id: result.agentId,
4445
+ new_delegate_address: result.newDelegateAddress,
4446
+ mcp_servers: result.serverNames,
4447
+ restart_commands: restart.commands
4448
+ })
4449
+ )}
4450
+ `
4451
+ );
4452
+ } else {
4453
+ for (const line of result.messages) io.stdout(redactSecrets(`${line}
4454
+ `));
4455
+ io.stdout("\n");
4456
+ for (const line of restart.lines) io.stdout(redactSecrets(`${line}
4457
+ `));
4458
+ }
4459
+ return 0;
4460
+ } catch (err) {
4461
+ io.stderr(`${redactSecrets(err instanceof Error ? err.message : String(err))}
4462
+ `);
4463
+ return 1;
4464
+ }
4465
+ }
3013
4466
  if (parsed.doctor || parsed.repair) {
3014
4467
  const { runDoctor: runDoctor2, runRepair: runRepair2 } = await Promise.resolve().then(() => (init_doctor(), doctor_exports));
3015
4468
  const runtime = parsed.options.runtime ?? "";
@@ -3032,6 +4485,23 @@ async function runCli(argv, io = {
3032
4485
  if (check.repair) io.stdout(redactSecrets(` \u21B3 repair: ${check.repair}
3033
4486
  `));
3034
4487
  }
4488
+ const otherAgents = report.agents.filter((agent) => agent.directory !== report.credentialDirectory);
4489
+ if (otherAgents.length > 0) {
4490
+ io.stdout("\nOther agents on this machine:\n");
4491
+ for (const agent of otherAgents) {
4492
+ const name = agent.slug ? `${agent.slug} (${agent.agentId ?? "unknown"})` : agent.agentId ?? "unknown";
4493
+ const failed = agent.checks.filter((check) => !check.ok);
4494
+ const verdict = agent.classification === "wired" ? failed.length === 0 ? "wired, all checks passed" : `wired, ${failed.length} check(s) FAILED` : agent.classification === "parked" ? "parked re-key only \u2014 no identity.json in this directory, but key material is still there" : agent.classification;
4495
+ io.stdout(redactSecrets(` ${failed.length > 0 ? "\u2717" : "\u2022"} ${name}: ${verdict}
4496
+ `));
4497
+ for (const check of failed) {
4498
+ io.stdout(redactSecrets(` \u2717 ${check.label}: ${check.detail}
4499
+ `));
4500
+ if (check.repair) io.stdout(redactSecrets(` \u21B3 repair: ${check.repair}
4501
+ `));
4502
+ }
4503
+ }
4504
+ }
3035
4505
  io.stdout(report.ok ? "All checks passed.\n" : "One or more checks FAILED \u2014 see repairs above.\n");
3036
4506
  }
3037
4507
  return report.ok ? 0 : 1;
@@ -3043,7 +4513,15 @@ async function runCli(argv, io = {
3043
4513
  }
3044
4514
  try {
3045
4515
  const result = await runConnect(
3046
- { ...parsed.options, waitForApproval: !parsed.json },
4516
+ {
4517
+ ...parsed.options,
4518
+ waitForApproval: !parsed.json,
4519
+ // #1719: only a human-facing run may be asked which installed client to
4520
+ // configure. --json is the automation contract — it must fail with a
4521
+ // machine-readable code, never block on stdin. runConnect additionally
4522
+ // requires a real TTY before it prompts.
4523
+ interactive: !parsed.json
4524
+ },
3047
4525
  {
3048
4526
  log: (message) => (parsed.json ? io.stderr : io.stdout)(`${message}
3049
4527
  `),