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