@haven_ai/connect 0.1.29-alpha.0 → 0.1.31-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,19 @@
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
17
  var readline = require('readline');
18
18
 
19
19
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
@@ -31,10 +31,132 @@ var __export = (target, all) => {
31
31
  __defProp(target, name, { get: all[name], enumerable: true });
32
32
  };
33
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
+ };
98
+ }
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;
114
+ }
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;
125
+ };
126
+ }
127
+ });
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"() {
150
+ }
151
+ });
152
+
34
153
  // src/redact.ts
35
154
  function redactSecrets(value) {
36
155
  return value.replace(API_KEY_RE, "sk_agent_[redacted]").replace(PRIVATE_KEY_RE, "0x[redacted-private-key]");
37
156
  }
157
+ function redactForAutomation(value) {
158
+ return redactSecrets(value).replace(/(?:~|\/)[^\s`"']*\/(?:identity|signer|agent)\.json\b/g, "[credential-file-redacted]").replace(/(?:~|\/)[^\s`"']*\/\.env\b/g, "[credential-env-redacted]");
159
+ }
38
160
  function shortAddress(address) {
39
161
  if (!/^0x[0-9a-fA-F]{40}$/.test(address)) return address;
40
162
  return `${address.slice(0, 6)}...${address.slice(-4)}`;
@@ -93,115 +215,411 @@ var init_server_names = __esm({
93
215
  SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
94
216
  }
95
217
  });
96
- function mcpPackageSpec() {
97
- return `${MCP_RUNTIME_MANIFEST.mcpPackage}@${MCP_RUNTIME_MANIFEST.mcpVersion}`;
98
- }
99
- function sdkPackageSpec() {
100
- return `${MCP_RUNTIME_MANIFEST.sdkPackage}@${MCP_RUNTIME_MANIFEST.sdkVersion}`;
101
- }
102
- function signerPackageSpec() {
103
- return `${MCP_RUNTIME_MANIFEST.signerPackage}@${MCP_RUNTIME_MANIFEST.signerVersion}`;
218
+ async function preflightCredentialStorage(input = {}) {
219
+ const directory = defaultCredentialRoot(input.baseDir);
220
+ await promises.mkdir(directory, { recursive: true, mode: 448 });
221
+ await restrictPermissions(directory, 448, input.warn);
222
+ const probePath = path.join(directory, `.haven-connect-preflight-${crypto__default.default.randomBytes(8).toString("hex")}`);
223
+ try {
224
+ await writeOwnerOnlyJson(probePath, { ok: true }, input.warn);
225
+ } finally {
226
+ await promises.rm(probePath, { force: true }).catch(() => void 0);
227
+ }
228
+ return directory;
104
229
  }
105
- var MCP_RUNTIME_MANIFEST;
106
- var init_runtime_manifest = __esm({
107
- "src/runtime-manifest.ts"() {
108
- MCP_RUNTIME_MANIFEST = {
109
- mcpPackage: "@haven_ai/mcp",
110
- mcpVersion: mcp.MCP_VERSION,
111
- sdkPackage: "@haven_ai/sdk",
112
- sdkVersion: "0.1.29-alpha.0",
113
- signerPackage: "@haven_ai/signer",
114
- signerVersion: "0.1.29-alpha.0",
115
- // Sourced from the SDK, never a literal (#1161). This field read '20.0.0'
116
- // while every package's `engines` said `>=24` and the docs said `>=24.0.0`,
117
- // so the guard that was supposed to enforce the floor waved Node v23 through
118
- // — including on the `--local` path where it does run. A hand-maintained
119
- // second copy of a number is a drift waiting to happen; a guard test pins
120
- // this against `package.json`'s `engines.node`.
121
- minimumNodeVersion: sdk.HAVEN_MINIMUM_NODE_VERSION,
122
- supportedClients: ["codex-cli", "codex-desktop", "claude-code"],
123
- requiredTools: mcp.registeredToolNames(),
124
- /**
125
- * The signer MCP's tool surface, DERIVED from the pinned @haven_ai/signer
126
- * package (#1587) — same anti-drift rule as `requiredTools` above: a
127
- * literal list here would rot the first time the signer gains a tool.
128
- * The handshake probe requires all of them.
129
- */
130
- requiredSignerTools: Object.keys(signer.toolSchemas)
131
- };
230
+ async function writeCredentialFiles(input) {
231
+ const directory = defaultAgentDirectory(input.serverName ?? input.agentId, input.baseDir);
232
+ await promises.mkdir(directory, { recursive: true, mode: 448 });
233
+ await restrictPermissions(directory, 448, input.warn);
234
+ const identityPath = path.join(directory, "identity.json");
235
+ const signerPath = path.join(directory, "signer.json");
236
+ const agentPath = path.join(directory, "agent.json");
237
+ await assertDoesNotExist(identityPath);
238
+ await assertDoesNotExist(signerPath);
239
+ await assertDoesNotExist(agentPath);
240
+ await writeOwnerOnlyJson(signerPath, signerPayload(input), input.warn);
241
+ try {
242
+ await writeOwnerOnlyJson(identityPath, identityPayload(input), input.warn);
243
+ } catch (err) {
244
+ await promises.rm(signerPath, { force: true }).catch(() => void 0);
245
+ throw err;
132
246
  }
133
- });
134
- async function writeRuntimeConfig(input, deps = {}) {
135
- switch (input.runtime) {
136
- case "codex-cli":
137
- case "codex-desktop":
138
- return writeCodexConfig(input);
139
- case "cursor":
140
- return writeJsonRuntimeConfig(input, cursorConfigPath(input.homeDir), "mcpServers");
141
- case "vscode":
142
- return writeJsonRuntimeConfig(input, vscodeConfigPath(input.homeDir), "servers");
143
- case "vscode-insiders":
144
- return writeJsonRuntimeConfig(input, vscodeInsidersConfigPath(input.homeDir), "servers");
145
- case "claude-desktop":
146
- return writeJsonRuntimeConfig(input, claudeDesktopConfigPath(input.homeDir), "mcpServers");
147
- case "hermes":
148
- return writeHermesConfig(input, deps);
149
- default:
150
- return {
151
- hostedConfigured: false,
152
- signerConfigured: false,
153
- localMcpConfigured: false,
154
- runtimeMcpMode: "manual",
155
- target: "manual runtime setup",
156
- changed: false,
157
- restartRequired: true,
158
- messages: ["Runtime config needs to be added manually for this agent environment."],
159
- errorCode: "manual_runtime_setup_required"
160
- };
247
+ try {
248
+ await writeOwnerOnlyJson(agentPath, agentPayload(input), input.warn);
249
+ } catch (err) {
250
+ await promises.rm(signerPath, { force: true }).catch(() => void 0);
251
+ await promises.rm(identityPath, { force: true }).catch(() => void 0);
252
+ await promises.rm(agentPath, { force: true }).catch(() => void 0);
253
+ throw err;
161
254
  }
255
+ return { directory, identityPath, signerPath, agentPath };
162
256
  }
163
- function buildHostedServer(hostedMcpUrl, apiKey, runtime) {
164
- if (runtime === "vscode" || runtime === "vscode-insiders") {
165
- return {
166
- type: "http",
167
- url: hostedMcpUrl,
168
- headers: { Authorization: `Bearer ${apiKey}` }
169
- };
170
- }
257
+ function signerPayload(input) {
171
258
  return {
172
- url: hostedMcpUrl,
173
- headers: { Authorization: `Bearer ${apiKey}` }
259
+ delegate_key: input.delegateKey,
260
+ delegate_address: input.delegateAddress,
261
+ agent_id: input.agentId,
262
+ safe_address: input.safeAddress,
263
+ chain_id: input.chainId,
264
+ network: input.network,
265
+ x402_binding_signer: input.x402BindingSigner,
266
+ note: "Local signer credential. Haven backend never receives this private key."
174
267
  };
175
268
  }
176
- function resolveSignerLaunchSpec(input) {
177
- return input.signerCommand ?? {
178
- command: "npx",
179
- args: ["-y", signerPackageSpec(), "--credentials", input.signerPath]
269
+ function identityPayload(input) {
270
+ return {
271
+ api_key: input.apiKey,
272
+ agent_id: input.agentId,
273
+ safe_address: input.safeAddress,
274
+ chain_id: input.chainId,
275
+ network: input.network,
276
+ api_url: input.apiUrl,
277
+ hosted_mcp_url: input.hostedMcpUrl,
278
+ agent_budget: input.agentBudget,
279
+ note: "Haven API key identifies the agent only. It cannot spend without the local signer key and on-chain Haven wallet rules."
180
280
  };
181
281
  }
182
- function buildSignerServer(spec, runtime) {
183
- const server = {
184
- command: spec.command,
185
- args: spec.args
282
+ function agentPayload(input) {
283
+ return {
284
+ agent_id: input.agentId,
285
+ delegate_address: input.delegateAddress,
286
+ safe_address: input.safeAddress,
287
+ chain_id: input.chainId,
288
+ network: input.network,
289
+ agent_budget: input.agentBudget,
290
+ 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."
186
291
  };
187
- if (runtime === "vscode" || runtime === "vscode-insiders") return { type: "stdio", ...server };
188
- return server;
189
292
  }
190
- function mergeJsonMcpConfig(existingJson, serverRoot, hostedServer, signerServer, names = serverNamesFor(), configPath) {
191
- const config = existingJson?.trim() ? parseJsonObject(existingJson, configPath) : {};
192
- const existingRoot = config[serverRoot];
193
- const servers = existingRoot && typeof existingRoot === "object" && !Array.isArray(existingRoot) ? existingRoot : {};
194
- config[serverRoot] = {
195
- ...servers,
196
- [names.hosted]: hostedServer,
197
- [names.signer]: signerServer
293
+ async function readStoredCredentials(serverName, agentIdOrSlug, baseDir) {
294
+ const key = serverName ?? agentIdOrSlug;
295
+ const directory = key ? defaultAgentDirectory(key, baseDir) : await discoverSoleAgentDirectory(baseDir);
296
+ const identity = await readJsonFile(path.join(directory, "identity.json"));
297
+ if (!identity) {
298
+ throw new Error(
299
+ `No Haven credentials at ${directory}. Nothing to re-key \u2014 connect this agent first, or pass the --name you wired it under.`
300
+ );
301
+ }
302
+ const agent = await readJsonFile(path.join(directory, "agent.json")) ?? {};
303
+ const signer = await readJsonFile(path.join(directory, "signer.json")) ?? {};
304
+ const agentId = asString(identity.agent_id);
305
+ const apiKey = asString(identity.api_key);
306
+ const apiUrl = asString(identity.api_url);
307
+ const hostedMcpUrl = asString(identity.hosted_mcp_url);
308
+ if (!agentId || !apiKey || !apiUrl || !hostedMcpUrl) {
309
+ throw new Error(
310
+ `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.`
311
+ );
312
+ }
313
+ return {
314
+ directory,
315
+ agentId,
316
+ apiKey,
317
+ apiUrl,
318
+ hostedMcpUrl,
319
+ delegateAddress: asString(agent.delegate_address) ?? asString(signer.delegate_address),
320
+ safeAddress: asString(identity.safe_address) ?? asString(agent.safe_address),
321
+ chainId: typeof identity.chain_id === "number" ? identity.chain_id : void 0,
322
+ network: asString(identity.network),
323
+ x402BindingSigner: asString(signer.x402_binding_signer),
324
+ agentBudget: Array.isArray(identity.agent_budget) ? identity.agent_budget : void 0
198
325
  };
199
- return `${JSON.stringify(config, null, 2)}
200
- `;
201
326
  }
202
- function mergeHermesYaml(existingYaml, hostedServer, signerServer, names = serverNamesFor(), configPath) {
203
- if (!existingYaml?.trim()) {
204
- return renderHermesYaml({ [names.hosted]: hostedServer, [names.signer]: signerServer });
327
+ async function discoverSoleAgentDirectory(baseDir) {
328
+ const root = defaultCredentialRoot(baseDir);
329
+ let entries = [];
330
+ try {
331
+ entries = await promises.readdir(root);
332
+ } catch {
333
+ throw new Error(`No Haven credentials found under ${root}. Connect an agent on this machine first.`);
334
+ }
335
+ const candidates = [];
336
+ for (const entry of entries) {
337
+ const directory = path.join(root, entry);
338
+ if (!await readJsonFile(path.join(directory, "identity.json"))) continue;
339
+ if (await readJsonFile(path.join(directory, "TOMBSTONE.json"))) continue;
340
+ candidates.push(directory);
341
+ }
342
+ if (candidates.length === 1) return candidates[0];
343
+ if (candidates.length === 0) {
344
+ throw new Error(`No Haven credentials found under ${root}. Connect an agent on this machine first.`);
345
+ }
346
+ throw new Error(
347
+ `Several agents are wired on this machine, so --rekey cannot tell which one you mean:
348
+ ` + candidates.map((d) => ` ${d}`).join("\n") + "\nRe-run with --name <slug> to pick one."
349
+ );
350
+ }
351
+ async function rewriteCredentialFiles(input) {
352
+ const directory = defaultAgentDirectory(input.serverName ?? input.agentId, input.baseDir);
353
+ const identityPath = path.join(directory, "identity.json");
354
+ const signerPath = path.join(directory, "signer.json");
355
+ const agentPath = path.join(directory, "agent.json");
356
+ const targets = [
357
+ { path: signerPath, payload: signerPayload(input) },
358
+ { path: identityPath, payload: identityPayload(input) },
359
+ { path: agentPath, payload: agentPayload(input) }
360
+ ];
361
+ const originals = /* @__PURE__ */ new Map();
362
+ for (const { path } of targets) {
363
+ originals.set(path, await readRawFile(path));
364
+ }
365
+ const temps = [];
366
+ try {
367
+ for (const { path, payload } of targets) {
368
+ const temp = `${path}.rekey-${crypto__default.default.randomBytes(6).toString("hex")}.tmp`;
369
+ await writeOwnerOnlyJson(temp, payload, input.warn);
370
+ temps.push({ from: temp, to: path });
371
+ }
372
+ for (const { from, to } of temps) {
373
+ await promises.rename(from, to);
374
+ }
375
+ } catch (err) {
376
+ for (const { from } of temps) await promises.rm(from, { force: true }).catch(() => void 0);
377
+ for (const [path, contents] of originals) {
378
+ if (contents === null) {
379
+ await promises.rm(path, { force: true }).catch(() => void 0);
380
+ } else {
381
+ await promises.writeFile(path, contents, { mode: 384 }).catch(() => void 0);
382
+ }
383
+ }
384
+ throw err;
385
+ }
386
+ return { directory, identityPath, signerPath, agentPath };
387
+ }
388
+ async function writeRekeyPending(directory, pending, warn) {
389
+ const path$1 = path.join(directory, REKEY_PENDING_FILENAME);
390
+ await promises.rm(path$1, { force: true }).catch(() => void 0);
391
+ await writeOwnerOnlyJson(path$1, { ...pending }, warn);
392
+ return path$1;
393
+ }
394
+ async function readRekeyPending(directory, now = Date.now()) {
395
+ const path$1 = path.join(directory, REKEY_PENDING_FILENAME);
396
+ const raw = await readJsonFile(path$1);
397
+ if (!raw) {
398
+ throw new Error(
399
+ `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.`
400
+ );
401
+ }
402
+ const pending = raw;
403
+ if (!pending.new_delegate_key || !pending.new_delegate_address || !pending.agent_id) {
404
+ throw new Error(`The pending re-key at ${path$1} is unreadable. Delete it and start again with --rekey.`);
405
+ }
406
+ if (pending.expires_at && Date.parse(pending.expires_at) < now) {
407
+ throw new Error(
408
+ `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.`
409
+ );
410
+ }
411
+ return pending;
412
+ }
413
+ async function inspectRekeyPending(directory, now = Date.now()) {
414
+ const path$1 = path.join(directory, REKEY_PENDING_FILENAME);
415
+ const raw = await readJsonFile(path$1);
416
+ if (!raw) {
417
+ const present = await readRawFile(path$1) !== null;
418
+ return present ? { state: "unreadable", path: path$1 } : null;
419
+ }
420
+ const agentId = asString(raw.agent_id);
421
+ const newDelegateAddress = asString(raw.new_delegate_address);
422
+ const startedAt = asString(raw.started_at);
423
+ const expiresAt = asString(raw.expires_at);
424
+ if (!agentId || !newDelegateAddress) {
425
+ return { state: "unreadable", path: path$1, ...startedAt ? { startedAt } : {} };
426
+ }
427
+ const expired = expiresAt !== void 0 && Date.parse(expiresAt) < now;
428
+ return {
429
+ state: expired ? "expired" : "pending",
430
+ path: path$1,
431
+ agentId,
432
+ newDelegateAddress,
433
+ ...startedAt ? { startedAt } : {},
434
+ ...expiresAt ? { expiresAt } : {}
435
+ };
436
+ }
437
+ async function clearRekeyPending(directory) {
438
+ await promises.rm(path.join(directory, REKEY_PENDING_FILENAME), { force: true }).catch(() => void 0);
439
+ }
440
+ async function readJsonFile(path) {
441
+ const raw = await readRawFile(path);
442
+ if (raw === null) return null;
443
+ try {
444
+ const parsed = JSON.parse(raw);
445
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
446
+ } catch {
447
+ return null;
448
+ }
449
+ }
450
+ async function readRawFile(path) {
451
+ try {
452
+ return await promises.readFile(path, "utf8");
453
+ } catch {
454
+ return null;
455
+ }
456
+ }
457
+ function asString(value) {
458
+ return typeof value === "string" && value.length > 0 ? value : void 0;
459
+ }
460
+ async function assertServerSlugAvailable(serverName, baseDir) {
461
+ const directory = defaultAgentDirectory(serverName, baseDir);
462
+ try {
463
+ await promises.stat(path.join(directory, "identity.json"));
464
+ } catch {
465
+ return;
466
+ }
467
+ throw new Error(
468
+ `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.`
469
+ );
470
+ }
471
+ function defaultAgentDirectory(agentId, baseDir = path.join(os.homedir(), ".haven", "agents")) {
472
+ return path.resolve(defaultCredentialRoot(baseDir), safePathPart(agentId));
473
+ }
474
+ function defaultCredentialRoot(baseDir = path.join(os.homedir(), ".haven", "agents")) {
475
+ return path.resolve(baseDir);
476
+ }
477
+ async function writeOwnerOnlyJson(path, value, warn) {
478
+ const json = JSON.stringify(dropUndefined(value), null, 2);
479
+ await promises.writeFile(path, `${json}
480
+ `, { mode: 384, flag: "wx" });
481
+ await restrictPermissions(path, 384, warn);
482
+ }
483
+ function safePathPart(value) {
484
+ return value.replace(/[^A-Za-z0-9_.-]/g, "_");
485
+ }
486
+ function dropUndefined(value) {
487
+ return Object.fromEntries(Object.entries(value).filter(([, field]) => field !== void 0));
488
+ }
489
+ async function assertDoesNotExist(path) {
490
+ try {
491
+ await promises.access(path);
492
+ } catch (err) {
493
+ if (err && typeof err === "object" && "code" in err && err.code === "ENOENT") return;
494
+ throw err;
495
+ }
496
+ throw new Error(`Refusing to overwrite existing Haven credential file: ${path}`);
497
+ }
498
+ async function restrictPermissions(path, mode, warn) {
499
+ try {
500
+ await promises.chmod(path, mode);
501
+ } catch (err) {
502
+ warn?.(
503
+ `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)}`
504
+ );
505
+ }
506
+ }
507
+ var REKEY_PENDING_FILENAME, REKEY_PENDING_TTL_MS;
508
+ var init_storage = __esm({
509
+ "src/storage.ts"() {
510
+ REKEY_PENDING_FILENAME = "rekey-pending.json";
511
+ REKEY_PENDING_TTL_MS = 24 * 60 * 60 * 1e3;
512
+ }
513
+ });
514
+ function mcpPackageSpec() {
515
+ return `${MCP_RUNTIME_MANIFEST.mcpPackage}@${MCP_RUNTIME_MANIFEST.mcpVersion}`;
516
+ }
517
+ function sdkPackageSpec() {
518
+ return `${MCP_RUNTIME_MANIFEST.sdkPackage}@${MCP_RUNTIME_MANIFEST.sdkVersion}`;
519
+ }
520
+ function signerPackageSpec() {
521
+ return `${MCP_RUNTIME_MANIFEST.signerPackage}@${MCP_RUNTIME_MANIFEST.signerVersion}`;
522
+ }
523
+ var MCP_RUNTIME_MANIFEST;
524
+ var init_runtime_manifest = __esm({
525
+ "src/runtime-manifest.ts"() {
526
+ MCP_RUNTIME_MANIFEST = {
527
+ mcpPackage: "@haven_ai/mcp",
528
+ mcpVersion: mcp.MCP_VERSION,
529
+ sdkPackage: "@haven_ai/sdk",
530
+ sdkVersion: "0.1.31-alpha.0",
531
+ signerPackage: "@haven_ai/signer",
532
+ signerVersion: "0.1.31-alpha.0",
533
+ // Sourced from the SDK, never a literal (#1161). This field read '20.0.0'
534
+ // while every package's `engines` said `>=24` and the docs said `>=24.0.0`,
535
+ // so the guard that was supposed to enforce the floor waved Node v23 through
536
+ // — including on the `--local` path where it does run. A hand-maintained
537
+ // second copy of a number is a drift waiting to happen; a guard test pins
538
+ // this against `package.json`'s `engines.node`.
539
+ minimumNodeVersion: sdk.HAVEN_MINIMUM_NODE_VERSION,
540
+ supportedClients: ["codex-cli", "codex-desktop", "claude-code"],
541
+ requiredTools: mcp.registeredToolNames(),
542
+ /**
543
+ * The signer MCP's tool surface, DERIVED from the pinned @haven_ai/signer
544
+ * package (#1587) — same anti-drift rule as `requiredTools` above: a
545
+ * literal list here would rot the first time the signer gains a tool.
546
+ * The handshake probe requires all of them.
547
+ */
548
+ requiredSignerTools: Object.keys(signer.toolSchemas)
549
+ };
550
+ }
551
+ });
552
+ async function writeRuntimeConfig(input, deps = {}) {
553
+ switch (input.runtime) {
554
+ case "codex-cli":
555
+ case "codex-desktop":
556
+ return writeCodexConfig(input);
557
+ case "cursor":
558
+ return writeJsonRuntimeConfig(input, cursorConfigPath(input.homeDir), "mcpServers");
559
+ case "vscode":
560
+ return writeJsonRuntimeConfig(input, vscodeConfigPath(input.homeDir), "servers");
561
+ case "vscode-insiders":
562
+ return writeJsonRuntimeConfig(input, vscodeInsidersConfigPath(input.homeDir), "servers");
563
+ case "claude-desktop":
564
+ return writeJsonRuntimeConfig(input, claudeDesktopConfigPath(input.homeDir), "mcpServers");
565
+ case "hermes":
566
+ return writeHermesConfig(input, deps);
567
+ default:
568
+ return {
569
+ hostedConfigured: false,
570
+ signerConfigured: false,
571
+ localMcpConfigured: false,
572
+ runtimeMcpMode: "manual",
573
+ target: "manual runtime setup",
574
+ changed: false,
575
+ restartRequired: true,
576
+ messages: ["Runtime config needs to be added manually for this agent environment."],
577
+ errorCode: "manual_runtime_setup_required"
578
+ };
579
+ }
580
+ }
581
+ function buildHostedServer(hostedMcpUrl, apiKey, runtime) {
582
+ if (runtime === "vscode" || runtime === "vscode-insiders") {
583
+ return {
584
+ type: "http",
585
+ url: hostedMcpUrl,
586
+ headers: { Authorization: `Bearer ${apiKey}` }
587
+ };
588
+ }
589
+ return {
590
+ url: hostedMcpUrl,
591
+ headers: { Authorization: `Bearer ${apiKey}` }
592
+ };
593
+ }
594
+ function resolveSignerLaunchSpec(input) {
595
+ return input.signerCommand ?? {
596
+ command: "npx",
597
+ args: ["-y", signerPackageSpec(), "--credentials", input.signerPath]
598
+ };
599
+ }
600
+ function buildSignerServer(spec, runtime) {
601
+ const server = {
602
+ command: spec.command,
603
+ args: spec.args
604
+ };
605
+ if (runtime === "vscode" || runtime === "vscode-insiders") return { type: "stdio", ...server };
606
+ return server;
607
+ }
608
+ function mergeJsonMcpConfig(existingJson, serverRoot, hostedServer, signerServer, names = serverNamesFor(), configPath) {
609
+ const config = existingJson?.trim() ? parseJsonObject(existingJson, configPath) : {};
610
+ const existingRoot = config[serverRoot];
611
+ const servers = existingRoot && typeof existingRoot === "object" && !Array.isArray(existingRoot) ? existingRoot : {};
612
+ config[serverRoot] = {
613
+ ...servers,
614
+ [names.hosted]: hostedServer,
615
+ [names.signer]: signerServer
616
+ };
617
+ return `${JSON.stringify(config, null, 2)}
618
+ `;
619
+ }
620
+ function mergeHermesYaml(existingYaml, hostedServer, signerServer, names = serverNamesFor(), configPath) {
621
+ if (!existingYaml?.trim()) {
622
+ return renderHermesYaml({ [names.hosted]: hostedServer, [names.signer]: signerServer });
205
623
  }
206
624
  const doc = yaml.parseDocument(existingYaml, { keepSourceTokens: true });
207
625
  if (doc.errors.length > 0 || !yaml.isMap(doc.contents)) {
@@ -852,35 +1270,115 @@ var init_config_writers = __esm({
852
1270
  };
853
1271
  }
854
1272
  });
855
- async function probeHostedAgentIdentity(apiKey, apiUrl, fetchImpl = fetch) {
856
- let response;
1273
+ async function acknowledgeLocalMcpConsent(identityPath, signerPath, log) {
857
1274
  try {
858
- response = await fetchWithTimeout(fetchImpl, `${apiUrl.replace(/\/+$/, "")}/machine-payments/agent`, {
859
- method: "GET",
860
- headers: { Authorization: `Bearer ${apiKey}`, Accept: "application/json" }
1275
+ const input = await buildLocalMcpConsentInput(identityPath, signerPath);
1276
+ const decision = await mcp.ensureConsent(input, {
1277
+ credentialsPath: identityPath,
1278
+ writeAck: true,
1279
+ out: log ? { write: (chunk) => writeLogChunk(log, chunk) } : void 0
861
1280
  });
862
- } catch {
863
- return { status: "network_error" };
864
- }
865
- if (response.status === 401 || response.status === 403) return { status: "unauthorized" };
866
- if (!response.ok) return { status: "bad_response" };
867
- try {
868
- const payload = JSON.parse(await response.text());
869
- if (typeof payload?.delegate_address !== "string") return { status: "bad_response" };
870
- return { status: "ok", agentId: payload.id, delegateAddress: payload.delegate_address };
871
- } catch {
872
- return { status: "bad_response" };
1281
+ return {
1282
+ acknowledged: decision.ok,
1283
+ hash: decision.hash,
1284
+ reason: decision.reason
1285
+ };
1286
+ } catch (err) {
1287
+ return {
1288
+ acknowledged: false,
1289
+ error: err instanceof Error ? err.message : String(err)
1290
+ };
873
1291
  }
874
1292
  }
875
- async function probeHostedMcpTools(apiKey, hostedMcpUrl, fetchImpl = fetch) {
876
- let response;
1293
+ async function getLocalMcpConsentStatus(identityPath, signerPath) {
877
1294
  try {
878
- response = await fetchWithTimeout(fetchImpl, hostedMcpUrl, {
879
- method: "POST",
880
- headers: {
881
- Authorization: `Bearer ${apiKey}`,
882
- "Content-Type": "application/json",
883
- Accept: "application/json, text/event-stream"
1295
+ const input = await buildLocalMcpConsentInput(identityPath, signerPath);
1296
+ const hash = mcp.computeConsentHash(input);
1297
+ const stored = await readLocalMcpAckFile(localMcpAckPath(identityPath));
1298
+ if (stored === hash) {
1299
+ return { acknowledged: true, hash, reason: "ack_file_match" };
1300
+ }
1301
+ return {
1302
+ acknowledged: false,
1303
+ hash,
1304
+ reason: stored ? "ack_file_mismatch" : "ack_file_missing"
1305
+ };
1306
+ } catch (err) {
1307
+ return {
1308
+ acknowledged: false,
1309
+ error: err instanceof Error ? err.message : String(err)
1310
+ };
1311
+ }
1312
+ }
1313
+ function localMcpAckPath(identityPath) {
1314
+ return path.resolve(`${identityPath}.ack.json`);
1315
+ }
1316
+ async function buildLocalMcpConsentInput(identityPath, signerPath) {
1317
+ const credentials = await mcp.loadCredentials({ identityPath, signerPath });
1318
+ const unavailableDuringSetup = {
1319
+ getAllowances: async () => {
1320
+ throw new Error("Haven approval is not complete yet.");
1321
+ }
1322
+ };
1323
+ return mcp.consentInputFromClient(
1324
+ unavailableDuringSetup,
1325
+ {
1326
+ apiKey: credentials.apiKey,
1327
+ apiUrl: credentials.apiUrl,
1328
+ agentId: credentials.agentId,
1329
+ safeAddress: credentials.safeAddress,
1330
+ delegateAddress: credentials.delegateAddress,
1331
+ chainId: credentials.chainId,
1332
+ allowanceSummary: credentials.allowanceSummary
1333
+ },
1334
+ mcp.registeredToolNames()
1335
+ );
1336
+ }
1337
+ async function readLocalMcpAckFile(path) {
1338
+ try {
1339
+ const parsed = JSON.parse(await promises.readFile(path, "utf8"));
1340
+ return typeof parsed.ack === "string" ? parsed.ack : null;
1341
+ } catch {
1342
+ return null;
1343
+ }
1344
+ }
1345
+ function writeLogChunk(log, chunk) {
1346
+ const message = String(chunk).trimEnd();
1347
+ if (message) log(message);
1348
+ }
1349
+ var init_local_mcp_consent = __esm({
1350
+ "src/local-mcp-consent.ts"() {
1351
+ }
1352
+ });
1353
+ async function probeHostedAgentIdentity(apiKey, apiUrl, fetchImpl = fetch) {
1354
+ let response;
1355
+ try {
1356
+ response = await fetchWithTimeout(fetchImpl, `${apiUrl.replace(/\/+$/, "")}/machine-payments/agent`, {
1357
+ method: "GET",
1358
+ headers: { Authorization: `Bearer ${apiKey}`, Accept: "application/json" }
1359
+ });
1360
+ } catch {
1361
+ return { status: "network_error" };
1362
+ }
1363
+ if (response.status === 401 || response.status === 403) return { status: "unauthorized" };
1364
+ if (!response.ok) return { status: "bad_response" };
1365
+ try {
1366
+ const payload = JSON.parse(await response.text());
1367
+ if (typeof payload?.delegate_address !== "string") return { status: "bad_response" };
1368
+ return { status: "ok", agentId: payload.id, delegateAddress: payload.delegate_address };
1369
+ } catch {
1370
+ return { status: "bad_response" };
1371
+ }
1372
+ }
1373
+ async function probeHostedMcpTools(apiKey, hostedMcpUrl, fetchImpl = fetch) {
1374
+ let response;
1375
+ try {
1376
+ response = await fetchWithTimeout(fetchImpl, hostedMcpUrl, {
1377
+ method: "POST",
1378
+ headers: {
1379
+ Authorization: `Bearer ${apiKey}`,
1380
+ "Content-Type": "application/json",
1381
+ Accept: "application/json, text/event-stream"
884
1382
  },
885
1383
  body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" })
886
1384
  });
@@ -1167,98 +1665,378 @@ var init_signer_runtime = __esm({
1167
1665
  SIGNER_INSTALL_HEARTBEAT_MS = 15e3;
1168
1666
  }
1169
1667
  });
1170
-
1171
- // src/connect-error.ts
1172
- var ConnectError;
1173
- var init_connect_error = __esm({
1174
- "src/connect-error.ts"() {
1175
- ConnectError = class extends Error {
1176
- code;
1177
- nextAction;
1178
- constructor(code, message, nextAction2) {
1179
- super(message);
1180
- this.name = "ConnectError";
1181
- this.code = code;
1182
- this.nextAction = nextAction2;
1183
- }
1184
- };
1668
+ async function prepareLocalMcpRuntime(input, deps = {}) {
1669
+ assertSupportedNodeVersion(input.nodeVersion);
1670
+ const homeDir = input.homeDir ?? os.homedir();
1671
+ const runtimeDirectory = path.resolve(homeDir, ".haven", "mcp-runtime", MCP_RUNTIME_MANIFEST.mcpVersion);
1672
+ const npmCacheDirectory = path.resolve(homeDir, ".haven", "npm-cache");
1673
+ const cliPath = path.join(runtimeDirectory, "node_modules", "@haven_ai", "mcp", "dist", "cli.js");
1674
+ const messages = [];
1675
+ await promises.mkdir(runtimeDirectory, { recursive: true, mode: 448 });
1676
+ await promises.chmod(runtimeDirectory, 448).catch(() => void 0);
1677
+ await promises.mkdir(npmCacheDirectory, { recursive: true, mode: 448 });
1678
+ await promises.chmod(npmCacheDirectory, 448).catch(() => void 0);
1679
+ if (await installedRuntimeMatches2(runtimeDirectory, cliPath)) {
1680
+ messages.push(`Using existing local Haven MCP runtime ${mcpPackageSpec()}.`);
1681
+ } else {
1682
+ await installRuntimePackages2(runtimeDirectory, npmCacheDirectory, deps);
1683
+ messages.push(`Installed local Haven MCP runtime ${mcpPackageSpec()}.`);
1185
1684
  }
1186
- });
1187
-
1188
- // src/runtime-registry.ts
1189
- function runtimeProfile(runtime, env = process.env) {
1190
- return RUNTIME_PROFILES[normalizeRuntime(runtime, env)];
1685
+ await assertFileExists2(cliPath, "local Haven MCP CLI");
1686
+ const wrapperPath = path.join(input.credentialDirectory, "bin", "haven-mcp");
1687
+ await writeWrapper2({
1688
+ wrapperPath,
1689
+ cliPath,
1690
+ identityPath: input.identityPath,
1691
+ signerPath: input.signerPath
1692
+ });
1693
+ await writeRuntimeSidecar2({
1694
+ path: path.join(input.credentialDirectory, "mcp-runtime.json"),
1695
+ wrapperPath,
1696
+ runtimeDirectory,
1697
+ npmCacheDirectory,
1698
+ cliPath,
1699
+ serverName: input.serverName
1700
+ });
1701
+ messages.push(`Prepared stable local Haven MCP wrapper: ${wrapperPath}`);
1702
+ return {
1703
+ command: wrapperPath,
1704
+ args: [],
1705
+ wrapperPath,
1706
+ runtimeDirectory,
1707
+ npmCacheDirectory,
1708
+ cliPath,
1709
+ messages
1710
+ };
1191
1711
  }
1192
- function normalizeRuntime(runtime, env = process.env) {
1193
- const explicit = normalizeRuntimeName(runtime);
1194
- if (explicit) return explicit;
1195
- return detectRuntime(env) ?? "other";
1712
+ function assertSupportedNodeVersion(nodeVersion = process.versions.node, minimumNodeVersion = MCP_RUNTIME_MANIFEST.minimumNodeVersion, subject = "Haven setup") {
1713
+ if (!sdk.isSupportedNodeVersion(nodeVersion, minimumNodeVersion)) {
1714
+ throw new UnsupportedNodeVersionError(nodeVersion, minimumNodeVersion, subject);
1715
+ }
1196
1716
  }
1197
- async function resolveRuntimeSelection(explicit, force, options = {}) {
1198
- const env = options.env ?? process.env;
1199
- if (force !== void 0) {
1200
- const forced = normalizeRuntimeName(force);
1201
- if (!forced) {
1202
- throw new ConnectError(
1203
- "runtime_force_unrecognized",
1204
- `Unknown --runtime-force value "${force}". Valid values: ${RUNTIME_FLAG_VALUES}.`,
1205
- "rerun_connect_with_a_valid_runtime_name"
1206
- );
1717
+ async function installRuntimePackages2(runtimeDirectory, npmCacheDirectory, deps) {
1718
+ const { runCommand, onProgress } = deps;
1719
+ const baseArgs = [
1720
+ "install",
1721
+ "--prefix",
1722
+ runtimeDirectory,
1723
+ "--no-audit",
1724
+ "--no-fund",
1725
+ "--omit=dev",
1726
+ "--prefer-offline",
1727
+ mcpPackageSpec(),
1728
+ sdkPackageSpec()
1729
+ ];
1730
+ const run = async (args) => {
1731
+ const startedAt = Date.now();
1732
+ const heartbeat = setInterval(() => {
1733
+ const seconds = Math.round((Date.now() - startedAt) / 1e3);
1734
+ onProgress?.(`Still installing the local Haven MCP runtime\u2026 (${seconds}s \u2014 a cold cache can take several minutes)`);
1735
+ }, SIGNER_INSTALL_HEARTBEAT_MS);
1736
+ heartbeat.unref?.();
1737
+ try {
1738
+ if (runCommand) await runCommand("npm", args);
1739
+ else await execFileAsync2("npm", args, { timeout: SIGNER_INSTALL_TIMEOUT_MS, maxBuffer: 1024 * 1024 });
1740
+ } finally {
1741
+ clearInterval(heartbeat);
1207
1742
  }
1208
- return { runtime: forced, source: "force" };
1209
- }
1210
- const detected = detectRuntime(env);
1211
- const supplied = explicit?.trim() || options.selfReported?.trim() || void 0;
1212
- const hint = normalizeRuntimeName(supplied);
1213
- if (supplied && !hint) {
1214
- if (!detected) {
1215
- throw new ConnectError(
1216
- "runtime_unrecognized",
1217
- `"${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.`,
1218
- "rerun_connect_with_a_valid_runtime_name"
1219
- );
1743
+ };
1744
+ try {
1745
+ await run(baseArgs);
1746
+ } catch {
1747
+ try {
1748
+ await run([...baseArgs, "--cache", npmCacheDirectory]);
1749
+ } catch (err) {
1750
+ throw new Error(`Could not install local Haven MCP runtime ${mcpPackageSpec()}: ${err instanceof Error ? err.message : String(err)}`);
1220
1751
  }
1221
- return { runtime: detected, source: "detected", discardedHint: supplied };
1222
1752
  }
1223
- if (detected && hint && detected !== hint) {
1224
- return { runtime: detected, source: "detected", overrodeHint: hint };
1225
- }
1226
- if (hint) return { runtime: hint, source: "explicit" };
1227
- if (detected) return { runtime: detected, source: "detected" };
1228
- if (options.promptForRuntime) {
1229
- return { runtime: await options.promptForRuntime(), source: "prompted" };
1230
- }
1231
- return { runtime: null, source: "none" };
1232
- }
1233
- function restartRequiredForRuntime(runtime, env = process.env) {
1234
- const mode = runtimeProfile(runtime, env).restartMode;
1235
- return mode === "restart-session" || mode === "restart-app";
1236
- }
1237
- function runtimeVerificationInstruction(runtime) {
1238
- const label = RUNTIME_PROFILES[runtime].label;
1239
- 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.`;
1240
1753
  }
1241
- function normalizeRuntimeName(runtime) {
1242
- const key = runtime?.trim().toLowerCase();
1243
- if (!key) return null;
1244
- return RUNTIME_ALIASES[key.replace(/\s+/g, "-")] ?? null;
1754
+ async function installedRuntimeMatches2(runtimeDirectory, cliPath) {
1755
+ try {
1756
+ await assertFileExists2(cliPath, "local Haven MCP CLI");
1757
+ const [mcpPackage, sdkPackage] = await Promise.all([
1758
+ readPackageJson2(path.join(runtimeDirectory, "node_modules", "@haven_ai", "mcp", "package.json")),
1759
+ readPackageJson2(path.join(runtimeDirectory, "node_modules", "@haven_ai", "sdk", "package.json"))
1760
+ ]);
1761
+ return mcpPackage.version === MCP_RUNTIME_MANIFEST.mcpVersion && sdkPackage.version === MCP_RUNTIME_MANIFEST.sdkVersion;
1762
+ } catch {
1763
+ return false;
1764
+ }
1245
1765
  }
1246
- function detectRuntime(env) {
1247
- if (env.CLAUDECODE || env.CLAUDE_CODE || env.CLAUDECODE_CWD) return "claude-code";
1248
- if (env.CODEX_SANDBOX || env.CODEX_HOME || env.CODEX_CWD) return "codex-cli";
1249
- if (env.VSCODE_CWD || env.VSCODE_IPC_HOOK_CLI || env.TERM_PROGRAM === "vscode") return "vscode";
1250
- if (env.HERMES_HOME || env.HERMES_AGENT) return "hermes";
1251
- return null;
1766
+ async function readPackageJson2(path) {
1767
+ return JSON.parse(await promises.readFile(path, "utf8"));
1252
1768
  }
1253
- var RUNTIME_PROFILES, RUNTIME_ALIASES, RUNTIME_FLAG_VALUES;
1254
- var init_runtime_registry = __esm({
1255
- "src/runtime-registry.ts"() {
1256
- init_connect_error();
1257
- RUNTIME_PROFILES = {
1258
- "claude-code": {
1259
- id: "claude-code",
1260
- label: "Claude Code",
1261
- restartMode: "restart-session",
1769
+ async function writeWrapper2(input) {
1770
+ await promises.mkdir(path.dirname(input.wrapperPath), { recursive: true, mode: 448 });
1771
+ await promises.chmod(path.dirname(input.wrapperPath), 448).catch(() => void 0);
1772
+ const source = [
1773
+ "#!/usr/bin/env node",
1774
+ "import { spawn } from 'node:child_process'",
1775
+ "",
1776
+ `const cliPath = ${JSON.stringify(input.cliPath)}`,
1777
+ `const identityPath = ${JSON.stringify(input.identityPath)}`,
1778
+ `const signerPath = ${JSON.stringify(input.signerPath)}`,
1779
+ "",
1780
+ "const child = spawn(process.execPath, [cliPath, '--identity', identityPath, '--signer', signerPath, ...process.argv.slice(2)], {",
1781
+ " stdio: 'inherit',",
1782
+ "})",
1783
+ "",
1784
+ "child.on('exit', (code, signal) => {",
1785
+ " if (signal) process.kill(process.pid, signal)",
1786
+ " else process.exit(code ?? 1)",
1787
+ "})",
1788
+ ""
1789
+ ].join("\n");
1790
+ await promises.writeFile(input.wrapperPath, source, { mode: 448 });
1791
+ await promises.chmod(input.wrapperPath, 448).catch(() => void 0);
1792
+ }
1793
+ async function writeRuntimeSidecar2(input) {
1794
+ const value = {
1795
+ ...input.serverName ? { server_name: input.serverName } : {},
1796
+ mcp_package: MCP_RUNTIME_MANIFEST.mcpPackage,
1797
+ mcp_version: MCP_RUNTIME_MANIFEST.mcpVersion,
1798
+ sdk_package: MCP_RUNTIME_MANIFEST.sdkPackage,
1799
+ sdk_version: MCP_RUNTIME_MANIFEST.sdkVersion,
1800
+ minimum_node_version: MCP_RUNTIME_MANIFEST.minimumNodeVersion,
1801
+ wrapper_path: input.wrapperPath,
1802
+ runtime_directory: input.runtimeDirectory,
1803
+ npm_cache_directory: input.npmCacheDirectory,
1804
+ cli_path: input.cliPath
1805
+ };
1806
+ await promises.writeFile(input.path, `${JSON.stringify(value, null, 2)}
1807
+ `, { mode: 384 });
1808
+ await promises.chmod(input.path, 384).catch(() => void 0);
1809
+ }
1810
+ async function assertFileExists2(path, label) {
1811
+ try {
1812
+ await promises.access(path);
1813
+ } catch {
1814
+ throw new Error(`Missing ${label}: ${path}`);
1815
+ }
1816
+ }
1817
+ var execFileAsync2, UnsupportedNodeVersionError;
1818
+ var init_local_mcp_runtime = __esm({
1819
+ "src/local-mcp-runtime.ts"() {
1820
+ init_signer_runtime();
1821
+ init_runtime_manifest();
1822
+ execFileAsync2 = util.promisify(child_process.execFile);
1823
+ UnsupportedNodeVersionError = class extends Error {
1824
+ code = "local_mcp_unsupported_node_version";
1825
+ nodeVersion;
1826
+ minimumNodeVersion;
1827
+ constructor(nodeVersion, minimumNodeVersion, subject = "Haven setup") {
1828
+ super(sdk.unsupportedNodeVersionMessage({ subject, nodeVersion, minimumNodeVersion }));
1829
+ this.name = "UnsupportedNodeVersionError";
1830
+ this.nodeVersion = nodeVersion;
1831
+ this.minimumNodeVersion = minimumNodeVersion;
1832
+ }
1833
+ };
1834
+ }
1835
+ });
1836
+ async function installSkillForRuntime(runtime, deps = {}) {
1837
+ switch (runtime) {
1838
+ case "claude-code":
1839
+ return installSkillFile(
1840
+ path.resolve(deps.homeDir ?? os.homedir(), ".claude", "skills", sdk.SKILL_FOLDER_NAME),
1841
+ "~/.claude/skills/haven-pay"
1842
+ );
1843
+ case "hermes":
1844
+ return installSkillFile(
1845
+ path.join(hermesHome(deps), "skills", sdk.SKILL_FOLDER_NAME),
1846
+ "the Hermes skills folder"
1847
+ );
1848
+ case "codex-cli":
1849
+ case "codex-desktop":
1850
+ return installCodexAgentsSection(deps);
1851
+ default:
1852
+ return void 0;
1853
+ }
1854
+ }
1855
+ async function installSkillFile(skillDir, label) {
1856
+ try {
1857
+ await promises.mkdir(skillDir, { recursive: true });
1858
+ const target = path.join(skillDir, "SKILL.md");
1859
+ await promises.writeFile(target, sdk.HAVEN_SKILL_MD, "utf8");
1860
+ return {
1861
+ installed: true,
1862
+ target,
1863
+ messages: [`Installed the generic Haven payment skill (${label}). It contains no secrets.`]
1864
+ };
1865
+ } catch (err) {
1866
+ return {
1867
+ installed: false,
1868
+ messages: [
1869
+ `Could not install the Haven payment skill: ${err instanceof Error ? err.message : String(err)}. Download it from the Haven dashboard instead.`
1870
+ ]
1871
+ };
1872
+ }
1873
+ }
1874
+ async function installCodexAgentsSection(deps) {
1875
+ try {
1876
+ const codexDir = path.resolve(deps.homeDir ?? os.homedir(), ".codex");
1877
+ const target = path.join(codexDir, "AGENTS.md");
1878
+ await promises.mkdir(codexDir, { recursive: true });
1879
+ const existing = await promises.readFile(target, "utf8").catch(() => null);
1880
+ const next = upsertManagedSection(existing, codexManagedSection());
1881
+ if (next !== existing) {
1882
+ await promises.writeFile(target, next, "utf8");
1883
+ }
1884
+ return {
1885
+ installed: true,
1886
+ target,
1887
+ messages: [
1888
+ "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."
1889
+ ]
1890
+ };
1891
+ } catch (err) {
1892
+ return {
1893
+ installed: false,
1894
+ messages: [
1895
+ `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.`
1896
+ ]
1897
+ };
1898
+ }
1899
+ }
1900
+ function codexManagedSection() {
1901
+ return `${CODEX_AGENTS_BEGIN_MARKER}
1902
+
1903
+ ${sdk.HAVEN_SKILL_BODY_MD.trimEnd()}
1904
+
1905
+ ${CODEX_AGENTS_END_MARKER}
1906
+ `;
1907
+ }
1908
+ function upsertManagedSection(existing, section) {
1909
+ if (existing === null || existing.trim() === "") return section;
1910
+ const begins = markerLineIndexes(existing, CODEX_AGENTS_BEGIN_MARKER);
1911
+ const ends = markerLineIndexes(existing, CODEX_AGENTS_END_MARKER);
1912
+ if (begins.length === 1 && ends.length === 1 && ends[0] > begins[0]) {
1913
+ const afterEnd = ends[0] + CODEX_AGENTS_END_MARKER.length;
1914
+ const tail = existing.startsWith("\r\n", afterEnd) ? existing.slice(afterEnd + 2) : existing.startsWith("\n", afterEnd) ? existing.slice(afterEnd + 1) : existing.slice(afterEnd);
1915
+ return existing.slice(0, begins[0]) + section + tail;
1916
+ }
1917
+ if (begins.length > 0 || ends.length > 0) {
1918
+ throw new Error(
1919
+ "found a damaged Haven marker section (orphaned or duplicated markers); remove the leftover marker lines and re-run setup"
1920
+ );
1921
+ }
1922
+ return `${existing.replace(/\n*$/, "\n\n")}${section}`;
1923
+ }
1924
+ function markerLineIndexes(text, marker) {
1925
+ const indexes = [];
1926
+ for (let from = 0; ; ) {
1927
+ const at = text.indexOf(marker, from);
1928
+ if (at === -1) return indexes;
1929
+ if (at === 0 || text[at - 1] === "\n") indexes.push(at);
1930
+ from = at + marker.length;
1931
+ }
1932
+ }
1933
+ function hermesHome(deps) {
1934
+ const env = deps.env ?? process.env;
1935
+ return env.HERMES_HOME ?? path.join(deps.homeDir ?? os.homedir(), ".hermes");
1936
+ }
1937
+ var CODEX_AGENTS_BEGIN_MARKER, CODEX_AGENTS_END_MARKER;
1938
+ var init_skill_install = __esm({
1939
+ "src/skill-install.ts"() {
1940
+ CODEX_AGENTS_BEGIN_MARKER = "<!-- BEGIN haven-pay (managed by @haven_ai/connect; edits inside this section are overwritten on re-setup) -->";
1941
+ CODEX_AGENTS_END_MARKER = "<!-- END haven-pay -->";
1942
+ }
1943
+ });
1944
+
1945
+ // src/connect-error.ts
1946
+ var ConnectError;
1947
+ var init_connect_error = __esm({
1948
+ "src/connect-error.ts"() {
1949
+ ConnectError = class extends Error {
1950
+ code;
1951
+ nextAction;
1952
+ details;
1953
+ constructor(code, message, nextAction2, details = {}) {
1954
+ super(message);
1955
+ this.name = "ConnectError";
1956
+ this.code = code;
1957
+ this.nextAction = nextAction2;
1958
+ this.details = details;
1959
+ }
1960
+ };
1961
+ }
1962
+ });
1963
+
1964
+ // src/runtime-registry.ts
1965
+ function runtimeProfile(runtime, env = process.env) {
1966
+ return RUNTIME_PROFILES[normalizeRuntime(runtime, env)];
1967
+ }
1968
+ function normalizeRuntime(runtime, env = process.env) {
1969
+ const explicit = normalizeRuntimeName(runtime);
1970
+ if (explicit) return explicit;
1971
+ return detectRuntime(env) ?? "other";
1972
+ }
1973
+ async function resolveRuntimeSelection(explicit, force, options = {}) {
1974
+ const env = options.env ?? process.env;
1975
+ if (force !== void 0) {
1976
+ const forced = normalizeRuntimeName(force);
1977
+ if (!forced) {
1978
+ throw new ConnectError(
1979
+ "runtime_force_unrecognized",
1980
+ `Unknown --runtime-force value "${force}". Valid values: ${RUNTIME_FLAG_VALUES}.`,
1981
+ "rerun_connect_with_a_valid_runtime_name",
1982
+ { allowedRuntimes: RUNTIME_FLAG_VALUE_LIST }
1983
+ );
1984
+ }
1985
+ return { runtime: forced, source: "force" };
1986
+ }
1987
+ const detected = detectRuntime(env);
1988
+ const supplied = explicit?.trim() || options.selfReported?.trim() || void 0;
1989
+ const hint = normalizeRuntimeName(supplied);
1990
+ if (supplied && !hint) {
1991
+ if (!detected) {
1992
+ throw new ConnectError(
1993
+ "runtime_unrecognized",
1994
+ `"${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.`,
1995
+ "rerun_connect_with_a_valid_runtime_name",
1996
+ { allowedRuntimes: RUNTIME_FLAG_VALUE_LIST }
1997
+ );
1998
+ }
1999
+ return { runtime: detected, source: "detected", discardedHint: supplied };
2000
+ }
2001
+ if (detected && hint && detected !== hint) {
2002
+ return { runtime: detected, source: "detected", overrodeHint: hint };
2003
+ }
2004
+ if (hint) return { runtime: hint, source: "explicit" };
2005
+ if (detected) return { runtime: detected, source: "detected" };
2006
+ if (options.promptForRuntime) {
2007
+ return { runtime: await options.promptForRuntime(), source: "prompted" };
2008
+ }
2009
+ return { runtime: null, source: "none" };
2010
+ }
2011
+ function restartRequiredForRuntime(runtime, env = process.env) {
2012
+ const mode = runtimeProfile(runtime, env).restartMode;
2013
+ return mode === "restart-session" || mode === "restart-app";
2014
+ }
2015
+ function runtimeVerificationInstruction(runtime) {
2016
+ const label = RUNTIME_PROFILES[runtime].label;
2017
+ 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.`;
2018
+ }
2019
+ function normalizeRuntimeName(runtime) {
2020
+ const key = runtime?.trim().toLowerCase();
2021
+ if (!key) return null;
2022
+ return RUNTIME_ALIASES[key.replace(/\s+/g, "-")] ?? null;
2023
+ }
2024
+ function detectRuntime(env) {
2025
+ if (env.CLAUDECODE || env.CLAUDE_CODE || env.CLAUDECODE_CWD) return "claude-code";
2026
+ if (env.CODEX_SANDBOX || env.CODEX_HOME || env.CODEX_CWD) return "codex-cli";
2027
+ if (env.VSCODE_CWD || env.VSCODE_IPC_HOOK_CLI || env.TERM_PROGRAM === "vscode") return "vscode";
2028
+ if (env.HERMES_HOME || env.HERMES_AGENT) return "hermes";
2029
+ return null;
2030
+ }
2031
+ var RUNTIME_PROFILES, RUNTIME_ALIASES, RUNTIME_FLAG_VALUE_LIST, RUNTIME_FLAG_VALUES;
2032
+ var init_runtime_registry = __esm({
2033
+ "src/runtime-registry.ts"() {
2034
+ init_connect_error();
2035
+ RUNTIME_PROFILES = {
2036
+ "claude-code": {
2037
+ id: "claude-code",
2038
+ label: "Claude Code",
2039
+ restartMode: "restart-session",
1262
2040
  canWriteRuntimeConfig: true,
1263
2041
  activationInstruction: "Start a new Claude Code session so it loads the Haven MCP entries."
1264
2042
  },
@@ -1369,7 +2147,18 @@ var init_runtime_registry = __esm({
1369
2147
  other: "other",
1370
2148
  manual: "other"
1371
2149
  };
1372
- RUNTIME_FLAG_VALUES = "claude-code, codex-cli, codex-desktop, cursor, vscode, vscode-insiders, claude-desktop, hermes, other";
2150
+ RUNTIME_FLAG_VALUE_LIST = [
2151
+ "claude-code",
2152
+ "codex-cli",
2153
+ "codex-desktop",
2154
+ "cursor",
2155
+ "vscode",
2156
+ "vscode-insiders",
2157
+ "claude-desktop",
2158
+ "hermes",
2159
+ "other"
2160
+ ];
2161
+ RUNTIME_FLAG_VALUES = RUNTIME_FLAG_VALUE_LIST.join(", ");
1373
2162
  }
1374
2163
  });
1375
2164
  async function acknowledgeLocalSignerConsent(signerPath, log) {
@@ -1445,1519 +2234,1319 @@ var init_signer_consent = __esm({
1445
2234
  "src/signer-consent.ts"() {
1446
2235
  }
1447
2236
  });
1448
-
1449
- // src/tombstone.ts
1450
- var tombstone_exports = {};
1451
- __export(tombstone_exports, {
1452
- TOMBSTONE_FILENAME: () => TOMBSTONE_FILENAME,
1453
- TOMBSTONE_MARKER: () => TOMBSTONE_MARKER,
1454
- readAgentTombstone: () => readAgentTombstone,
1455
- writeAgentTombstone: () => writeAgentTombstone
1456
- });
1457
- function tombstoneScript(info) {
1458
- const lines = [
1459
- `${TOMBSTONE_MARKER}: this Haven agent was retired.`,
1460
- "",
1461
- ` agent: ${info.agent_id}`,
1462
- ` retired at: ${info.retired_at}`,
1463
- ` reason: ${info.reason}`,
1464
- ...info.replaced_by ? [` replaced by: ${info.replaced_by}`] : [],
1465
- "",
1466
- "This process is running with a wiring snapshot that predates the",
1467
- "retirement \u2014 it loaded its MCP config at startup and has kept it since.",
1468
- "Restart THIS host to pick up the current wiring. If several long-lived",
1469
- "hosts are running (a gateway, a TUI worker, an editor), restart EVERY",
1470
- "one of them: each holds the snapshot from its own start time, so after",
1471
- "a chain of recreations each can be parked on a DIFFERENT old agent.",
1472
- "",
1473
- "Then verify with: npx @haven_ai/connect@alpha --doctor --runtime <runtime>"
1474
- ];
1475
- return [
1476
- "#!/usr/bin/env node",
1477
- `// ${TOMBSTONE_MARKER} \u2014 written by @haven_ai/connect (#1681). Safe to delete`,
1478
- "// once every long-lived MCP host on this machine has been restarted.",
1479
- `process.stderr.write(${JSON.stringify(lines.join("\n") + "\n")})`,
1480
- "process.exit(1)",
1481
- ""
1482
- ].join("\n");
1483
- }
1484
- async function writeAgentTombstone(input) {
1485
- const dirStat = await promises.stat(input.directory).catch(() => null);
1486
- if (!dirStat?.isDirectory()) {
1487
- throw new Error(`Not a directory: ${input.directory} \u2014 nothing to tombstone.`);
1488
- }
1489
- const info = {
1490
- // reason / replaced_by are persisted to disk and re-emitted to the host's
1491
- // MCP stderr log on EVERY stale probe, potentially for months — redact
1492
- // like every other output path, at the write layer so any future caller
1493
- // inherits it. (#1681 review, finding 1)
1494
- agent_id: input.agentId,
1495
- retired_at: input.retiredAt ?? (/* @__PURE__ */ new Date()).toISOString(),
1496
- reason: redactSecrets(input.reason),
1497
- ...input.replacedBy ? { replaced_by: redactSecrets(input.replacedBy) } : {}
1498
- };
1499
- const binDir = path.join(input.directory, "bin");
1500
- await promises.mkdir(binDir, { recursive: true });
1501
- const wrapperPath = path.join(binDir, "haven-signer.mjs");
1502
- await promises.writeFile(wrapperPath, tombstoneScript(info), "utf8");
1503
- await promises.chmod(wrapperPath, 493);
1504
- await promises.writeFile(path.join(input.directory, TOMBSTONE_FILENAME), JSON.stringify(info, null, 2) + "\n", "utf8");
1505
- return info;
1506
- }
1507
- async function readAgentTombstone(directory) {
1508
- try {
1509
- const parsed = JSON.parse(await promises.readFile(path.join(directory, TOMBSTONE_FILENAME), "utf8"));
1510
- if (typeof parsed?.agent_id !== "string") return null;
1511
- return parsed;
1512
- } catch {
1513
- return null;
1514
- }
1515
- }
1516
- var TOMBSTONE_FILENAME, TOMBSTONE_MARKER;
1517
- var init_tombstone = __esm({
1518
- "src/tombstone.ts"() {
1519
- init_redact();
1520
- TOMBSTONE_FILENAME = "TOMBSTONE.json";
1521
- TOMBSTONE_MARKER = "HAVEN-TOMBSTONE";
1522
- }
1523
- });
1524
-
1525
- // src/doctor.ts
1526
- var doctor_exports = {};
1527
- __export(doctor_exports, {
1528
- runDoctor: () => runDoctor,
1529
- runRepair: () => runRepair
1530
- });
1531
- async function discoverCredentialDirectory(homeDir, explicit) {
1532
- const root = explicit ? path.dirname(explicit) : path.join(homeDir, ".haven", "agents");
1533
- let entries = [];
1534
- try {
1535
- entries = await promises.readdir(root);
1536
- } catch {
1537
- return explicit ? { directory: explicit, others: [] } : { others: [] };
2237
+ async function installRuntime(input, deps = {}) {
2238
+ const runtime = normalizeRuntime(input.runtime, deps.env);
2239
+ const profile = runtimeProfile(runtime, deps.env);
2240
+ const progress = deps.onProgress ?? (() => void 0);
2241
+ const localRuntime = input.localMcp === true && supportsLocalMcp(runtime);
2242
+ const consentMessages = [];
2243
+ const localMcpConsent = localRuntime ? await resolveLocalMcpConsent(input, consentMessages) : void 0;
2244
+ const signerConsent = localRuntime ? void 0 : await resolveSignerConsent(input, consentMessages);
2245
+ if (runtime === "other") {
2246
+ const signerCredentialReady2 = await probeLocalSignerCredential(input.signerPath);
2247
+ const signerReady = signerCredentialReady2 && signerConsent?.acknowledged;
2248
+ return {
2249
+ runtime,
2250
+ runtimeMcpMode: "manual",
2251
+ hostedMcpConfigured: false,
2252
+ localSignerConfigured: false,
2253
+ localMcpConfigured: false,
2254
+ probeResult: signerReady ? "manual_runtime_setup_required_local_signer_ready" : "manual_runtime_setup_required_local_signer_unavailable",
2255
+ restartRequired: true,
2256
+ nextUserAction: "return_to_haven_for_wallet_approval_then_configure_runtime",
2257
+ errorCode: "manual_runtime_setup_required",
2258
+ configTarget: "manual runtime setup",
2259
+ signerAcknowledged: signerConsent?.acknowledged,
2260
+ localMcpAcknowledged: false,
2261
+ messages: [
2262
+ ...consentMessages,
2263
+ "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.",
2264
+ ` identity (hosted MCP Bearer): ${input.identityPath}`,
2265
+ ` signer (local signing key): ${input.signerPath}`,
2266
+ "After wallet approval, wire the runtime to Haven by reference:",
2267
+ ` 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}`,
2268
+ ` Fully local MCP (no hosted dependency): npx -y ${mcpPackageSpec()} --identity ${input.identityPath} --signer ${input.signerPath}`
2269
+ ]
2270
+ };
1538
2271
  }
1539
- const candidates = [];
1540
- const tombstonedOnly = [];
1541
- for (const entry of entries) {
1542
- const directory = path.join(root, entry);
2272
+ let localRuntimeInstall;
2273
+ let localRuntimeError;
2274
+ if (localRuntime) {
1543
2275
  try {
1544
- const s = await promises.stat(path.join(directory, "identity.json"));
1545
- candidates.push({ directory, mtimeMs: s.mtimeMs });
1546
- } catch {
1547
- try {
1548
- await promises.stat(path.join(directory, TOMBSTONE_FILENAME));
1549
- tombstonedOnly.push(directory);
1550
- } catch {
1551
- }
2276
+ localRuntimeInstall = await prepareRuntimeForLocalMcp(input, deps);
2277
+ } catch (err) {
2278
+ localRuntimeError = err;
1552
2279
  }
1553
2280
  }
1554
- candidates.sort((a, b) => b.mtimeMs - a.mtimeMs);
1555
- if (explicit) {
2281
+ if (localRuntimeError) {
2282
+ const errorCode2 = localRuntimePrepareErrorCode(localRuntimeError);
1556
2283
  return {
1557
- directory: explicit,
1558
- others: [...candidates.map((c) => c.directory), ...tombstonedOnly].filter((d) => d !== explicit)
2284
+ runtime,
2285
+ runtimeMcpMode: "local_stdio",
2286
+ hostedMcpConfigured: false,
2287
+ localSignerConfigured: false,
2288
+ localMcpConfigured: false,
2289
+ probeResult: errorCode2 === "local_mcp_unsupported_node_version" ? "local_stdio_mcp_unsupported_node_version" : "local_stdio_mcp_runtime_install_failed",
2290
+ restartRequired: true,
2291
+ nextUserAction: nextAction(runtime, profile.restartMode, errorCode2),
2292
+ errorCode: errorCode2,
2293
+ configTarget: profile.label,
2294
+ signerAcknowledged: signerConsent?.acknowledged,
2295
+ localMcpAcknowledged: localMcpConsent?.acknowledged,
2296
+ activationCommand: void 0,
2297
+ messages: [
2298
+ ...consentMessages,
2299
+ `Could not prepare local Haven MCP runtime: ${localRuntimeError instanceof Error ? localRuntimeError.message : String(localRuntimeError)}`
2300
+ ]
1559
2301
  };
1560
2302
  }
1561
- if (candidates.length === 0 && tombstonedOnly.length === 0) return { others: [] };
1562
- return {
1563
- directory: candidates[0]?.directory,
1564
- others: [...candidates.slice(1).map((c) => c.directory), ...tombstonedOnly]
1565
- };
1566
- }
1567
- function agentIsWired(configText, names, slug, identity, sidecar, isPrimary, bareOwnerExists) {
1568
- if (configText === null) return isPrimary;
1569
- if (slug) {
1570
- for (const name of [names.hosted, names.codexHosted, names.signer, names.codexSigner]) {
1571
- if (new RegExp(`(^|[."'\\s\\[])${name}(["'\\]:\\s]|$)`, "m").test(configText)) return true;
2303
+ let signerCommand;
2304
+ if (!localRuntime) {
2305
+ progress("Getting the signer ready\u2026");
2306
+ try {
2307
+ const signerRuntime = await prepareSignerForRuntime(input, deps);
2308
+ signerCommand = { command: signerRuntime.command, args: signerRuntime.args };
2309
+ consentMessages.push(...signerRuntime.messages);
2310
+ } catch (err) {
2311
+ return {
2312
+ runtime,
2313
+ runtimeMcpMode: "hosted_plus_signer",
2314
+ hostedMcpConfigured: false,
2315
+ localSignerConfigured: false,
2316
+ localMcpConfigured: false,
2317
+ probeResult: "signer_runtime_install_failed",
2318
+ restartRequired: false,
2319
+ 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",
2320
+ errorCode: "signer_runtime_install_failed",
2321
+ configTarget: profile.label,
2322
+ signerAcknowledged: signerConsent?.acknowledged,
2323
+ localMcpAcknowledged: localMcpConsent?.acknowledged,
2324
+ activationCommand: void 0,
2325
+ signerRuntimePrepared: false,
2326
+ messages: [
2327
+ ...consentMessages,
2328
+ `Could not pre-install the local Haven signer: ${err instanceof Error ? err.message : String(err)}`,
2329
+ "No runtime configuration was written (fail-closed): a config pointing at an uninstalled signer looks wired but cannot start.",
2330
+ "Re-run `npx @haven_ai/connect@alpha` to retry the setup."
2331
+ ]
2332
+ };
1572
2333
  }
1573
- return false;
1574
- }
1575
- if (sidecar?.wrapper_path && configText.includes(sidecar.wrapper_path)) return true;
1576
- if (bareOwnerExists) return false;
1577
- return isPrimary && Boolean(identity?.hosted_mcp_url && configText.includes(identity.hosted_mcp_url));
1578
- }
1579
- async function readIdentity(directory) {
1580
- try {
1581
- return JSON.parse(await promises.readFile(path.join(directory, "identity.json"), "utf8"));
1582
- } catch {
1583
- return void 0;
1584
2334
  }
1585
- }
1586
- async function checksForAgent(entry, input, deps) {
1587
- const { directory, identity, sidecar } = entry;
1588
- const checks = [];
1589
- let signerCapabilities;
1590
- let signerFile;
1591
- try {
1592
- const parsed = JSON.parse(await promises.readFile(path.join(directory, "signer.json"), "utf8"));
1593
- signerFile = typeof parsed === "object" && parsed !== null ? parsed : void 0;
1594
- } catch {
1595
- signerFile = void 0;
2335
+ const signerRuntimePrepared = localRuntime ? void 0 : signerCommand !== void 0;
2336
+ progress("Setting up your Haven tools\u2026");
2337
+ const configResult = localRuntime ? runtime === "claude-code" ? await configureClaudeCode(deps, localRuntimeInstall?.command ?? "", input.serverName) : await writeRuntimeConfig({
2338
+ runtime,
2339
+ hostedMcpUrl: input.hostedMcpUrl,
2340
+ apiKey: input.apiKey,
2341
+ identityPath: input.identityPath,
2342
+ signerPath: input.signerPath,
2343
+ serverName: input.serverName,
2344
+ credentialDirectory: input.credentialDirectory,
2345
+ localMcpCommand: localRuntimeInstall?.command,
2346
+ signerCommand,
2347
+ homeDir: deps.homeDir,
2348
+ mode: "local"
2349
+ }) : await writeHostedRuntimeConfig(deps, { ...input, runtime }, signerCommand);
2350
+ if (deps.onRuntimeConfigured) {
2351
+ const signerCredentialOnDisk = await probeLocalSignerCredential(input.signerPath);
2352
+ const earlyLocalMcpOk = configResult.runtimeMcpMode === "local_stdio" && configResult.localMcpConfigured && signerCredentialOnDisk && Boolean(localMcpConsent?.acknowledged);
2353
+ const earlySignerOk = configResult.runtimeMcpMode === "local_stdio" ? earlyLocalMcpOk : configResult.signerConfigured && signerCredentialOnDisk && Boolean(signerConsent?.acknowledged);
2354
+ try {
2355
+ await deps.onRuntimeConfigured({
2356
+ runtime,
2357
+ runtimeMcpMode: configResult.runtimeMcpMode,
2358
+ hostedMcpConfigured: configResult.hostedConfigured,
2359
+ localSignerConfigured: earlySignerOk,
2360
+ localMcpConfigured: earlyLocalMcpOk,
2361
+ signerAcknowledged: signerConsent?.acknowledged,
2362
+ localMcpAcknowledged: localMcpConsent?.acknowledged,
2363
+ restartRequired: configResult.restartRequired || restartRequiredForRuntime(runtime, deps.env),
2364
+ nextUserAction: nextAction(runtime, profile.restartMode, configResult.errorCode),
2365
+ errorCode: configResult.errorCode
2366
+ });
2367
+ } catch {
2368
+ }
1596
2369
  }
1597
- const credentialsOk = Boolean(identity?.api_key) && signerFile !== void 0;
1598
- checks.push({
1599
- id: "credentials",
1600
- label: "Agent credentials",
1601
- ok: credentialsOk,
1602
- detail: credentialsOk ? `identity.json and signer.json parse (agent ${identity?.agent_id ?? "unknown"})` : "identity.json or signer.json is missing or unparseable.",
1603
- ...credentialsOk ? {} : { repair: `Re-run the full setup with a fresh token: ${RERUN} --setup <token>.` }
1604
- });
1605
- if (!sidecar) {
1606
- checks.push({
1607
- id: "signer_runtime",
1608
- label: "Signer runtime (preinstalled wrapper)",
1609
- ok: false,
1610
- detail: "No signer-runtime.json sidecar \u2014 the pinned signer runtime was never prepared (or a pre-#1586 npx config).",
1611
- repair: `Run: ${RERUN} --doctor --repair --runtime ${input.runtime}`
1612
- });
1613
- } else {
1614
- const matches = await installedRuntimeMatches(sidecar.runtime_directory, sidecar.cli_path);
1615
- const versionOk = sidecar.signer_version === MCP_RUNTIME_MANIFEST.signerVersion;
1616
- const ok = matches && versionOk;
1617
- checks.push({
1618
- id: "signer_runtime",
1619
- label: "Signer runtime (preinstalled wrapper)",
1620
- ok,
1621
- 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.`,
1622
- ...ok ? {} : { repair: `Run: ${RERUN} --doctor --repair --runtime ${input.runtime}` }
1623
- });
1624
- }
1625
- const hostedUrl = identity?.hosted_mcp_url ?? (identity?.api_url ? `${identity.api_url}/mcp` : void 0);
1626
- if (identity?.api_key && hostedUrl) {
1627
- const probe = await (deps.probeHosted ?? probeHostedMcpTools)(identity.api_key, hostedUrl, deps.fetch);
1628
- checks.push({
1629
- id: "hosted_mcp",
1630
- label: "Hosted Haven MCP",
1631
- ok: probe.status === "ok",
1632
- detail: probe.status === "ok" ? `Reachable and authorized (${hostedUrl}).` : `Probe failed: ${probe.status} (${hostedUrl}).`,
1633
- ...probe.status === "ok" ? {} : {
1634
- 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."
1635
- }
1636
- });
1637
- } else {
1638
- checks.push({
1639
- id: "hosted_mcp",
1640
- label: "Hosted Haven MCP",
1641
- ok: false,
1642
- detail: "No stored API key / hosted MCP URL to probe with.",
1643
- repair: `Re-run the full setup: ${RERUN} --setup <token>.`
1644
- });
1645
- }
1646
- const localDelegate = typeof signerFile?.delegate_address === "string" ? signerFile.delegate_address : void 0;
1647
- if (identity?.api_key && identity.api_url) {
1648
- const probe = await (deps.probeHostedIdentity ?? probeHostedAgentIdentity)(
1649
- identity.api_key,
1650
- identity.api_url,
1651
- deps.fetch
1652
- );
1653
- if (probe.status !== "ok") {
1654
- checks.push({
1655
- id: "identity_match",
1656
- label: "Hosted identity matches the local signing key",
1657
- ok: false,
1658
- 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.`,
1659
- 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}`
1660
- });
1661
- } else if (!localDelegate) {
1662
- checks.push({
1663
- id: "identity_match",
1664
- label: "Hosted identity matches the local signing key",
1665
- ok: false,
1666
- detail: "signer.json holds no delegate_address to compare against the hosted identity.",
1667
- repair: `Re-run the full setup with a fresh token: ${RERUN} --setup <token>.`
1668
- });
1669
- } else {
1670
- const same = probe.delegateAddress?.toLowerCase() === localDelegate.toLowerCase();
1671
- checks.push({
1672
- id: "identity_match",
1673
- label: "Hosted identity matches the local signing key",
1674
- ok: same,
1675
- 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.`,
1676
- ...same ? {} : {
1677
- 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.`
1678
- }
1679
- });
1680
- }
1681
- }
1682
- if (sidecar) {
1683
- const consent = await getLocalSignerConsentStatus(path.join(directory, "signer.json"));
1684
- if (!consent.acknowledged) {
1685
- checks.push({
1686
- id: "signer_process",
1687
- label: "Signer stdio handshake",
1688
- ok: false,
1689
- detail: "The local-tools consent is not acknowledged, so the signer refuses to start (by design).",
1690
- repair: `Run: ${RERUN} --ack-local-tools --setup <token> (or re-run your original setup command with --ack-local-tools).`
1691
- });
1692
- } else {
1693
- const probe = await (deps.probeSignerTools ?? probeLocalMcpTools)(
1694
- sidecar.wrapper_path,
1695
- [],
1696
- MCP_RUNTIME_MANIFEST.requiredSignerTools
1697
- );
1698
- const experimental = probe.capabilities?.experimental ?? probe.capabilities;
1699
- const compat = experimental?.["haven/signer-compatibility"];
1700
- signerCapabilities = compat ? { "haven/signer-compatibility": compat } : void 0;
1701
- const compatDetail = compat ? ` Compat: x402 expected-context v${JSON.stringify(compat.x402_expected_context_versions ?? "?")}.` : "";
1702
- checks.push({
1703
- id: "signer_process",
1704
- label: "Signer stdio handshake",
1705
- ok: probe.status === "ok",
1706
- detail: probe.status === "ok" ? `Signer started, listed ${probe.toolNames?.length ?? 0} tools${probe.serverInfo?.version ? ` (v${probe.serverInfo.version})` : ""}.${compatDetail}` : `Handshake failed: ${probe.status}.`,
1707
- ...probe.status === "ok" ? {} : { repair: `Run: ${RERUN} --doctor --repair --runtime ${input.runtime}` }
1708
- });
1709
- }
1710
- } else {
1711
- checks.push({
1712
- id: "signer_process",
1713
- label: "Signer stdio handshake",
1714
- ok: false,
1715
- detail: "Skipped \u2014 no prepared signer runtime to probe.",
1716
- repair: `Run: ${RERUN} --doctor --repair --runtime ${input.runtime}`
1717
- });
1718
- }
1719
- return { checks, ...signerCapabilities ? { signerCapabilities } : {} };
1720
- }
1721
- async function runDoctor(input, deps = {}) {
1722
- const homeDir = deps.homeDir ?? os.homedir();
1723
- const checks = [];
1724
- let signerCapabilities;
1725
- const { directory, others } = await discoverCredentialDirectory(homeDir, input.credentialsDir);
1726
- const configPath = runtimeConfigPathFor(input.runtime, homeDir);
1727
- let configText = null;
1728
- if (configPath !== null) {
1729
- try {
1730
- configText = await promises.readFile(configPath, "utf8");
1731
- } catch {
1732
- configText = null;
1733
- }
1734
- }
1735
- const allDirectories = directory ? [directory, ...others] : others;
1736
- let bareOwnerExists = false;
1737
- for (const dir of allDirectories) {
1738
- const sidecar = await readRuntimeSidecar(dir);
1739
- if (!sidecar?.server_name && sidecar?.wrapper_path && configText?.includes(sidecar.wrapper_path)) {
1740
- bareOwnerExists = true;
1741
- break;
1742
- }
1743
- }
1744
- const inventory = [];
1745
- const capabilitiesByDirectory = /* @__PURE__ */ new Map();
1746
- const primaryChecksById = /* @__PURE__ */ new Map();
1747
- for (const dir of allDirectories) {
1748
- const identity = await readIdentity(dir);
1749
- const sidecar = await readRuntimeSidecar(dir);
1750
- const tombstone = await readAgentTombstone(dir);
1751
- const slug = sidecar?.server_name;
1752
- const names = serverNamesFor(slug);
1753
- if (!identity?.api_key) {
1754
- inventory.push({
1755
- ...slug ? { slug } : {},
1756
- ...tombstone?.agent_id ? { agentId: tombstone.agent_id } : {},
1757
- directory: dir,
1758
- classification: tombstone ? "retired" : "orphaned",
1759
- checks: []
1760
- });
1761
- continue;
1762
- }
1763
- const wired = agentIsWired(configText, names, slug, identity, sidecar, dir === directory, bareOwnerExists);
1764
- const entry = {
1765
- ...slug ? { slug } : {},
1766
- ...identity.agent_id ? { agentId: identity.agent_id } : {},
1767
- directory: dir,
1768
- classification: wired ? "wired" : "superseded",
1769
- checks: []
1770
- };
1771
- if (wired) {
1772
- const result = await checksForAgent({ directory: dir, identity, sidecar }, input, deps);
1773
- entry.checks = result.checks;
1774
- capabilitiesByDirectory.set(dir, result.signerCapabilities);
1775
- }
1776
- inventory.push(entry);
1777
- }
1778
- const wiredDirectories = inventory.filter((entry) => entry.classification === "wired").map((entry) => entry.directory);
1779
- const primaryDirectory = input.credentialsDir ? directory : wiredDirectories.includes(directory ?? "") ? directory : wiredDirectories[0] ?? directory;
1780
- if (primaryDirectory) {
1781
- const primaryEntry = inventory.find((entry) => entry.directory === primaryDirectory);
1782
- signerCapabilities = capabilitiesByDirectory.get(primaryDirectory);
1783
- for (const check of primaryEntry?.checks ?? []) primaryChecksById.set(check.id, check);
1784
- }
1785
- if (!primaryDirectory) {
1786
- checks.push({
1787
- id: "credentials",
1788
- label: "Agent credentials",
1789
- ok: false,
1790
- detail: "No agent credential directory with an identity.json under ~/.haven/agents.",
1791
- repair: `Run the full setup once: ${RERUN} --setup <token from the Haven dashboard>.`
1792
- });
1793
- } else {
1794
- const primaryIdentity = await readIdentity(primaryDirectory);
1795
- const primarySidecar = await readRuntimeSidecar(primaryDirectory);
1796
- if (primaryChecksById.size === 0) {
1797
- const result = await checksForAgent(
1798
- { directory: primaryDirectory, identity: primaryIdentity, sidecar: primarySidecar },
1799
- input,
1800
- deps
1801
- );
1802
- signerCapabilities = result.signerCapabilities;
1803
- for (const check of result.checks) primaryChecksById.set(check.id, check);
1804
- }
1805
- for (const id of ["credentials", "signer_runtime"]) {
1806
- const check = primaryChecksById.get(id);
1807
- if (check) checks.push(check);
1808
- }
1809
- }
1810
- if (configPath === null) {
1811
- checks.push({
1812
- id: "runtime_config",
1813
- label: "Runtime MCP config",
1814
- ok: true,
1815
- detail: `Runtime '${input.runtime}' has no file-based config the connector owns (CLI-managed) \u2014 skipping the file check.`
1816
- });
1817
- } else if (configText === null) {
1818
- checks.push({
1819
- id: "runtime_config",
1820
- label: "Runtime MCP config",
1821
- ok: false,
1822
- detail: `No runtime config at ${configPath}.`,
1823
- repair: `Run: ${RERUN} --doctor --repair --runtime ${input.runtime}`
1824
- });
1825
- } else {
1826
- const primaryIdentity = await readIdentity(primaryDirectory ?? "");
1827
- const primarySidecar = primaryDirectory ? await readRuntimeSidecar(primaryDirectory) : null;
1828
- const hasHaven = primaryIdentity?.hosted_mcp_url ? configText.includes(primaryIdentity.hosted_mcp_url) : configText.includes("haven");
1829
- const signerViaNpx = configText.includes("@haven_ai/signer");
1830
- const wrapperReferenced = primarySidecar ? configText.includes(primarySidecar.wrapper_path) : false;
1831
- const ok = hasHaven && !signerViaNpx && (primarySidecar ? wrapperReferenced : true);
1832
- checks.push({
1833
- id: "runtime_config",
1834
- label: "Runtime MCP config",
1835
- ok,
1836
- 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)" : ""}.`,
1837
- ...ok ? {} : { repair: `Run: ${RERUN} --doctor --repair --runtime ${input.runtime}` }
1838
- });
1839
- }
1840
- for (const id of ["hosted_mcp", "identity_match"]) {
1841
- const check = primaryChecksById.get(id);
1842
- if (check) checks.push(check);
1843
- }
1844
- const otherEntries = inventory.filter((entry) => entry.directory !== primaryDirectory);
1845
- if (otherEntries.length > 0) {
1846
- const live = [];
1847
- const revoked = [];
1848
- const unverifiable = [];
1849
- const retired = [];
1850
- for (const entry of otherEntries) {
1851
- const identity = await readIdentity(entry.directory);
1852
- const tombstone = await readAgentTombstone(entry.directory);
1853
- const otherAgent = identity?.agent_id ?? tombstone?.agent_id ?? path.basename(entry.directory);
1854
- const otherUrl = identity?.hosted_mcp_url ?? (identity?.api_url ? `${identity.api_url}/mcp` : void 0);
1855
- if (!identity?.api_key || !otherUrl) {
1856
- if (tombstone) retired.push(`${otherAgent} (retired ${tombstone.retired_at})`);
1857
- else unverifiable.push(`${otherAgent} (no stored key/URL to probe)`);
1858
- continue;
1859
- }
1860
- const suffix = tombstone ? " [tombstoned \u2014 key material still present]" : "";
1861
- const probe = await (deps.probeHosted ?? probeHostedMcpTools)(identity.api_key, otherUrl, deps.fetch);
1862
- if (probe.status === "ok") live.push({ label: `${otherAgent}${suffix}`, entry });
1863
- else if (probe.status === "unauthorized") revoked.push(`${otherAgent}${suffix}`);
1864
- else unverifiable.push(`${otherAgent} (${probe.status})${suffix}`);
1865
- }
1866
- const parts = [];
1867
- if (live.length > 0) parts.push(`STILL SPEND-CAPABLE: ${live.map((item) => item.label).join(", ")}`);
1868
- if (revoked.length > 0) parts.push(`already revoked: ${revoked.join(", ")}`);
1869
- if (retired.length > 0) parts.push(`tombstoned (keys removed): ${retired.join(", ")}`);
1870
- if (unverifiable.length > 0) parts.push(`could not verify: ${unverifiable.join(", ")}`);
1871
- const supersededLive = live.filter((item) => item.entry.classification !== "wired").map((item) => item.label);
1872
- checks.push({
1873
- id: "superseded_agents",
1874
- label: "Superseded agent credentials",
1875
- ok: supersededLive.length === 0,
1876
- 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("; ")}.`,
1877
- ...supersededLive.length > 0 ? {
1878
- 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.`
1879
- } : {}
1880
- });
1881
- }
1882
- const signerProcess = primaryChecksById.get("signer_process");
1883
- if (signerProcess) checks.push(signerProcess);
1884
- const restart = restartRequiredForRuntime(input.runtime, deps.env);
1885
- checks.push({
1886
- id: "restart",
1887
- label: "Runtime restart",
1888
- ok: true,
1889
- 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."
1890
- });
1891
- const wiredOk = inventory.filter((entry) => entry.classification === "wired").every((entry) => entry.checks.every((check) => check.ok));
1892
- return {
1893
- version: 1,
1894
- ok: checks.every((check) => check.ok) && wiredOk,
1895
- runtime: input.runtime,
1896
- credentialDirectory: primaryDirectory,
1897
- checks,
1898
- agents: inventory,
1899
- ...signerCapabilities ? { signerCapabilities } : {}
1900
- };
1901
- }
1902
- async function runRepair(input, deps = {}) {
1903
- const homeDir = deps.homeDir ?? os.homedir();
1904
- const messages = [];
1905
- const { directory, others } = await discoverCredentialDirectory(homeDir, input.credentialsDir);
1906
- if (others.length > 0) {
1907
- messages.push(`Note: ${others.length} other agent credential dir(s) exist \u2014 run --doctor for their status.`);
1908
- }
1909
- if (!directory) {
1910
- return {
1911
- ok: false,
1912
- messages: [`No agent credentials found to repair \u2014 run the full setup: ${RERUN} --setup <token>.`]
1913
- };
1914
- }
1915
- let identity;
1916
- try {
1917
- identity = JSON.parse(await promises.readFile(path.join(directory, "identity.json"), "utf8"));
1918
- } catch {
1919
- return { ok: false, messages: ["identity.json is unreadable \u2014 re-run the full setup with a fresh token."] };
1920
- }
1921
- if (!identity.api_key || !(identity.hosted_mcp_url || identity.api_url)) {
1922
- return { ok: false, messages: ["identity.json lacks the stored API key / hosted URL \u2014 re-run the full setup."] };
1923
- }
1924
- const configPath = runtimeConfigPathFor(input.runtime, homeDir);
1925
- if (configPath) {
1926
- try {
1927
- const existing = await promises.readFile(configPath, "utf8");
1928
- if (existing.includes("bin/haven-mcp") || existing.includes(".haven/mcp-runtime")) {
1929
- return {
1930
- ok: false,
1931
- messages: [
1932
- `The config at ${configPath} is the LOCAL-stdio topology (--local). Repair currently rewrites only the hosted+signer shape and will not touch it.`,
1933
- "Re-run your original setup command (with --local) to repair a local-stdio install."
1934
- ]
1935
- };
1936
- }
1937
- } catch {
1938
- }
1939
- }
1940
- const signerPath = path.join(directory, "signer.json");
1941
- const prepared = await prepareSignerRuntime(
1942
- { credentialDirectory: directory, signerPath, homeDir },
1943
- { runCommand: deps.runCommand }
1944
- );
1945
- messages.push(...prepared.messages);
1946
- const configResult = await writeRuntimeConfig({
1947
- runtime: input.runtime,
1948
- hostedMcpUrl: identity.hosted_mcp_url ?? `${identity.api_url}/mcp`,
1949
- apiKey: identity.api_key,
1950
- identityPath: path.join(directory, "identity.json"),
1951
- signerPath,
1952
- credentialDirectory: directory,
1953
- signerCommand: { command: prepared.command, args: prepared.args },
1954
- homeDir,
1955
- mode: "hosted"
1956
- });
1957
- messages.push(...configResult.messages);
1958
- messages.push("Repair complete \u2014 restart the runtime, then verify with --doctor.");
1959
- return { ok: true, messages };
1960
- }
1961
- var RERUN;
1962
- var init_doctor = __esm({
1963
- "src/doctor.ts"() {
1964
- init_runtime_manifest();
1965
- init_probes();
1966
- init_signer_runtime();
1967
- init_config_writers();
1968
- init_runtime_registry();
1969
- init_signer_consent();
1970
- init_tombstone();
1971
- init_server_names();
1972
- init_redact();
1973
- RERUN = "npx @haven_ai/connect@alpha";
1974
- }
1975
- });
1976
-
1977
- // src/api.ts
1978
- function createConnectApiClient(baseUrl, fetchImpl = fetch) {
1979
- const root = baseUrl.replace(/\/+$/, "");
1980
- return {
1981
- resolveSetup: (input) => request(fetchImpl, `${root}/agent-connection-setups/resolve`, {
1982
- method: "POST",
1983
- body: JSON.stringify({
1984
- setup_token: input.setupToken,
1985
- connector_version: input.connectorVersion,
1986
- runtime: input.runtime
1987
- })
1988
- }),
1989
- registerSetup: (input) => request(fetchImpl, `${root}/agent-connection-setups/register`, {
1990
- method: "POST",
1991
- body: JSON.stringify({
1992
- setup_token: input.setupToken,
1993
- challenge_id: input.challengeId,
1994
- delegate_address: input.delegateAddress,
1995
- proof_signature: input.proofSignature,
1996
- api_key_hash: input.apiKeyHash,
1997
- api_key_prefix: input.apiKeyPrefix,
1998
- runtime: input.runtime,
1999
- connector_version: input.connectorVersion,
2000
- connector_context: input.connectorContext,
2001
- install_capabilities: input.installCapabilities && {
2002
- can_write_runtime_config: input.installCapabilities.canWriteRuntimeConfig,
2003
- restart_required: input.installCapabilities.restartRequired
2004
- }
2005
- })
2006
- }),
2007
- getConnectorStatus: (setupId, apiKey) => request(fetchImpl, `${root}/agent-connection-setups/${encodeURIComponent(setupId)}/connector-status`, {
2008
- method: "GET",
2009
- headers: { Authorization: `Bearer ${apiKey}` }
2010
- }),
2011
- updateInstallStatus: async (setupId, apiKey, input) => {
2012
- await request(fetchImpl, `${root}/agent-connection-setups/${encodeURIComponent(setupId)}/install-status`, {
2013
- method: "POST",
2014
- headers: { Authorization: `Bearer ${apiKey}` },
2015
- body: JSON.stringify({
2016
- runtime: input.runtime,
2017
- connector_version: input.connectorVersion,
2018
- runtime_mcp_mode: input.runtimeMcpMode,
2019
- hosted_mcp_configured: input.hostedMcpConfigured,
2020
- local_signer_configured: input.localSignerConfigured,
2021
- local_mcp_configured: input.localMcpConfigured,
2022
- credential_files_written: input.credentialFilesWritten,
2023
- signer_acknowledged: input.signerAcknowledged,
2024
- local_mcp_acknowledged: input.localMcpAcknowledged,
2025
- activation_command_available: input.activationCommandAvailable,
2026
- skill_installed: input.skillInstalled,
2027
- probe_result: input.probeResult,
2028
- restart_required: input.restartRequired,
2029
- next_user_action: input.nextUserAction,
2030
- error_code: input.errorCode ?? null,
2031
- environment_label: input.environmentLabel
2032
- })
2033
- });
2034
- }
2035
- };
2036
- }
2037
- var ConnectRequestError = class extends Error {
2038
- constructor(message, status) {
2039
- super(message);
2040
- this.status = status;
2041
- this.name = "ConnectRequestError";
2042
- }
2043
- status;
2044
- };
2045
- async function request(fetchImpl, url, init) {
2046
- const response = await fetchImpl(url, {
2047
- ...init,
2048
- headers: {
2049
- "Content-Type": "application/json",
2050
- ...init.headers ?? {}
2051
- }
2052
- });
2053
- const text = await response.text();
2054
- const body = text ? JSON.parse(text) : null;
2055
- if (!response.ok) {
2056
- const message = body?.error ?? body?.message ?? `${response.status} ${response.statusText}`;
2057
- throw new ConnectRequestError(`Haven setup request failed: ${message}`, response.status);
2058
- }
2059
- return body;
2060
- }
2061
- function generateDelegateKey() {
2062
- return delegateKeyFromPrivateKey(ethers.Wallet.createRandom().privateKey);
2063
- }
2064
- function delegateKeyFromPrivateKey(privateKey) {
2065
- const wallet = new ethers.Wallet(privateKey);
2066
- return {
2067
- privateKey: wallet.privateKey,
2068
- address: wallet.address,
2069
- signChallenge: (message) => wallet.signMessage(message)
2070
- };
2071
- }
2072
- function generateAgentApiKey() {
2073
- return `sk_agent_${crypto__default.default.randomBytes(24).toString("hex")}`;
2074
- }
2075
- function hashAgentApiKey(apiKey) {
2076
- return crypto__default.default.createHash("sha256").update(apiKey).digest("hex");
2077
- }
2078
- function agentApiKeyPrefix(apiKey) {
2079
- return apiKey.slice(0, 12);
2080
- }
2081
-
2082
- // src/runtime.ts
2083
- init_redact();
2084
- init_server_names();
2085
- async function preflightCredentialStorage(input = {}) {
2086
- const directory = defaultCredentialRoot(input.baseDir);
2087
- await promises.mkdir(directory, { recursive: true, mode: 448 });
2088
- await restrictPermissions(directory, 448, input.warn);
2089
- const probePath = path.join(directory, `.haven-connect-preflight-${crypto__default.default.randomBytes(8).toString("hex")}`);
2090
- try {
2091
- await writeOwnerOnlyJson(probePath, { ok: true }, input.warn);
2092
- } finally {
2093
- await promises.rm(probePath, { force: true }).catch(() => void 0);
2094
- }
2095
- return directory;
2096
- }
2097
- async function writeCredentialFiles(input) {
2098
- const directory = defaultAgentDirectory(input.serverName ?? input.agentId, input.baseDir);
2099
- await promises.mkdir(directory, { recursive: true, mode: 448 });
2100
- await restrictPermissions(directory, 448, input.warn);
2101
- const identityPath = path.join(directory, "identity.json");
2102
- const signerPath = path.join(directory, "signer.json");
2103
- const agentPath = path.join(directory, "agent.json");
2104
- await assertDoesNotExist(identityPath);
2105
- await assertDoesNotExist(signerPath);
2106
- await assertDoesNotExist(agentPath);
2107
- await writeOwnerOnlyJson(
2108
- signerPath,
2109
- {
2110
- delegate_key: input.delegateKey,
2111
- delegate_address: input.delegateAddress,
2112
- agent_id: input.agentId,
2113
- safe_address: input.safeAddress,
2114
- chain_id: input.chainId,
2115
- network: input.network,
2116
- x402_binding_signer: input.x402BindingSigner,
2117
- note: "Local signer credential. Haven backend never receives this private key."
2118
- },
2119
- input.warn
2120
- );
2121
- try {
2122
- await writeOwnerOnlyJson(
2123
- identityPath,
2124
- {
2125
- api_key: input.apiKey,
2126
- agent_id: input.agentId,
2127
- safe_address: input.safeAddress,
2128
- chain_id: input.chainId,
2129
- network: input.network,
2130
- api_url: input.apiUrl,
2131
- hosted_mcp_url: input.hostedMcpUrl,
2132
- agent_budget: input.agentBudget,
2133
- note: "Haven API key identifies the agent only. It cannot spend without the local signer key and on-chain Haven wallet rules."
2134
- },
2135
- input.warn
2136
- );
2137
- } catch (err) {
2138
- await promises.rm(signerPath, { force: true }).catch(() => void 0);
2139
- throw err;
2140
- }
2141
- try {
2142
- await writeOwnerOnlyJson(
2143
- agentPath,
2144
- {
2145
- agent_id: input.agentId,
2146
- delegate_address: input.delegateAddress,
2147
- safe_address: input.safeAddress,
2148
- chain_id: input.chainId,
2149
- network: input.network,
2150
- agent_budget: input.agentBudget,
2151
- 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."
2152
- },
2153
- input.warn
2154
- );
2155
- } catch (err) {
2156
- await promises.rm(signerPath, { force: true }).catch(() => void 0);
2157
- await promises.rm(identityPath, { force: true }).catch(() => void 0);
2158
- await promises.rm(agentPath, { force: true }).catch(() => void 0);
2159
- throw err;
2160
- }
2161
- return { directory, identityPath, signerPath, agentPath };
2162
- }
2163
- async function assertServerSlugAvailable(serverName, baseDir) {
2164
- const directory = defaultAgentDirectory(serverName, baseDir);
2165
- try {
2166
- await promises.stat(path.join(directory, "identity.json"));
2167
- } catch {
2168
- return;
2169
- }
2170
- throw new Error(
2171
- `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.`
2172
- );
2173
- }
2174
- function defaultAgentDirectory(agentId, baseDir = path.join(os.homedir(), ".haven", "agents")) {
2175
- return path.resolve(defaultCredentialRoot(baseDir), safePathPart(agentId));
2176
- }
2177
- function defaultCredentialRoot(baseDir = path.join(os.homedir(), ".haven", "agents")) {
2178
- return path.resolve(baseDir);
2179
- }
2180
- async function writeOwnerOnlyJson(path, value, warn) {
2181
- const json = JSON.stringify(dropUndefined(value), null, 2);
2182
- await promises.writeFile(path, `${json}
2183
- `, { mode: 384, flag: "wx" });
2184
- await restrictPermissions(path, 384, warn);
2185
- }
2186
- function safePathPart(value) {
2187
- return value.replace(/[^A-Za-z0-9_.-]/g, "_");
2188
- }
2189
- function dropUndefined(value) {
2190
- return Object.fromEntries(Object.entries(value).filter(([, field]) => field !== void 0));
2191
- }
2192
- async function assertDoesNotExist(path) {
2193
- try {
2194
- await promises.access(path);
2195
- } catch (err) {
2196
- if (err && typeof err === "object" && "code" in err && err.code === "ENOENT") return;
2197
- throw err;
2198
- }
2199
- throw new Error(`Refusing to overwrite existing Haven credential file: ${path}`);
2370
+ progress("Almost there \u2014 just confirming everything connects\u2026");
2371
+ const localProbePromise = configResult.runtimeMcpMode === "local_stdio" && localRuntimeInstall ? runLocalMcpProbe(localRuntimeInstall, deps) : Promise.resolve(void 0);
2372
+ const signerProbePromise = configResult.runtimeMcpMode !== "local_stdio" && signerCommand ? (deps.probeSignerTools ?? probeLocalMcpTools)(
2373
+ signerCommand.command,
2374
+ signerCommand.args,
2375
+ MCP_RUNTIME_MANIFEST.requiredSignerTools
2376
+ ) : Promise.resolve(void 0);
2377
+ const [hostedProbe, signerCredentialReady, localMcpProbe, signerProbe] = await Promise.all([
2378
+ configResult.hostedConfigured ? probeHostedMcpTools(input.apiKey, input.hostedMcpUrl, deps.fetch) : Promise.resolve({ status: "bad_response" }),
2379
+ probeLocalSignerCredential(input.signerPath),
2380
+ localProbePromise,
2381
+ signerProbePromise
2382
+ ]);
2383
+ const hostedOk = configResult.hostedConfigured && hostedProbe.status === "ok";
2384
+ const localMcpOk = configResult.runtimeMcpMode === "local_stdio" && configResult.localMcpConfigured && signerCredentialReady && Boolean(localMcpConsent?.acknowledged) && localMcpProbe?.status === "ok";
2385
+ const signerOk = configResult.runtimeMcpMode === "local_stdio" ? localMcpOk : configResult.signerConfigured && signerCredentialReady && Boolean(signerConsent?.acknowledged) && // #1587: no handshake, no green. A signer command that was registered
2386
+ // but not probed (manual topology) keeps the old semantics.
2387
+ (signerProbe === void 0 || signerProbe.status === "ok");
2388
+ const restartRequired = configResult.restartRequired || restartRequiredForRuntime(runtime, deps.env);
2389
+ const errorCode = configResult.errorCode ?? (configResult.runtimeMcpMode === "local_stdio" ? localMcpErrorCode(signerCredentialReady, localMcpConsent, localMcpProbe?.status) : hostedMcpErrorCode(configResult.hostedConfigured, hostedProbe.status) ?? signerConsentErrorCode(signerCredentialReady, signerConsent) ?? signerProbeErrorCode(signerProbe));
2390
+ 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."] : [];
2391
+ const signerProbeMessages = signerProbe ? signerProbe.status === "ok" ? ["Verified local Haven signer with a stdio handshake."] : [
2392
+ `Local Haven signer handshake failed: ${signerProbe.status}.`,
2393
+ "Re-run `npx @haven_ai/connect@alpha` to repair the signer setup."
2394
+ ] : [];
2395
+ 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."] : [];
2396
+ const skillInstall = !configResult.errorCode ? await installSkillForRuntime(runtime, { homeDir: deps.homeDir, env: deps.env }) : void 0;
2397
+ return {
2398
+ runtime,
2399
+ runtimeMcpMode: configResult.runtimeMcpMode,
2400
+ hostedMcpConfigured: hostedOk,
2401
+ localSignerConfigured: signerOk,
2402
+ localMcpConfigured: localMcpOk,
2403
+ probeResult: buildProbeResult(configResult.runtimeMcpMode, configResult.hostedConfigured, hostedProbe.status, signerOk, localMcpOk, localMcpProbe?.status),
2404
+ restartRequired,
2405
+ nextUserAction: nextAction(runtime, profile.restartMode, errorCode),
2406
+ errorCode,
2407
+ configTarget: configResult.target,
2408
+ signerAcknowledged: signerConsent?.acknowledged,
2409
+ localMcpAcknowledged: localMcpConsent?.acknowledged,
2410
+ activationCommand: configResult.activationCommand,
2411
+ skillInstalled: skillInstall?.installed,
2412
+ signerRuntimePrepared,
2413
+ messages: [...consentMessages, ...localRuntimeInstall?.messages ?? [], ...configResult.messages, ...hostedProbeMessages, ...signerProbeMessages, ...localProbeMessages, ...skillInstall?.messages ?? []]
2414
+ };
2200
2415
  }
2201
- async function restrictPermissions(path, mode, warn) {
2202
- try {
2203
- await promises.chmod(path, mode);
2204
- } catch (err) {
2205
- warn?.(
2206
- `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)}`
2207
- );
2208
- }
2416
+ function runtimeInstallCapabilities(runtime, env = process.env) {
2417
+ const profile = runtimeProfile(runtime, env);
2418
+ return {
2419
+ canWriteRuntimeConfig: profile.canWriteRuntimeConfig,
2420
+ restartRequired: restartRequiredForRuntime(runtime, env)
2421
+ };
2209
2422
  }
2210
-
2211
- // src/runtime-install.ts
2212
- init_config_writers();
2213
- init_server_names();
2214
- async function acknowledgeLocalMcpConsent(identityPath, signerPath, log) {
2423
+ async function configureClaudeCode(deps, localMcpCommand, serverName) {
2424
+ const runCommand = deps.runCommand ?? defaultRunCommand;
2425
+ const serverJson = JSON.stringify({
2426
+ type: "stdio",
2427
+ command: localMcpCommand,
2428
+ args: [],
2429
+ env: {}
2430
+ });
2215
2431
  try {
2216
- const input = await buildLocalMcpConsentInput(identityPath, signerPath);
2217
- const decision = await mcp.ensureConsent(input, {
2218
- credentialsPath: identityPath,
2219
- writeAck: true,
2220
- out: log ? { write: (chunk) => writeLogChunk(log, chunk) } : void 0
2432
+ if (!localMcpCommand) throw new Error("local MCP wrapper command is required");
2433
+ const names = serverNamesFor(serverName);
2434
+ await runCommand("claude", ["mcp", "remove", names.hosted]).catch(() => void 0);
2435
+ await runCommand("claude", ["mcp", "remove", names.signer]).catch(() => void 0);
2436
+ await runCommand("claude", ["mcp", "add-json", names.hosted, serverJson, "--scope", "user"]).catch(async () => {
2437
+ await runCommand("claude", ["mcp", "add", names.hosted, "--scope", "user", "--", localMcpCommand]);
2221
2438
  });
2439
+ const verified = await runCommand("claude", ["mcp", "get", names.hosted]).then(() => true).catch(() => false);
2222
2440
  return {
2223
- acknowledged: decision.ok,
2224
- hash: decision.hash,
2225
- reason: decision.reason
2441
+ hostedConfigured: false,
2442
+ signerConfigured: true,
2443
+ localMcpConfigured: true,
2444
+ runtimeMcpMode: "local_stdio",
2445
+ target: "Claude Code MCP config",
2446
+ changed: true,
2447
+ restartRequired: true,
2448
+ messages: [
2449
+ "Updated local Haven MCP entry with Claude Code.",
2450
+ ...verified ? ["Verified Claude Code MCP entry."] : []
2451
+ ]
2226
2452
  };
2227
2453
  } catch (err) {
2228
2454
  return {
2229
- acknowledged: false,
2230
- error: err instanceof Error ? err.message : String(err)
2455
+ hostedConfigured: false,
2456
+ signerConfigured: false,
2457
+ localMcpConfigured: false,
2458
+ runtimeMcpMode: "local_stdio",
2459
+ target: "Claude Code MCP config",
2460
+ changed: false,
2461
+ restartRequired: true,
2462
+ messages: [
2463
+ `Could not update Claude Code MCP config: ${err instanceof Error ? err.message : String(err)}`,
2464
+ "Install Claude Code or rerun the Haven setup command inside a Claude Code terminal."
2465
+ ],
2466
+ errorCode: "claude_code_config_failed"
2231
2467
  };
2232
2468
  }
2233
2469
  }
2234
- async function getLocalMcpConsentStatus(identityPath, signerPath) {
2470
+ async function writeHostedRuntimeConfig(deps, input, signerCommand) {
2471
+ if (input.runtime === "claude-code") {
2472
+ return configureClaudeCodeHosted(deps, input, signerCommand);
2473
+ }
2474
+ return writeRuntimeConfig({
2475
+ runtime: input.runtime,
2476
+ hostedMcpUrl: input.hostedMcpUrl,
2477
+ apiKey: input.apiKey,
2478
+ identityPath: input.identityPath,
2479
+ signerPath: input.signerPath,
2480
+ serverName: input.serverName,
2481
+ credentialDirectory: input.credentialDirectory,
2482
+ signerCommand,
2483
+ homeDir: deps.homeDir,
2484
+ mode: "hosted"
2485
+ });
2486
+ }
2487
+ async function configureClaudeCodeHosted(deps, input, signerCommand) {
2488
+ const runCommand = deps.runCommand ?? defaultRunCommand;
2489
+ const hostedJson = JSON.stringify({
2490
+ type: "http",
2491
+ url: input.hostedMcpUrl,
2492
+ headers: { Authorization: `Bearer ${input.apiKey}` }
2493
+ });
2494
+ const signerJson = JSON.stringify({
2495
+ type: "stdio",
2496
+ command: signerCommand?.command ?? "npx",
2497
+ args: signerCommand?.args ?? ["-y", signerPackageSpec(), "--credentials", input.signerPath],
2498
+ env: {}
2499
+ });
2235
2500
  try {
2236
- const input = await buildLocalMcpConsentInput(identityPath, signerPath);
2237
- const hash = mcp.computeConsentHash(input);
2238
- const stored = await readLocalMcpAckFile(localMcpAckPath(identityPath));
2239
- if (stored === hash) {
2240
- return { acknowledged: true, hash, reason: "ack_file_match" };
2241
- }
2501
+ const names = serverNamesFor(input.serverName);
2502
+ await runCommand("claude", ["mcp", "remove", names.hosted]).catch(() => void 0);
2503
+ await runCommand("claude", ["mcp", "remove", names.signer]).catch(() => void 0);
2504
+ await runCommand("claude", ["mcp", "add-json", names.hosted, hostedJson, "--scope", "user"]);
2505
+ await runCommand("claude", ["mcp", "add-json", names.signer, signerJson, "--scope", "user"]);
2506
+ const verified = await runCommand("claude", ["mcp", "get", names.hosted]).then(() => true).catch(() => false);
2242
2507
  return {
2243
- acknowledged: false,
2244
- hash,
2245
- reason: stored ? "ack_file_mismatch" : "ack_file_missing"
2508
+ hostedConfigured: true,
2509
+ signerConfigured: true,
2510
+ localMcpConfigured: false,
2511
+ runtimeMcpMode: "hosted_plus_signer",
2512
+ target: "Claude Code MCP config",
2513
+ changed: true,
2514
+ restartRequired: true,
2515
+ messages: [
2516
+ "Updated hosted Haven MCP and local signer entries with Claude Code.",
2517
+ ...verified ? ["Verified Claude Code MCP entry."] : []
2518
+ ]
2246
2519
  };
2247
2520
  } catch (err) {
2248
2521
  return {
2249
- acknowledged: false,
2250
- error: err instanceof Error ? err.message : String(err)
2522
+ hostedConfigured: false,
2523
+ signerConfigured: false,
2524
+ localMcpConfigured: false,
2525
+ runtimeMcpMode: "hosted_plus_signer",
2526
+ target: "Claude Code MCP config",
2527
+ changed: false,
2528
+ restartRequired: true,
2529
+ messages: [
2530
+ `Could not update Claude Code MCP config: ${err instanceof Error ? err.message : String(err)}`,
2531
+ "Install Claude Code or rerun the Haven setup command inside a Claude Code terminal."
2532
+ ],
2533
+ errorCode: "claude_code_config_failed"
2251
2534
  };
2252
2535
  }
2253
2536
  }
2254
- function localMcpAckPath(identityPath) {
2255
- return path.resolve(`${identityPath}.ack.json`);
2537
+ async function defaultRunCommand(command, args) {
2538
+ await execFileAsync3(command, args, { timeout: 1e4 });
2539
+ }
2540
+ function buildProbeResult(mode, hostedConfigured, hostedStatus, signerReady, localMcpReady, localMcpProbeStatus) {
2541
+ if (mode === "local_stdio") {
2542
+ if (localMcpReady) return "local_stdio_mcp_ready";
2543
+ return localMcpProbeStatus ? `local_stdio_mcp_${localMcpProbeStatus}` : "local_stdio_mcp_unavailable";
2544
+ }
2545
+ const hostedPart = hostedConfigured ? `hosted_${hostedStatus}` : "hosted_not_configured";
2546
+ const signerPart = signerReady ? "local_signer_ready" : "local_signer_unavailable";
2547
+ return `${hostedPart}_${signerPart}`.slice(0, 120);
2548
+ }
2549
+ async function resolveLocalMcpConsent(input, messages) {
2550
+ if (input.ackLocalTools || input.ackSigner) {
2551
+ const status = await acknowledgeLocalMcpConsent(input.identityPath, input.signerPath, (message) => messages.push(message));
2552
+ if (status.acknowledged) {
2553
+ messages.push("Prepared the local Haven tools acknowledgement.");
2554
+ } else {
2555
+ messages.push("Local Haven tools acknowledgement still needs attention.");
2556
+ }
2557
+ return status;
2558
+ }
2559
+ return getLocalMcpConsentStatus(input.identityPath, input.signerPath);
2560
+ }
2561
+ async function resolveSignerConsent(input, messages) {
2562
+ if (input.ackSigner || input.ackLocalTools) {
2563
+ const status = await acknowledgeLocalSignerConsent(input.signerPath, (message) => messages.push(message));
2564
+ if (status.acknowledged) {
2565
+ messages.push("Prepared the local Haven signer acknowledgement.");
2566
+ } else {
2567
+ messages.push("Local Haven signer acknowledgement still needs attention.");
2568
+ }
2569
+ return status;
2570
+ }
2571
+ return getLocalSignerConsentStatus(input.signerPath);
2572
+ }
2573
+ function signerConsentErrorCode(signerCredentialReady, signerConsent) {
2574
+ if (!signerCredentialReady) return "local_signer_credential_unavailable";
2575
+ if (!signerConsent?.acknowledged) return "local_signer_ack_required";
2576
+ return void 0;
2577
+ }
2578
+ function signerProbeErrorCode(probe) {
2579
+ if (!probe || probe.status === "ok") return void 0;
2580
+ return `local_signer_probe_${probe.status}`;
2256
2581
  }
2257
- async function buildLocalMcpConsentInput(identityPath, signerPath) {
2258
- const credentials = await mcp.loadCredentials({ identityPath, signerPath });
2259
- const unavailableDuringSetup = {
2260
- getAllowances: async () => {
2261
- throw new Error("Haven approval is not complete yet.");
2262
- }
2263
- };
2264
- return mcp.consentInputFromClient(
2265
- unavailableDuringSetup,
2266
- {
2267
- apiKey: credentials.apiKey,
2268
- apiUrl: credentials.apiUrl,
2269
- agentId: credentials.agentId,
2270
- safeAddress: credentials.safeAddress,
2271
- delegateAddress: credentials.delegateAddress,
2272
- chainId: credentials.chainId,
2273
- allowanceSummary: credentials.allowanceSummary
2274
- },
2275
- mcp.registeredToolNames()
2276
- );
2582
+ function hostedMcpErrorCode(hostedConfigured, hostedProbeStatus) {
2583
+ if (!hostedConfigured || hostedProbeStatus === "ok") return void 0;
2584
+ return `hosted_mcp_probe_${hostedProbeStatus}`;
2277
2585
  }
2278
- async function readLocalMcpAckFile(path) {
2279
- try {
2280
- const parsed = JSON.parse(await promises.readFile(path, "utf8"));
2281
- return typeof parsed.ack === "string" ? parsed.ack : null;
2282
- } catch {
2283
- return null;
2284
- }
2586
+ function localMcpErrorCode(signerCredentialReady, localMcpConsent, localMcpProbeStatus) {
2587
+ if (!signerCredentialReady) return "local_signer_credential_unavailable";
2588
+ if (!localMcpConsent?.acknowledged) return "local_mcp_ack_required";
2589
+ if (localMcpProbeStatus && localMcpProbeStatus !== "ok") return `local_mcp_probe_${localMcpProbeStatus}`;
2590
+ return void 0;
2285
2591
  }
2286
- function writeLogChunk(log, chunk) {
2287
- const message = String(chunk).trimEnd();
2288
- if (message) log(message);
2592
+ function nextAction(runtime, restartMode, errorCode) {
2593
+ if (errorCode) return "return_to_haven_for_wallet_approval_then_finish_runtime_setup";
2594
+ if (restartMode === "hot-reload") return "return_to_haven_for_wallet_approval";
2595
+ if (runtime === "codex-cli" || runtime === "codex-desktop") return "return_to_haven_for_wallet_approval_then_restart_codex";
2596
+ if (runtime === "claude-code") return "return_to_haven_for_wallet_approval_then_restart_claude_code";
2597
+ if (restartMode === "restart-app") return "return_to_haven_for_wallet_approval_then_restart_app";
2598
+ if (restartMode === "restart-session") return "return_to_haven_for_wallet_approval_then_restart_agent_session";
2599
+ return "return_to_haven_for_wallet_approval_then_configure_runtime";
2289
2600
  }
2290
-
2291
- // src/runtime-install.ts
2292
- init_probes();
2293
-
2294
- // src/local-mcp-runtime.ts
2295
- init_signer_runtime();
2296
- init_runtime_manifest();
2297
- var execFileAsync2 = util.promisify(child_process.execFile);
2298
- var UnsupportedNodeVersionError = class extends Error {
2299
- code = "local_mcp_unsupported_node_version";
2300
- nodeVersion;
2301
- minimumNodeVersion;
2302
- constructor(nodeVersion, minimumNodeVersion, subject = "Haven setup") {
2303
- super(sdk.unsupportedNodeVersionMessage({ subject, nodeVersion, minimumNodeVersion }));
2304
- this.name = "UnsupportedNodeVersionError";
2305
- this.nodeVersion = nodeVersion;
2306
- this.minimumNodeVersion = minimumNodeVersion;
2307
- }
2308
- };
2309
- async function prepareLocalMcpRuntime(input, deps = {}) {
2310
- assertSupportedNodeVersion(input.nodeVersion);
2311
- const homeDir = input.homeDir ?? os.homedir();
2312
- const runtimeDirectory = path.resolve(homeDir, ".haven", "mcp-runtime", MCP_RUNTIME_MANIFEST.mcpVersion);
2313
- const npmCacheDirectory = path.resolve(homeDir, ".haven", "npm-cache");
2314
- const cliPath = path.join(runtimeDirectory, "node_modules", "@haven_ai", "mcp", "dist", "cli.js");
2315
- const messages = [];
2316
- await promises.mkdir(runtimeDirectory, { recursive: true, mode: 448 });
2317
- await promises.chmod(runtimeDirectory, 448).catch(() => void 0);
2318
- await promises.mkdir(npmCacheDirectory, { recursive: true, mode: 448 });
2319
- await promises.chmod(npmCacheDirectory, 448).catch(() => void 0);
2320
- if (await installedRuntimeMatches2(runtimeDirectory, cliPath)) {
2321
- messages.push(`Using existing local Haven MCP runtime ${mcpPackageSpec()}.`);
2322
- } else {
2323
- await installRuntimePackages2(runtimeDirectory, npmCacheDirectory, deps);
2324
- messages.push(`Installed local Haven MCP runtime ${mcpPackageSpec()}.`);
2325
- }
2326
- await assertFileExists2(cliPath, "local Haven MCP CLI");
2327
- const wrapperPath = path.join(input.credentialDirectory, "bin", "haven-mcp");
2328
- await writeWrapper2({
2329
- wrapperPath,
2330
- cliPath,
2601
+ function supportsLocalMcp(runtime) {
2602
+ return runtime === "codex-cli" || runtime === "codex-desktop" || runtime === "claude-code";
2603
+ }
2604
+ async function prepareRuntimeForLocalMcp(input, deps) {
2605
+ const prepare = deps.prepareLocalMcpRuntime ?? ((runtimeInput) => prepareLocalMcpRuntime(runtimeInput, { runCommand: deps.runCommand, onProgress: deps.onProgress }));
2606
+ return prepare({
2607
+ credentialDirectory: input.credentialDirectory,
2331
2608
  identityPath: input.identityPath,
2332
- signerPath: input.signerPath
2333
- });
2334
- await writeRuntimeSidecar2({
2335
- path: path.join(input.credentialDirectory, "mcp-runtime.json"),
2336
- wrapperPath,
2337
- runtimeDirectory,
2338
- npmCacheDirectory,
2339
- cliPath,
2609
+ signerPath: input.signerPath,
2610
+ homeDir: deps.homeDir,
2340
2611
  serverName: input.serverName
2341
2612
  });
2342
- messages.push(`Prepared stable local Haven MCP wrapper: ${wrapperPath}`);
2343
- return {
2344
- command: wrapperPath,
2345
- args: [],
2346
- wrapperPath,
2347
- runtimeDirectory,
2348
- npmCacheDirectory,
2349
- cliPath,
2350
- messages
2351
- };
2352
2613
  }
2353
- function assertSupportedNodeVersion(nodeVersion = process.versions.node, minimumNodeVersion = MCP_RUNTIME_MANIFEST.minimumNodeVersion, subject = "Haven setup") {
2354
- if (!sdk.isSupportedNodeVersion(nodeVersion, minimumNodeVersion)) {
2355
- throw new UnsupportedNodeVersionError(nodeVersion, minimumNodeVersion, subject);
2356
- }
2614
+ async function prepareSignerForRuntime(input, deps) {
2615
+ const prepare = deps.prepareSignerRuntime ?? ((runtimeInput) => (
2616
+ // onProgress threaded through on purpose (#1586 review): without it the
2617
+ // install heartbeat was dead code in production and the console still
2618
+ // went silent for the whole cold install — the exact symptom the issue
2619
+ // set out to remove, at a longer timeout.
2620
+ prepareSignerRuntime(runtimeInput, { runCommand: deps.runCommand, onProgress: deps.onProgress })
2621
+ ));
2622
+ return prepare({
2623
+ credentialDirectory: input.credentialDirectory,
2624
+ signerPath: input.signerPath,
2625
+ homeDir: deps.homeDir,
2626
+ serverName: input.serverName
2627
+ });
2357
2628
  }
2358
- async function installRuntimePackages2(runtimeDirectory, npmCacheDirectory, deps) {
2359
- const { runCommand, onProgress } = deps;
2360
- const baseArgs = [
2361
- "install",
2362
- "--prefix",
2363
- runtimeDirectory,
2364
- "--no-audit",
2365
- "--no-fund",
2366
- "--omit=dev",
2367
- "--prefer-offline",
2368
- mcpPackageSpec(),
2369
- sdkPackageSpec()
2370
- ];
2371
- const run = async (args) => {
2372
- const startedAt = Date.now();
2373
- const heartbeat = setInterval(() => {
2374
- const seconds = Math.round((Date.now() - startedAt) / 1e3);
2375
- onProgress?.(`Still installing the local Haven MCP runtime\u2026 (${seconds}s \u2014 a cold cache can take several minutes)`);
2376
- }, SIGNER_INSTALL_HEARTBEAT_MS);
2377
- heartbeat.unref?.();
2378
- try {
2379
- if (runCommand) await runCommand("npm", args);
2380
- else await execFileAsync2("npm", args, { timeout: SIGNER_INSTALL_TIMEOUT_MS, maxBuffer: 1024 * 1024 });
2381
- } finally {
2382
- clearInterval(heartbeat);
2383
- }
2384
- };
2629
+ async function runLocalMcpProbe(runtimeInstall, deps) {
2630
+ const probe = deps.probeLocalMcpTools ?? probeLocalMcpTools;
2385
2631
  try {
2386
- await run(baseArgs);
2632
+ return await probe(runtimeInstall.command, runtimeInstall.args, MCP_RUNTIME_MANIFEST.requiredTools);
2387
2633
  } catch {
2388
- try {
2389
- await run([...baseArgs, "--cache", npmCacheDirectory]);
2390
- } catch (err) {
2391
- throw new Error(`Could not install local Haven MCP runtime ${mcpPackageSpec()}: ${err instanceof Error ? err.message : String(err)}`);
2392
- }
2634
+ return { status: "process_error" };
2393
2635
  }
2394
2636
  }
2395
- async function installedRuntimeMatches2(runtimeDirectory, cliPath) {
2396
- try {
2397
- await assertFileExists2(cliPath, "local Haven MCP CLI");
2398
- const [mcpPackage, sdkPackage] = await Promise.all([
2399
- readPackageJson2(path.join(runtimeDirectory, "node_modules", "@haven_ai", "mcp", "package.json")),
2400
- readPackageJson2(path.join(runtimeDirectory, "node_modules", "@haven_ai", "sdk", "package.json"))
2401
- ]);
2402
- return mcpPackage.version === MCP_RUNTIME_MANIFEST.mcpVersion && sdkPackage.version === MCP_RUNTIME_MANIFEST.sdkVersion;
2403
- } catch {
2404
- return false;
2637
+ function localRuntimePrepareErrorCode(err) {
2638
+ if (err && typeof err === "object" && "code" in err && err.code === "local_mcp_unsupported_node_version") {
2639
+ return "local_mcp_unsupported_node_version";
2405
2640
  }
2641
+ return "local_mcp_runtime_install_failed";
2406
2642
  }
2407
- async function readPackageJson2(path) {
2408
- return JSON.parse(await promises.readFile(path, "utf8"));
2409
- }
2410
- async function writeWrapper2(input) {
2411
- await promises.mkdir(path.dirname(input.wrapperPath), { recursive: true, mode: 448 });
2412
- await promises.chmod(path.dirname(input.wrapperPath), 448).catch(() => void 0);
2413
- const source = [
2414
- "#!/usr/bin/env node",
2415
- "import { spawn } from 'node:child_process'",
2643
+ var execFileAsync3;
2644
+ var init_runtime_install = __esm({
2645
+ "src/runtime-install.ts"() {
2646
+ init_config_writers();
2647
+ init_server_names();
2648
+ init_local_mcp_consent();
2649
+ init_probes();
2650
+ init_local_mcp_runtime();
2651
+ init_signer_runtime();
2652
+ init_runtime_manifest();
2653
+ init_skill_install();
2654
+ init_runtime_registry();
2655
+ init_signer_consent();
2656
+ execFileAsync3 = util.promisify(child_process.execFile);
2657
+ }
2658
+ });
2659
+
2660
+ // src/tombstone.ts
2661
+ var tombstone_exports = {};
2662
+ __export(tombstone_exports, {
2663
+ TOMBSTONE_FILENAME: () => TOMBSTONE_FILENAME,
2664
+ TOMBSTONE_MARKER: () => TOMBSTONE_MARKER,
2665
+ readAgentTombstone: () => readAgentTombstone,
2666
+ writeAgentTombstone: () => writeAgentTombstone
2667
+ });
2668
+ function tombstoneScript(info) {
2669
+ const lines = [
2670
+ `${TOMBSTONE_MARKER}: this Haven agent was retired.`,
2416
2671
  "",
2417
- `const cliPath = ${JSON.stringify(input.cliPath)}`,
2418
- `const identityPath = ${JSON.stringify(input.identityPath)}`,
2419
- `const signerPath = ${JSON.stringify(input.signerPath)}`,
2672
+ ` agent: ${info.agent_id}`,
2673
+ ` retired at: ${info.retired_at}`,
2674
+ ` reason: ${info.reason}`,
2675
+ ...info.replaced_by ? [` replaced by: ${info.replaced_by}`] : [],
2420
2676
  "",
2421
- "const child = spawn(process.execPath, [cliPath, '--identity', identityPath, '--signer', signerPath, ...process.argv.slice(2)], {",
2422
- " stdio: 'inherit',",
2423
- "})",
2677
+ "This process is running with a wiring snapshot that predates the",
2678
+ "retirement \u2014 it loaded its MCP config at startup and has kept it since.",
2679
+ "Restart THIS host to pick up the current wiring. If several long-lived",
2680
+ "hosts are running (a gateway, a TUI worker, an editor), restart EVERY",
2681
+ "one of them: each holds the snapshot from its own start time, so after",
2682
+ "a chain of recreations each can be parked on a DIFFERENT old agent.",
2424
2683
  "",
2425
- "child.on('exit', (code, signal) => {",
2426
- " if (signal) process.kill(process.pid, signal)",
2427
- " else process.exit(code ?? 1)",
2428
- "})",
2684
+ "Then verify with: npx @haven_ai/connect@alpha --doctor --runtime <runtime>"
2685
+ ];
2686
+ return [
2687
+ "#!/usr/bin/env node",
2688
+ `// ${TOMBSTONE_MARKER} \u2014 written by @haven_ai/connect (#1681). Safe to delete`,
2689
+ "// once every long-lived MCP host on this machine has been restarted.",
2690
+ `process.stderr.write(${JSON.stringify(lines.join("\n") + "\n")})`,
2691
+ "process.exit(1)",
2429
2692
  ""
2430
2693
  ].join("\n");
2431
- await promises.writeFile(input.wrapperPath, source, { mode: 448 });
2432
- await promises.chmod(input.wrapperPath, 448).catch(() => void 0);
2433
2694
  }
2434
- async function writeRuntimeSidecar2(input) {
2435
- const value = {
2436
- ...input.serverName ? { server_name: input.serverName } : {},
2437
- mcp_package: MCP_RUNTIME_MANIFEST.mcpPackage,
2438
- mcp_version: MCP_RUNTIME_MANIFEST.mcpVersion,
2439
- sdk_package: MCP_RUNTIME_MANIFEST.sdkPackage,
2440
- sdk_version: MCP_RUNTIME_MANIFEST.sdkVersion,
2441
- minimum_node_version: MCP_RUNTIME_MANIFEST.minimumNodeVersion,
2442
- wrapper_path: input.wrapperPath,
2443
- runtime_directory: input.runtimeDirectory,
2444
- npm_cache_directory: input.npmCacheDirectory,
2445
- cli_path: input.cliPath
2695
+ async function writeAgentTombstone(input) {
2696
+ const dirStat = await promises.stat(input.directory).catch(() => null);
2697
+ if (!dirStat?.isDirectory()) {
2698
+ throw new Error(`Not a directory: ${input.directory} \u2014 nothing to tombstone.`);
2699
+ }
2700
+ const info = {
2701
+ // reason / replaced_by are persisted to disk and re-emitted to the host's
2702
+ // MCP stderr log on EVERY stale probe, potentially for months — redact
2703
+ // like every other output path, at the write layer so any future caller
2704
+ // inherits it. (#1681 review, finding 1)
2705
+ agent_id: input.agentId,
2706
+ retired_at: input.retiredAt ?? (/* @__PURE__ */ new Date()).toISOString(),
2707
+ reason: redactSecrets(input.reason),
2708
+ ...input.replacedBy ? { replaced_by: redactSecrets(input.replacedBy) } : {}
2446
2709
  };
2447
- await promises.writeFile(input.path, `${JSON.stringify(value, null, 2)}
2448
- `, { mode: 384 });
2449
- await promises.chmod(input.path, 384).catch(() => void 0);
2710
+ const binDir = path.join(input.directory, "bin");
2711
+ await promises.mkdir(binDir, { recursive: true });
2712
+ const wrapperPath = path.join(binDir, "haven-signer.mjs");
2713
+ await promises.writeFile(wrapperPath, tombstoneScript(info), "utf8");
2714
+ await promises.chmod(wrapperPath, 493);
2715
+ await promises.writeFile(path.join(input.directory, TOMBSTONE_FILENAME), JSON.stringify(info, null, 2) + "\n", "utf8");
2716
+ return info;
2450
2717
  }
2451
- async function assertFileExists2(path, label) {
2718
+ async function readAgentTombstone(directory) {
2452
2719
  try {
2453
- await promises.access(path);
2720
+ const parsed = JSON.parse(await promises.readFile(path.join(directory, TOMBSTONE_FILENAME), "utf8"));
2721
+ if (typeof parsed?.agent_id !== "string") return null;
2722
+ return parsed;
2454
2723
  } catch {
2455
- throw new Error(`Missing ${label}: ${path}`);
2724
+ return null;
2456
2725
  }
2457
2726
  }
2727
+ var TOMBSTONE_FILENAME, TOMBSTONE_MARKER;
2728
+ var init_tombstone = __esm({
2729
+ "src/tombstone.ts"() {
2730
+ init_redact();
2731
+ TOMBSTONE_FILENAME = "TOMBSTONE.json";
2732
+ TOMBSTONE_MARKER = "HAVEN-TOMBSTONE";
2733
+ }
2734
+ });
2458
2735
 
2459
- // src/runtime-install.ts
2460
- init_signer_runtime();
2461
- init_runtime_manifest();
2462
- var CODEX_AGENTS_BEGIN_MARKER = "<!-- BEGIN haven-pay (managed by @haven_ai/connect; edits inside this section are overwritten on re-setup) -->";
2463
- var CODEX_AGENTS_END_MARKER = "<!-- END haven-pay -->";
2464
- async function installSkillForRuntime(runtime, deps = {}) {
2465
- switch (runtime) {
2466
- case "claude-code":
2467
- return installSkillFile(
2468
- path.resolve(deps.homeDir ?? os.homedir(), ".claude", "skills", sdk.SKILL_FOLDER_NAME),
2469
- "~/.claude/skills/haven-pay"
2470
- );
2471
- case "hermes":
2472
- return installSkillFile(
2473
- path.join(hermesHome(deps), "skills", sdk.SKILL_FOLDER_NAME),
2474
- "the Hermes skills folder"
2736
+ // src/rekey.ts
2737
+ var rekey_exports = {};
2738
+ __export(rekey_exports, {
2739
+ finishRekey: () => finishRekey,
2740
+ startRekey: () => startRekey
2741
+ });
2742
+ async function startRekey(options, deps = {}) {
2743
+ const now = deps.now ?? (() => Date.now());
2744
+ const stored = await readStoredCredentials(
2745
+ options.serverName,
2746
+ options.agentId,
2747
+ options.credentialsDir
2748
+ );
2749
+ const api = (deps.createApi ?? ((url) => createConnectApiClient(url)))(stored.apiUrl);
2750
+ const identity = await probeIdentity(api, stored.apiKey, "current");
2751
+ assertRekeyable(identity, stored);
2752
+ const key = (deps.generateKey ?? generateDelegateKey)();
2753
+ const startedAt = new Date(now()).toISOString();
2754
+ const expiresAt = new Date(now() + REKEY_PENDING_TTL_MS).toISOString();
2755
+ await writeRekeyPending(stored.directory, {
2756
+ agent_id: stored.agentId,
2757
+ new_delegate_address: key.address,
2758
+ new_delegate_key: key.privateKey,
2759
+ started_at: startedAt,
2760
+ expires_at: expiresAt
2761
+ });
2762
+ const finishCommand = [
2763
+ "npx @haven_ai/connect@alpha --rekey-finish",
2764
+ options.serverName ? `--name ${options.serverName}` : void 0,
2765
+ "--api-key <the key the dashboard showed you>",
2766
+ options.runtime ? `--runtime ${options.runtime}` : "--runtime <your runtime>"
2767
+ ].filter(Boolean).join(" ");
2768
+ return {
2769
+ started: true,
2770
+ agentId: stored.agentId,
2771
+ directory: stored.directory,
2772
+ newDelegateAddress: key.address,
2773
+ expiresAt,
2774
+ messages: [
2775
+ `New signing key generated on this machine for agent ${identity.name || stored.agentId}.`,
2776
+ "",
2777
+ ` New signing address: ${key.address}`,
2778
+ "",
2779
+ "The private half stays here \u2014 Haven never receives it, and there is no way to move it",
2780
+ "between machines. That is what keeps the account non-custodial.",
2781
+ "",
2782
+ 'Next, on the Haven agent page: choose "Replace signing key" and paste that address.',
2783
+ "When it finishes it shows a new API key ONCE. Come back here and run:",
2784
+ "",
2785
+ ` ${finishCommand}`,
2786
+ "",
2787
+ `Nothing has changed yet \u2014 the agent keeps working on its old key until you finish.`,
2788
+ `This pending re-key expires ${expiresAt}.`
2789
+ ]
2790
+ };
2791
+ }
2792
+ async function finishRekey(options, deps = {}) {
2793
+ const now = deps.now ?? (() => Date.now());
2794
+ if (!options.newApiKey) {
2795
+ throw new Error("--rekey-finish needs --api-key <key> \u2014 the one the Haven agent page showed once.");
2796
+ }
2797
+ const stored = await readStoredCredentials(
2798
+ options.serverName,
2799
+ options.agentId,
2800
+ options.credentialsDir
2801
+ );
2802
+ const pending = await readRekeyPending(stored.directory, now());
2803
+ if (pending.agent_id !== stored.agentId) {
2804
+ throw new Error(
2805
+ `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.`
2806
+ );
2807
+ }
2808
+ const api = (deps.createApi ?? ((url) => createConnectApiClient(url)))(stored.apiUrl);
2809
+ const identity = await probeIdentity(api, options.newApiKey, "new");
2810
+ if (identity.id !== stored.agentId) {
2811
+ throw new Error(
2812
+ `That API key belongs to agent ${identity.id}, not ${stored.agentId}. Nothing was changed.`
2813
+ );
2814
+ }
2815
+ const onChain = (identity.delegate_address ?? "").toLowerCase();
2816
+ const expected = pending.new_delegate_address.toLowerCase();
2817
+ if (onChain !== expected) {
2818
+ throw new Error(
2819
+ `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.`
2820
+ );
2821
+ }
2822
+ await rewriteCredentialFiles({
2823
+ baseDir: options.credentialsDir,
2824
+ agentId: stored.agentId,
2825
+ serverName: options.serverName,
2826
+ apiKey: options.newApiKey,
2827
+ delegateKey: pending.new_delegate_key,
2828
+ delegateAddress: pending.new_delegate_address,
2829
+ safeAddress: stored.safeAddress ?? identity.safe_address ?? void 0,
2830
+ chainId: stored.chainId ?? identity.chain_id ?? void 0,
2831
+ network: stored.network,
2832
+ agentBudget: stored.agentBudget,
2833
+ apiUrl: stored.apiUrl,
2834
+ hostedMcpUrl: stored.hostedMcpUrl,
2835
+ x402BindingSigner: stored.x402BindingSigner,
2836
+ warn: deps.log
2837
+ });
2838
+ await clearRekeyPending(stored.directory);
2839
+ const names = serverNamesFor(options.serverName);
2840
+ const messages = [
2841
+ `Agent ${identity.name || stored.agentId} is now on its new signing key.`,
2842
+ ` Signing address: ${pending.new_delegate_address}`,
2843
+ ` Credentials: ${stored.directory} (rewritten in place)`,
2844
+ ` MCP servers: ${names.hosted} / ${names.signer} (unchanged names)`
2845
+ ];
2846
+ let configRewritten = false;
2847
+ if (options.runtime) {
2848
+ const prepared = await (deps.prepareSigner ?? prepareSignerRuntime)(
2849
+ {
2850
+ credentialDirectory: stored.directory,
2851
+ signerPath: `${stored.directory}/signer.json`,
2852
+ homeDir: options.homeDir
2853
+ },
2854
+ { runCommand: deps.runCommand }
2855
+ );
2856
+ const result = await (deps.writeConfig ?? writeHostedRuntimeConfig)(
2857
+ { runCommand: deps.runCommand, homeDir: options.homeDir },
2858
+ {
2859
+ runtime: options.runtime,
2860
+ hostedMcpUrl: stored.hostedMcpUrl,
2861
+ apiKey: options.newApiKey,
2862
+ identityPath: `${stored.directory}/identity.json`,
2863
+ signerPath: `${stored.directory}/signer.json`,
2864
+ credentialDirectory: stored.directory,
2865
+ serverName: options.serverName
2866
+ },
2867
+ { command: prepared.command, args: prepared.args }
2868
+ );
2869
+ configRewritten = result.hostedConfigured;
2870
+ messages.push(` Config: ${result.target}`);
2871
+ messages.push(...result.messages.map((line) => ` ${line}`));
2872
+ if (!configRewritten) {
2873
+ messages.push(
2874
+ "",
2875
+ "WARNING: the MCP config was NOT updated, so it still carries the OLD API key and every",
2876
+ `wired host will fail with 401. Fix the cause above and re-run with --runtime ${options.runtime},`,
2877
+ "or update the config by hand. The credential files on disk are already on the new key."
2475
2878
  );
2476
- case "codex-cli":
2477
- case "codex-desktop":
2478
- return installCodexAgentsSection(deps);
2479
- default:
2480
- return void 0;
2879
+ }
2880
+ } else {
2881
+ messages.push(
2882
+ "",
2883
+ "NOTE: no --runtime was given, so the MCP config still carries the OLD API key and every",
2884
+ "wired host will fail with 401. Re-run with --runtime <name> to rewrite it."
2885
+ );
2481
2886
  }
2887
+ return {
2888
+ finished: true,
2889
+ agentId: stored.agentId,
2890
+ directory: stored.directory,
2891
+ newDelegateAddress: pending.new_delegate_address,
2892
+ serverNames: { hosted: names.hosted, signer: names.signer },
2893
+ configRewritten,
2894
+ messages
2895
+ };
2482
2896
  }
2483
- async function installSkillFile(skillDir, label) {
2897
+ async function probeIdentity(api, apiKey, which) {
2484
2898
  try {
2485
- await promises.mkdir(skillDir, { recursive: true });
2486
- const target = path.join(skillDir, "SKILL.md");
2487
- await promises.writeFile(target, sdk.HAVEN_SKILL_MD, "utf8");
2488
- return {
2489
- installed: true,
2490
- target,
2491
- messages: [`Installed the generic Haven payment skill (${label}). It contains no secrets.`]
2492
- };
2899
+ return await api.getAgentIdentity(apiKey);
2493
2900
  } catch (err) {
2494
- return {
2495
- installed: false,
2496
- messages: [
2497
- `Could not install the Haven payment skill: ${err instanceof Error ? err.message : String(err)}. Download it from the Haven dashboard instead.`
2498
- ]
2499
- };
2500
- }
2501
- }
2502
- async function installCodexAgentsSection(deps) {
2503
- try {
2504
- const codexDir = path.resolve(deps.homeDir ?? os.homedir(), ".codex");
2505
- const target = path.join(codexDir, "AGENTS.md");
2506
- await promises.mkdir(codexDir, { recursive: true });
2507
- const existing = await promises.readFile(target, "utf8").catch(() => null);
2508
- const next = upsertManagedSection(existing, codexManagedSection());
2509
- if (next !== existing) {
2510
- await promises.writeFile(target, next, "utf8");
2901
+ const status = err?.status;
2902
+ if (status === 401 || status === 403) {
2903
+ throw new Error(
2904
+ 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."
2905
+ );
2511
2906
  }
2512
- return {
2513
- installed: true,
2514
- target,
2515
- messages: [
2516
- "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."
2517
- ]
2518
- };
2519
- } catch (err) {
2520
- return {
2521
- installed: false,
2522
- messages: [
2523
- `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.`
2524
- ]
2525
- };
2907
+ throw new Error(
2908
+ `Could not reach Haven to check this agent (${redactSecrets(
2909
+ err instanceof Error ? err.message : String(err)
2910
+ )}). Nothing was changed.`
2911
+ );
2526
2912
  }
2527
2913
  }
2528
- function codexManagedSection() {
2529
- return `${CODEX_AGENTS_BEGIN_MARKER}
2530
-
2531
- ${sdk.HAVEN_SKILL_BODY_MD.trimEnd()}
2532
-
2533
- ${CODEX_AGENTS_END_MARKER}
2534
- `;
2535
- }
2536
- function upsertManagedSection(existing, section) {
2537
- if (existing === null || existing.trim() === "") return section;
2538
- const begins = markerLineIndexes(existing, CODEX_AGENTS_BEGIN_MARKER);
2539
- const ends = markerLineIndexes(existing, CODEX_AGENTS_END_MARKER);
2540
- if (begins.length === 1 && ends.length === 1 && ends[0] > begins[0]) {
2541
- const afterEnd = ends[0] + CODEX_AGENTS_END_MARKER.length;
2542
- const tail = existing.startsWith("\r\n", afterEnd) ? existing.slice(afterEnd + 2) : existing.startsWith("\n", afterEnd) ? existing.slice(afterEnd + 1) : existing.slice(afterEnd);
2543
- return existing.slice(0, begins[0]) + section + tail;
2914
+ function assertRekeyable(identity, stored) {
2915
+ if (identity.id !== stored.agentId) {
2916
+ throw new Error(
2917
+ `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.`
2918
+ );
2544
2919
  }
2545
- if (begins.length > 0 || ends.length > 0) {
2920
+ if (identity.execution_rail === "legacy") {
2546
2921
  throw new Error(
2547
- "found a damaged Haven marker section (orphaned or duplicated markers); remove the leftover marker lines and re-run setup"
2922
+ `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.`
2548
2923
  );
2549
2924
  }
2550
- return `${existing.replace(/\n*$/, "\n\n")}${section}`;
2551
- }
2552
- function markerLineIndexes(text, marker) {
2553
- const indexes = [];
2554
- for (let from = 0; ; ) {
2555
- const at = text.indexOf(marker, from);
2556
- if (at === -1) return indexes;
2557
- if (at === 0 || text[at - 1] === "\n") indexes.push(at);
2558
- from = at + marker.length;
2925
+ if (identity.status === "revoked") {
2926
+ throw new Error(
2927
+ `Agent ${identity.name || identity.id} is revoked. Re-keying would hand a revoked agent fresh credentials \u2014 create a new agent instead.`
2928
+ );
2559
2929
  }
2560
2930
  }
2561
- function hermesHome(deps) {
2562
- const env = deps.env ?? process.env;
2563
- return env.HERMES_HOME ?? path.join(deps.homeDir ?? os.homedir(), ".hermes");
2564
- }
2931
+ var init_rekey = __esm({
2932
+ "src/rekey.ts"() {
2933
+ init_api();
2934
+ init_runtime_install();
2935
+ init_signer_runtime();
2936
+ init_key();
2937
+ init_redact();
2938
+ init_server_names();
2939
+ init_storage();
2940
+ }
2941
+ });
2565
2942
 
2566
- // src/runtime-install.ts
2567
- init_runtime_registry();
2568
- init_signer_consent();
2569
- var execFileAsync3 = util.promisify(child_process.execFile);
2570
- async function installRuntime(input, deps = {}) {
2571
- const runtime = normalizeRuntime(input.runtime, deps.env);
2572
- const profile = runtimeProfile(runtime, deps.env);
2573
- const progress = deps.onProgress ?? (() => void 0);
2574
- const localRuntime = input.localMcp === true && supportsLocalMcp(runtime);
2575
- const consentMessages = [];
2576
- const localMcpConsent = localRuntime ? await resolveLocalMcpConsent(input, consentMessages) : void 0;
2577
- const signerConsent = localRuntime ? void 0 : await resolveSignerConsent(input, consentMessages);
2578
- if (runtime === "other") {
2579
- const signerCredentialReady2 = await probeLocalSignerCredential(input.signerPath);
2580
- const signerReady = signerCredentialReady2 && signerConsent?.acknowledged;
2581
- return {
2582
- runtime,
2583
- runtimeMcpMode: "manual",
2584
- hostedMcpConfigured: false,
2585
- localSignerConfigured: false,
2586
- localMcpConfigured: false,
2587
- probeResult: signerReady ? "manual_runtime_setup_required_local_signer_ready" : "manual_runtime_setup_required_local_signer_unavailable",
2588
- restartRequired: true,
2589
- nextUserAction: "return_to_haven_for_wallet_approval_then_configure_runtime",
2590
- errorCode: "manual_runtime_setup_required",
2591
- configTarget: "manual runtime setup",
2592
- signerAcknowledged: signerConsent?.acknowledged,
2593
- localMcpAcknowledged: false,
2594
- messages: [
2595
- ...consentMessages,
2596
- "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.",
2597
- ` identity (hosted MCP Bearer): ${input.identityPath}`,
2598
- ` signer (local signing key): ${input.signerPath}`,
2599
- "After wallet approval, wire the runtime to Haven by reference:",
2600
- ` 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}`,
2601
- ` Fully local MCP (no hosted dependency): npx -y ${mcpPackageSpec()} --identity ${input.identityPath} --signer ${input.signerPath}`
2602
- ]
2943
+ // src/rekey-restart.ts
2944
+ var rekey_restart_exports = {};
2945
+ __export(rekey_restart_exports, {
2946
+ restartGuidance: () => restartGuidance
2947
+ });
2948
+ function restartGuidance(runtime) {
2949
+ const profile = runtime ? BY_RUNTIME[runtime] : void 0;
2950
+ const lines = ["The new key is only live in a process that started after now.", ""];
2951
+ if (profile) {
2952
+ lines.push(profile.how);
2953
+ for (const command of profile.commands) lines.push(` ${command}`);
2954
+ if (profile.commands.length > 0) lines.push("");
2955
+ } else {
2956
+ lines.push(
2957
+ 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."
2958
+ );
2959
+ lines.push("");
2960
+ }
2961
+ lines.push(SWEEP);
2962
+ return { commands: profile?.commands ?? [], lines };
2963
+ }
2964
+ var SWEEP, BY_RUNTIME;
2965
+ var init_rekey_restart = __esm({
2966
+ "src/rekey-restart.ts"() {
2967
+ 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.";
2968
+ BY_RUNTIME = {
2969
+ "claude-code": {
2970
+ commands: ["claude --continue"],
2971
+ how: "Exit this Claude Code session and start a new one:"
2972
+ },
2973
+ "codex-cli": {
2974
+ commands: ["codex resume --last"],
2975
+ how: "Start a fresh Codex CLI session:"
2976
+ },
2977
+ "codex-desktop": {
2978
+ commands: [],
2979
+ how: "Quit Codex Desktop completely (not just the window) and reopen it."
2980
+ },
2981
+ "claude-desktop": {
2982
+ commands: [],
2983
+ how: "Quit Claude Desktop completely (not just the window) and reopen it."
2984
+ },
2985
+ hermes: {
2986
+ commands: ["systemctl --user restart hermes-gateway", "/restart"],
2987
+ 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:"
2988
+ },
2989
+ cursor: {
2990
+ commands: [],
2991
+ 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").'
2992
+ },
2993
+ vscode: {
2994
+ commands: [],
2995
+ 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").'
2996
+ },
2997
+ "vscode-insiders": {
2998
+ commands: [],
2999
+ 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").'
3000
+ }
2603
3001
  };
2604
3002
  }
2605
- let localRuntimeInstall;
2606
- let localRuntimeError;
2607
- if (localRuntime) {
3003
+ });
3004
+
3005
+ // src/doctor.ts
3006
+ var doctor_exports = {};
3007
+ __export(doctor_exports, {
3008
+ runDoctor: () => runDoctor,
3009
+ runRepair: () => runRepair
3010
+ });
3011
+ async function discoverCredentialDirectory(homeDir, explicit) {
3012
+ const root = explicit ? path.dirname(explicit) : path.join(homeDir, ".haven", "agents");
3013
+ let entries = [];
3014
+ try {
3015
+ entries = await promises.readdir(root);
3016
+ } catch {
3017
+ return explicit ? { directory: explicit, others: [], parkedOnly: /* @__PURE__ */ new Set() } : { others: [], parkedOnly: /* @__PURE__ */ new Set() };
3018
+ }
3019
+ const candidates = [];
3020
+ const tombstonedOnly = [];
3021
+ const parkedOnly = [];
3022
+ for (const entry of entries) {
3023
+ const directory = path.join(root, entry);
2608
3024
  try {
2609
- localRuntimeInstall = await prepareRuntimeForLocalMcp(input, deps);
2610
- } catch (err) {
2611
- localRuntimeError = err;
3025
+ const s = await promises.stat(path.join(directory, "identity.json"));
3026
+ candidates.push({ directory, mtimeMs: s.mtimeMs });
3027
+ } catch {
3028
+ try {
3029
+ await promises.stat(path.join(directory, TOMBSTONE_FILENAME));
3030
+ tombstonedOnly.push(directory);
3031
+ } catch {
3032
+ try {
3033
+ await promises.stat(path.join(directory, REKEY_PENDING_FILENAME));
3034
+ parkedOnly.push(directory);
3035
+ } catch {
3036
+ }
3037
+ }
2612
3038
  }
2613
3039
  }
2614
- if (localRuntimeError) {
2615
- const errorCode2 = localRuntimePrepareErrorCode(localRuntimeError);
3040
+ const parkedOnlySet = new Set(parkedOnly);
3041
+ candidates.sort((a, b) => b.mtimeMs - a.mtimeMs);
3042
+ if (explicit) {
2616
3043
  return {
2617
- runtime,
2618
- runtimeMcpMode: "local_stdio",
2619
- hostedMcpConfigured: false,
2620
- localSignerConfigured: false,
2621
- localMcpConfigured: false,
2622
- probeResult: errorCode2 === "local_mcp_unsupported_node_version" ? "local_stdio_mcp_unsupported_node_version" : "local_stdio_mcp_runtime_install_failed",
2623
- restartRequired: true,
2624
- nextUserAction: nextAction(runtime, profile.restartMode, errorCode2),
2625
- errorCode: errorCode2,
2626
- configTarget: profile.label,
2627
- signerAcknowledged: signerConsent?.acknowledged,
2628
- localMcpAcknowledged: localMcpConsent?.acknowledged,
2629
- activationCommand: void 0,
2630
- messages: [
2631
- ...consentMessages,
2632
- `Could not prepare local Haven MCP runtime: ${localRuntimeError instanceof Error ? localRuntimeError.message : String(localRuntimeError)}`
2633
- ]
3044
+ directory: explicit,
3045
+ others: [...candidates.map((c) => c.directory), ...tombstonedOnly, ...parkedOnly].filter((d) => d !== explicit),
3046
+ parkedOnly: parkedOnlySet
2634
3047
  };
2635
3048
  }
2636
- let signerCommand;
2637
- if (!localRuntime) {
2638
- progress("Getting the signer ready\u2026");
2639
- try {
2640
- const signerRuntime = await prepareSignerForRuntime(input, deps);
2641
- signerCommand = { command: signerRuntime.command, args: signerRuntime.args };
2642
- consentMessages.push(...signerRuntime.messages);
2643
- } catch (err) {
2644
- return {
2645
- runtime,
2646
- runtimeMcpMode: "hosted_plus_signer",
2647
- hostedMcpConfigured: false,
2648
- localSignerConfigured: false,
2649
- localMcpConfigured: false,
2650
- probeResult: "signer_runtime_install_failed",
2651
- restartRequired: false,
2652
- 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",
2653
- errorCode: "signer_runtime_install_failed",
2654
- configTarget: profile.label,
2655
- signerAcknowledged: signerConsent?.acknowledged,
2656
- localMcpAcknowledged: localMcpConsent?.acknowledged,
2657
- activationCommand: void 0,
2658
- signerRuntimePrepared: false,
2659
- messages: [
2660
- ...consentMessages,
2661
- `Could not pre-install the local Haven signer: ${err instanceof Error ? err.message : String(err)}`,
2662
- "No runtime configuration was written (fail-closed): a config pointing at an uninstalled signer looks wired but cannot start.",
2663
- "Re-run `npx @haven_ai/connect@alpha` to retry the setup."
2664
- ]
2665
- };
3049
+ if (candidates.length === 0 && tombstonedOnly.length === 0 && parkedOnly.length === 0) {
3050
+ return { others: [], parkedOnly: parkedOnlySet };
3051
+ }
3052
+ return {
3053
+ directory: candidates[0]?.directory,
3054
+ others: [...candidates.slice(1).map((c) => c.directory), ...tombstonedOnly, ...parkedOnly],
3055
+ parkedOnly: parkedOnlySet
3056
+ };
3057
+ }
3058
+ function agentIsWired(configText, names, slug, identity, sidecar, isPrimary, bareOwnerExists) {
3059
+ if (configText === null) return isPrimary;
3060
+ if (slug) {
3061
+ for (const name of [names.hosted, names.codexHosted, names.signer, names.codexSigner]) {
3062
+ if (new RegExp(`(^|[."'\\s\\[])${name}(["'\\]:\\s]|$)`, "m").test(configText)) return true;
2666
3063
  }
3064
+ return false;
2667
3065
  }
2668
- const signerRuntimePrepared = localRuntime ? void 0 : signerCommand !== void 0;
2669
- progress("Setting up your Haven tools\u2026");
2670
- const configResult = runtime === "claude-code" ? localRuntime ? await configureClaudeCode(deps, localRuntimeInstall?.command ?? "", input.serverName) : await configureClaudeCodeHosted(deps, input, signerCommand) : await writeRuntimeConfig({
2671
- runtime,
2672
- hostedMcpUrl: input.hostedMcpUrl,
2673
- apiKey: input.apiKey,
2674
- identityPath: input.identityPath,
2675
- signerPath: input.signerPath,
2676
- serverName: input.serverName,
2677
- credentialDirectory: input.credentialDirectory,
2678
- localMcpCommand: localRuntimeInstall?.command,
2679
- signerCommand,
2680
- homeDir: deps.homeDir,
2681
- mode: localRuntime ? "local" : "hosted"
3066
+ if (sidecar?.wrapper_path && configText.includes(sidecar.wrapper_path)) return true;
3067
+ if (bareOwnerExists) return false;
3068
+ return isPrimary && Boolean(identity?.hosted_mcp_url && configText.includes(identity.hosted_mcp_url));
3069
+ }
3070
+ function rekeyPendingCheck(status, hostedDelegateAddress, runtime, slug) {
3071
+ const label = "Pending re-key";
3072
+ const nameFlag = slug ? ` --name ${slug}` : "";
3073
+ if (status.state === "unreadable") {
3074
+ return {
3075
+ id: "rekey_pending",
3076
+ label,
3077
+ ok: false,
3078
+ 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.`,
3079
+ repair: `Delete ${status.path}, then start again: ${RERUN} --rekey${nameFlag}`
3080
+ };
3081
+ }
3082
+ const started = status.startedAt ?? "an unknown time";
3083
+ const address = status.newDelegateAddress ?? "unknown";
3084
+ const completedOnHaven = hostedDelegateAddress !== void 0 && status.newDelegateAddress !== void 0 && hostedDelegateAddress.toLowerCase() === status.newDelegateAddress.toLowerCase();
3085
+ if (completedOnHaven) {
3086
+ return {
3087
+ id: "rekey_pending",
3088
+ label,
3089
+ ok: false,
3090
+ 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." : ""),
3091
+ 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}`
3092
+ };
3093
+ }
3094
+ 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.";
3095
+ if (status.state === "expired") {
3096
+ return {
3097
+ id: "rekey_pending",
3098
+ label,
3099
+ ok: false,
3100
+ 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,
3101
+ 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.`
3102
+ };
3103
+ }
3104
+ return {
3105
+ id: "rekey_pending",
3106
+ label,
3107
+ ok: true,
3108
+ 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
3109
+ };
3110
+ }
3111
+ async function readIdentity(directory) {
3112
+ try {
3113
+ return JSON.parse(await promises.readFile(path.join(directory, "identity.json"), "utf8"));
3114
+ } catch {
3115
+ return void 0;
3116
+ }
3117
+ }
3118
+ async function checksForAgent(entry, input, deps) {
3119
+ const { directory, identity, sidecar } = entry;
3120
+ const checks = [];
3121
+ let signerCapabilities;
3122
+ let signerFile;
3123
+ try {
3124
+ const parsed = JSON.parse(await promises.readFile(path.join(directory, "signer.json"), "utf8"));
3125
+ signerFile = typeof parsed === "object" && parsed !== null ? parsed : void 0;
3126
+ } catch {
3127
+ signerFile = void 0;
3128
+ }
3129
+ const credentialsOk = Boolean(identity?.api_key) && signerFile !== void 0;
3130
+ checks.push({
3131
+ id: "credentials",
3132
+ label: "Agent credentials",
3133
+ ok: credentialsOk,
3134
+ detail: credentialsOk ? `identity.json and signer.json parse (agent ${identity?.agent_id ?? "unknown"})` : "identity.json or signer.json is missing or unparseable.",
3135
+ ...credentialsOk ? {} : { repair: `Re-run the full setup with a fresh token: ${RERUN} --setup <token>.` }
2682
3136
  });
2683
- if (deps.onRuntimeConfigured) {
2684
- const signerCredentialOnDisk = await probeLocalSignerCredential(input.signerPath);
2685
- const earlyLocalMcpOk = configResult.runtimeMcpMode === "local_stdio" && configResult.localMcpConfigured && signerCredentialOnDisk && Boolean(localMcpConsent?.acknowledged);
2686
- const earlySignerOk = configResult.runtimeMcpMode === "local_stdio" ? earlyLocalMcpOk : configResult.signerConfigured && signerCredentialOnDisk && Boolean(signerConsent?.acknowledged);
2687
- try {
2688
- await deps.onRuntimeConfigured({
2689
- runtime,
2690
- runtimeMcpMode: configResult.runtimeMcpMode,
2691
- hostedMcpConfigured: configResult.hostedConfigured,
2692
- localSignerConfigured: earlySignerOk,
2693
- localMcpConfigured: earlyLocalMcpOk,
2694
- signerAcknowledged: signerConsent?.acknowledged,
2695
- localMcpAcknowledged: localMcpConsent?.acknowledged,
2696
- restartRequired: configResult.restartRequired || restartRequiredForRuntime(runtime, deps.env),
2697
- nextUserAction: nextAction(runtime, profile.restartMode, configResult.errorCode),
2698
- errorCode: configResult.errorCode
3137
+ if (!sidecar) {
3138
+ checks.push({
3139
+ id: "signer_runtime",
3140
+ label: "Signer runtime (preinstalled wrapper)",
3141
+ ok: false,
3142
+ detail: "No signer-runtime.json sidecar \u2014 the pinned signer runtime was never prepared (or a pre-#1586 npx config).",
3143
+ repair: `Run: ${RERUN} --doctor --repair --runtime ${input.runtime}`
3144
+ });
3145
+ } else {
3146
+ const matches = await installedRuntimeMatches(sidecar.runtime_directory, sidecar.cli_path);
3147
+ const versionOk = sidecar.signer_version === MCP_RUNTIME_MANIFEST.signerVersion;
3148
+ const ok = matches && versionOk;
3149
+ checks.push({
3150
+ id: "signer_runtime",
3151
+ label: "Signer runtime (preinstalled wrapper)",
3152
+ ok,
3153
+ 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.`,
3154
+ ...ok ? {} : { repair: `Run: ${RERUN} --doctor --repair --runtime ${input.runtime}` }
3155
+ });
3156
+ }
3157
+ const hostedUrl = identity?.hosted_mcp_url ?? (identity?.api_url ? `${identity.api_url}/mcp` : void 0);
3158
+ if (identity?.api_key && hostedUrl) {
3159
+ const probe = await (deps.probeHosted ?? probeHostedMcpTools)(identity.api_key, hostedUrl, deps.fetch);
3160
+ checks.push({
3161
+ id: "hosted_mcp",
3162
+ label: "Hosted Haven MCP",
3163
+ ok: probe.status === "ok",
3164
+ detail: probe.status === "ok" ? `Reachable and authorized (${hostedUrl}).` : `Probe failed: ${probe.status} (${hostedUrl}).`,
3165
+ ...probe.status === "ok" ? {} : {
3166
+ 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."
3167
+ }
3168
+ });
3169
+ } else {
3170
+ checks.push({
3171
+ id: "hosted_mcp",
3172
+ label: "Hosted Haven MCP",
3173
+ ok: false,
3174
+ detail: "No stored API key / hosted MCP URL to probe with.",
3175
+ repair: `Re-run the full setup: ${RERUN} --setup <token>.`
3176
+ });
3177
+ }
3178
+ const localDelegate = typeof signerFile?.delegate_address === "string" ? signerFile.delegate_address : void 0;
3179
+ let hostedDelegateAddress;
3180
+ if (identity?.api_key && identity.api_url) {
3181
+ const probe = await (deps.probeHostedIdentity ?? probeHostedAgentIdentity)(
3182
+ identity.api_key,
3183
+ identity.api_url,
3184
+ deps.fetch
3185
+ );
3186
+ if (probe.status === "ok") hostedDelegateAddress = probe.delegateAddress;
3187
+ if (probe.status !== "ok") {
3188
+ checks.push({
3189
+ id: "identity_match",
3190
+ label: "Hosted identity matches the local signing key",
3191
+ ok: false,
3192
+ 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.`,
3193
+ 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}`
3194
+ });
3195
+ } else if (!localDelegate) {
3196
+ checks.push({
3197
+ id: "identity_match",
3198
+ label: "Hosted identity matches the local signing key",
3199
+ ok: false,
3200
+ detail: "signer.json holds no delegate_address to compare against the hosted identity.",
3201
+ repair: `Re-run the full setup with a fresh token: ${RERUN} --setup <token>.`
3202
+ });
3203
+ } else {
3204
+ const same = probe.delegateAddress?.toLowerCase() === localDelegate.toLowerCase();
3205
+ checks.push({
3206
+ id: "identity_match",
3207
+ label: "Hosted identity matches the local signing key",
3208
+ ok: same,
3209
+ 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.`,
3210
+ ...same ? {} : {
3211
+ 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.`
3212
+ }
3213
+ });
3214
+ }
3215
+ }
3216
+ const pending = await inspectRekeyPending(directory, deps.now?.() ?? Date.now());
3217
+ if (pending) {
3218
+ checks.push(rekeyPendingCheck(pending, hostedDelegateAddress, input.runtime, sidecar?.server_name));
3219
+ }
3220
+ if (sidecar) {
3221
+ const consent = await getLocalSignerConsentStatus(path.join(directory, "signer.json"));
3222
+ if (!consent.acknowledged) {
3223
+ checks.push({
3224
+ id: "signer_process",
3225
+ label: "Signer stdio handshake",
3226
+ ok: false,
3227
+ detail: "The local-tools consent is not acknowledged, so the signer refuses to start (by design).",
3228
+ repair: `Run: ${RERUN} --ack-local-tools --setup <token> (or re-run your original setup command with --ack-local-tools).`
3229
+ });
3230
+ } else {
3231
+ const probe = await (deps.probeSignerTools ?? probeLocalMcpTools)(
3232
+ sidecar.wrapper_path,
3233
+ [],
3234
+ MCP_RUNTIME_MANIFEST.requiredSignerTools
3235
+ );
3236
+ const experimental = probe.capabilities?.experimental ?? probe.capabilities;
3237
+ const compat = experimental?.["haven/signer-compatibility"];
3238
+ signerCapabilities = compat ? { "haven/signer-compatibility": compat } : void 0;
3239
+ const compatDetail = compat ? ` Compat: x402 expected-context v${JSON.stringify(compat.x402_expected_context_versions ?? "?")}.` : "";
3240
+ checks.push({
3241
+ id: "signer_process",
3242
+ label: "Signer stdio handshake",
3243
+ ok: probe.status === "ok",
3244
+ detail: probe.status === "ok" ? `Signer started, listed ${probe.toolNames?.length ?? 0} tools${probe.serverInfo?.version ? ` (v${probe.serverInfo.version})` : ""}.${compatDetail}` : `Handshake failed: ${probe.status}.`,
3245
+ ...probe.status === "ok" ? {} : { repair: `Run: ${RERUN} --doctor --repair --runtime ${input.runtime}` }
2699
3246
  });
3247
+ }
3248
+ } else {
3249
+ checks.push({
3250
+ id: "signer_process",
3251
+ label: "Signer stdio handshake",
3252
+ ok: false,
3253
+ detail: "Skipped \u2014 no prepared signer runtime to probe.",
3254
+ repair: `Run: ${RERUN} --doctor --repair --runtime ${input.runtime}`
3255
+ });
3256
+ }
3257
+ return { checks, ...signerCapabilities ? { signerCapabilities } : {} };
3258
+ }
3259
+ async function runDoctor(input, deps = {}) {
3260
+ const homeDir = deps.homeDir ?? os.homedir();
3261
+ const checks = [];
3262
+ let signerCapabilities;
3263
+ const { directory, others, parkedOnly } = await discoverCredentialDirectory(homeDir, input.credentialsDir);
3264
+ const configPath = runtimeConfigPathFor(input.runtime, homeDir);
3265
+ let configText = null;
3266
+ if (configPath !== null) {
3267
+ try {
3268
+ configText = await promises.readFile(configPath, "utf8");
2700
3269
  } catch {
3270
+ configText = null;
2701
3271
  }
2702
3272
  }
2703
- progress("Almost there \u2014 just confirming everything connects\u2026");
2704
- const localProbePromise = configResult.runtimeMcpMode === "local_stdio" && localRuntimeInstall ? runLocalMcpProbe(localRuntimeInstall, deps) : Promise.resolve(void 0);
2705
- const signerProbePromise = configResult.runtimeMcpMode !== "local_stdio" && signerCommand ? (deps.probeSignerTools ?? probeLocalMcpTools)(
2706
- signerCommand.command,
2707
- signerCommand.args,
2708
- MCP_RUNTIME_MANIFEST.requiredSignerTools
2709
- ) : Promise.resolve(void 0);
2710
- const [hostedProbe, signerCredentialReady, localMcpProbe, signerProbe] = await Promise.all([
2711
- configResult.hostedConfigured ? probeHostedMcpTools(input.apiKey, input.hostedMcpUrl, deps.fetch) : Promise.resolve({ status: "bad_response" }),
2712
- probeLocalSignerCredential(input.signerPath),
2713
- localProbePromise,
2714
- signerProbePromise
2715
- ]);
2716
- const hostedOk = configResult.hostedConfigured && hostedProbe.status === "ok";
2717
- const localMcpOk = configResult.runtimeMcpMode === "local_stdio" && configResult.localMcpConfigured && signerCredentialReady && Boolean(localMcpConsent?.acknowledged) && localMcpProbe?.status === "ok";
2718
- const signerOk = configResult.runtimeMcpMode === "local_stdio" ? localMcpOk : configResult.signerConfigured && signerCredentialReady && Boolean(signerConsent?.acknowledged) && // #1587: no handshake, no green. A signer command that was registered
2719
- // but not probed (manual topology) keeps the old semantics.
2720
- (signerProbe === void 0 || signerProbe.status === "ok");
2721
- const restartRequired = configResult.restartRequired || restartRequiredForRuntime(runtime, deps.env);
2722
- const errorCode = configResult.errorCode ?? (configResult.runtimeMcpMode === "local_stdio" ? localMcpErrorCode(signerCredentialReady, localMcpConsent, localMcpProbe?.status) : hostedMcpErrorCode(configResult.hostedConfigured, hostedProbe.status) ?? signerConsentErrorCode(signerCredentialReady, signerConsent) ?? signerProbeErrorCode(signerProbe));
2723
- 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."] : [];
2724
- const signerProbeMessages = signerProbe ? signerProbe.status === "ok" ? ["Verified local Haven signer with a stdio handshake."] : [
2725
- `Local Haven signer handshake failed: ${signerProbe.status}.`,
2726
- "Re-run `npx @haven_ai/connect@alpha` to repair the signer setup."
2727
- ] : [];
2728
- 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."] : [];
2729
- const skillInstall = !configResult.errorCode ? await installSkillForRuntime(runtime, { homeDir: deps.homeDir, env: deps.env }) : void 0;
2730
- return {
2731
- runtime,
2732
- runtimeMcpMode: configResult.runtimeMcpMode,
2733
- hostedMcpConfigured: hostedOk,
2734
- localSignerConfigured: signerOk,
2735
- localMcpConfigured: localMcpOk,
2736
- probeResult: buildProbeResult(configResult.runtimeMcpMode, configResult.hostedConfigured, hostedProbe.status, signerOk, localMcpOk, localMcpProbe?.status),
2737
- restartRequired,
2738
- nextUserAction: nextAction(runtime, profile.restartMode, errorCode),
2739
- errorCode,
2740
- configTarget: configResult.target,
2741
- signerAcknowledged: signerConsent?.acknowledged,
2742
- localMcpAcknowledged: localMcpConsent?.acknowledged,
2743
- activationCommand: configResult.activationCommand,
2744
- skillInstalled: skillInstall?.installed,
2745
- signerRuntimePrepared,
2746
- messages: [...consentMessages, ...localRuntimeInstall?.messages ?? [], ...configResult.messages, ...hostedProbeMessages, ...signerProbeMessages, ...localProbeMessages, ...skillInstall?.messages ?? []]
2747
- };
2748
- }
2749
- function runtimeInstallCapabilities(runtime, env = process.env) {
2750
- const profile = runtimeProfile(runtime, env);
2751
- return {
2752
- canWriteRuntimeConfig: profile.canWriteRuntimeConfig,
2753
- restartRequired: restartRequiredForRuntime(runtime, env)
2754
- };
2755
- }
2756
- async function configureClaudeCode(deps, localMcpCommand, serverName) {
2757
- const runCommand = deps.runCommand ?? defaultRunCommand;
2758
- const serverJson = JSON.stringify({
2759
- type: "stdio",
2760
- command: localMcpCommand,
2761
- args: [],
2762
- env: {}
2763
- });
2764
- try {
2765
- if (!localMcpCommand) throw new Error("local MCP wrapper command is required");
2766
- const names = serverNamesFor(serverName);
2767
- await runCommand("claude", ["mcp", "remove", names.hosted]).catch(() => void 0);
2768
- await runCommand("claude", ["mcp", "remove", names.signer]).catch(() => void 0);
2769
- await runCommand("claude", ["mcp", "add-json", names.hosted, serverJson, "--scope", "user"]).catch(async () => {
2770
- await runCommand("claude", ["mcp", "add", names.hosted, "--scope", "user", "--", localMcpCommand]);
2771
- });
2772
- const verified = await runCommand("claude", ["mcp", "get", names.hosted]).then(() => true).catch(() => false);
2773
- return {
2774
- hostedConfigured: false,
2775
- signerConfigured: true,
2776
- localMcpConfigured: true,
2777
- runtimeMcpMode: "local_stdio",
2778
- target: "Claude Code MCP config",
2779
- changed: true,
2780
- restartRequired: true,
2781
- messages: [
2782
- "Updated local Haven MCP entry with Claude Code.",
2783
- ...verified ? ["Verified Claude Code MCP entry."] : []
2784
- ]
2785
- };
2786
- } catch (err) {
2787
- return {
2788
- hostedConfigured: false,
2789
- signerConfigured: false,
2790
- localMcpConfigured: false,
2791
- runtimeMcpMode: "local_stdio",
2792
- target: "Claude Code MCP config",
2793
- changed: false,
2794
- restartRequired: true,
2795
- messages: [
2796
- `Could not update Claude Code MCP config: ${err instanceof Error ? err.message : String(err)}`,
2797
- "Install Claude Code or rerun the Haven setup command inside a Claude Code terminal."
2798
- ],
2799
- errorCode: "claude_code_config_failed"
2800
- };
3273
+ const allDirectories = directory ? [directory, ...others] : others;
3274
+ let bareOwnerExists = false;
3275
+ for (const dir of allDirectories) {
3276
+ const sidecar = await readRuntimeSidecar(dir);
3277
+ if (!sidecar?.server_name && sidecar?.wrapper_path && configText?.includes(sidecar.wrapper_path)) {
3278
+ bareOwnerExists = true;
3279
+ break;
3280
+ }
2801
3281
  }
2802
- }
2803
- async function configureClaudeCodeHosted(deps, input, signerCommand) {
2804
- const runCommand = deps.runCommand ?? defaultRunCommand;
2805
- const hostedJson = JSON.stringify({
2806
- type: "http",
2807
- url: input.hostedMcpUrl,
2808
- headers: { Authorization: `Bearer ${input.apiKey}` }
2809
- });
2810
- const signerJson = JSON.stringify({
2811
- type: "stdio",
2812
- command: signerCommand?.command ?? "npx",
2813
- args: signerCommand?.args ?? ["-y", signerPackageSpec(), "--credentials", input.signerPath],
2814
- env: {}
2815
- });
2816
- try {
2817
- const names = serverNamesFor(input.serverName);
2818
- await runCommand("claude", ["mcp", "remove", names.hosted]).catch(() => void 0);
2819
- await runCommand("claude", ["mcp", "remove", names.signer]).catch(() => void 0);
2820
- await runCommand("claude", ["mcp", "add-json", names.hosted, hostedJson, "--scope", "user"]);
2821
- await runCommand("claude", ["mcp", "add-json", names.signer, signerJson, "--scope", "user"]);
2822
- const verified = await runCommand("claude", ["mcp", "get", names.hosted]).then(() => true).catch(() => false);
2823
- return {
2824
- hostedConfigured: true,
2825
- signerConfigured: true,
2826
- localMcpConfigured: false,
2827
- runtimeMcpMode: "hosted_plus_signer",
2828
- target: "Claude Code MCP config",
2829
- changed: true,
2830
- restartRequired: true,
2831
- messages: [
2832
- "Updated hosted Haven MCP and local signer entries with Claude Code.",
2833
- ...verified ? ["Verified Claude Code MCP entry."] : []
2834
- ]
2835
- };
2836
- } catch (err) {
2837
- return {
2838
- hostedConfigured: false,
2839
- signerConfigured: false,
2840
- localMcpConfigured: false,
2841
- runtimeMcpMode: "hosted_plus_signer",
2842
- target: "Claude Code MCP config",
2843
- changed: false,
2844
- restartRequired: true,
2845
- messages: [
2846
- `Could not update Claude Code MCP config: ${err instanceof Error ? err.message : String(err)}`,
2847
- "Install Claude Code or rerun the Haven setup command inside a Claude Code terminal."
2848
- ],
2849
- errorCode: "claude_code_config_failed"
3282
+ const inventory = [];
3283
+ const capabilitiesByDirectory = /* @__PURE__ */ new Map();
3284
+ const primaryChecksById = /* @__PURE__ */ new Map();
3285
+ for (const dir of allDirectories) {
3286
+ const identity = await readIdentity(dir);
3287
+ const sidecar = await readRuntimeSidecar(dir);
3288
+ const tombstone = await readAgentTombstone(dir);
3289
+ const slug = sidecar?.server_name;
3290
+ const names = serverNamesFor(slug);
3291
+ const rekeyPending = await inspectRekeyPending(dir, deps.now?.() ?? Date.now());
3292
+ if (!identity?.api_key) {
3293
+ const agentId = tombstone?.agent_id ?? rekeyPending?.agentId;
3294
+ inventory.push({
3295
+ ...slug ? { slug } : {},
3296
+ ...agentId ? { agentId } : {},
3297
+ directory: dir,
3298
+ // A tombstone is a deliberate record and outranks the discovery tell:
3299
+ // a retired directory that also holds a parked key stays `retired`.
3300
+ classification: tombstone ? "retired" : parkedOnly.has(dir) ? "parked" : "orphaned",
3301
+ checks: rekeyPending ? [rekeyPendingCheck(rekeyPending, void 0, input.runtime, slug)] : [],
3302
+ ...rekeyPending ? { rekeyPending } : {}
3303
+ });
3304
+ continue;
3305
+ }
3306
+ const wired = agentIsWired(configText, names, slug, identity, sidecar, dir === directory, bareOwnerExists);
3307
+ const entry = {
3308
+ ...slug ? { slug } : {},
3309
+ ...identity.agent_id ? { agentId: identity.agent_id } : {},
3310
+ directory: dir,
3311
+ classification: wired ? "wired" : "superseded",
3312
+ checks: [],
3313
+ ...rekeyPending ? { rekeyPending } : {}
2850
3314
  };
3315
+ if (wired) {
3316
+ const result = await checksForAgent({ directory: dir, identity, sidecar }, input, deps);
3317
+ entry.checks = result.checks;
3318
+ capabilitiesByDirectory.set(dir, result.signerCapabilities);
3319
+ } else if (rekeyPending) {
3320
+ entry.checks = [rekeyPendingCheck(rekeyPending, void 0, input.runtime, slug)];
3321
+ }
3322
+ inventory.push(entry);
2851
3323
  }
2852
- }
2853
- async function defaultRunCommand(command, args) {
2854
- await execFileAsync3(command, args, { timeout: 1e4 });
2855
- }
2856
- function buildProbeResult(mode, hostedConfigured, hostedStatus, signerReady, localMcpReady, localMcpProbeStatus) {
2857
- if (mode === "local_stdio") {
2858
- if (localMcpReady) return "local_stdio_mcp_ready";
2859
- return localMcpProbeStatus ? `local_stdio_mcp_${localMcpProbeStatus}` : "local_stdio_mcp_unavailable";
3324
+ const wiredDirectories = inventory.filter((entry) => entry.classification === "wired").map((entry) => entry.directory);
3325
+ const primaryDirectory = input.credentialsDir ? directory : wiredDirectories.includes(directory ?? "") ? directory : wiredDirectories[0] ?? directory;
3326
+ if (primaryDirectory) {
3327
+ const primaryEntry = inventory.find((entry) => entry.directory === primaryDirectory);
3328
+ signerCapabilities = capabilitiesByDirectory.get(primaryDirectory);
3329
+ for (const check of primaryEntry?.checks ?? []) primaryChecksById.set(check.id, check);
3330
+ }
3331
+ if (!primaryDirectory) {
3332
+ checks.push({
3333
+ id: "credentials",
3334
+ label: "Agent credentials",
3335
+ ok: false,
3336
+ detail: "No agent credential directory with an identity.json under ~/.haven/agents.",
3337
+ repair: `Run the full setup once: ${RERUN} --setup <token from the Haven dashboard>.`
3338
+ });
3339
+ } else {
3340
+ const primaryIdentity = await readIdentity(primaryDirectory);
3341
+ const primarySidecar = await readRuntimeSidecar(primaryDirectory);
3342
+ if (!primaryChecksById.has("credentials")) {
3343
+ const result = await checksForAgent(
3344
+ { directory: primaryDirectory, identity: primaryIdentity, sidecar: primarySidecar },
3345
+ input,
3346
+ deps
3347
+ );
3348
+ signerCapabilities = result.signerCapabilities;
3349
+ for (const check of result.checks) primaryChecksById.set(check.id, check);
3350
+ }
3351
+ for (const id of ["credentials", "signer_runtime"]) {
3352
+ const check = primaryChecksById.get(id);
3353
+ if (check) checks.push(check);
3354
+ }
3355
+ }
3356
+ if (configPath === null) {
3357
+ checks.push({
3358
+ id: "runtime_config",
3359
+ label: "Runtime MCP config",
3360
+ ok: true,
3361
+ detail: `Runtime '${input.runtime}' has no file-based config the connector owns (CLI-managed) \u2014 skipping the file check.`
3362
+ });
3363
+ } else if (configText === null) {
3364
+ checks.push({
3365
+ id: "runtime_config",
3366
+ label: "Runtime MCP config",
3367
+ ok: false,
3368
+ detail: `No runtime config at ${configPath}.`,
3369
+ repair: `Run: ${RERUN} --doctor --repair --runtime ${input.runtime}`
3370
+ });
3371
+ } else {
3372
+ const primaryIdentity = await readIdentity(primaryDirectory ?? "");
3373
+ const primarySidecar = primaryDirectory ? await readRuntimeSidecar(primaryDirectory) : null;
3374
+ const hasHaven = primaryIdentity?.hosted_mcp_url ? configText.includes(primaryIdentity.hosted_mcp_url) : configText.includes("haven");
3375
+ const signerViaNpx = configText.includes("@haven_ai/signer");
3376
+ const wrapperReferenced = primarySidecar ? configText.includes(primarySidecar.wrapper_path) : false;
3377
+ const ok = hasHaven && !signerViaNpx && (primarySidecar ? wrapperReferenced : true);
3378
+ checks.push({
3379
+ id: "runtime_config",
3380
+ label: "Runtime MCP config",
3381
+ ok,
3382
+ 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)" : ""}.`,
3383
+ ...ok ? {} : { repair: `Run: ${RERUN} --doctor --repair --runtime ${input.runtime}` }
3384
+ });
2860
3385
  }
2861
- const hostedPart = hostedConfigured ? `hosted_${hostedStatus}` : "hosted_not_configured";
2862
- const signerPart = signerReady ? "local_signer_ready" : "local_signer_unavailable";
2863
- return `${hostedPart}_${signerPart}`.slice(0, 120);
2864
- }
2865
- async function resolveLocalMcpConsent(input, messages) {
2866
- if (input.ackLocalTools || input.ackSigner) {
2867
- const status = await acknowledgeLocalMcpConsent(input.identityPath, input.signerPath, (message) => messages.push(message));
2868
- if (status.acknowledged) {
2869
- messages.push("Prepared the local Haven tools acknowledgement.");
2870
- } else {
2871
- messages.push("Local Haven tools acknowledgement still needs attention.");
2872
- }
2873
- return status;
3386
+ for (const id of ["hosted_mcp", "identity_match", "rekey_pending"]) {
3387
+ const check = primaryChecksById.get(id);
3388
+ if (check) checks.push(check);
2874
3389
  }
2875
- return getLocalMcpConsentStatus(input.identityPath, input.signerPath);
2876
- }
2877
- async function resolveSignerConsent(input, messages) {
2878
- if (input.ackSigner || input.ackLocalTools) {
2879
- const status = await acknowledgeLocalSignerConsent(input.signerPath, (message) => messages.push(message));
2880
- if (status.acknowledged) {
2881
- messages.push("Prepared the local Haven signer acknowledgement.");
2882
- } else {
2883
- messages.push("Local Haven signer acknowledgement still needs attention.");
3390
+ const otherEntries = inventory.filter((entry) => entry.directory !== primaryDirectory);
3391
+ if (otherEntries.length > 0) {
3392
+ const live = [];
3393
+ const revoked = [];
3394
+ const unverifiable = [];
3395
+ const retired = [];
3396
+ for (const entry of otherEntries) {
3397
+ const identity = await readIdentity(entry.directory);
3398
+ const tombstone = await readAgentTombstone(entry.directory);
3399
+ const otherAgent = entry.agentId ?? path.basename(entry.directory);
3400
+ const otherUrl = identity?.hosted_mcp_url ?? (identity?.api_url ? `${identity.api_url}/mcp` : void 0);
3401
+ if (!identity?.api_key || !otherUrl) {
3402
+ if (tombstone) retired.push(`${otherAgent} (retired ${tombstone.retired_at})`);
3403
+ else unverifiable.push(`${otherAgent} (no stored key/URL to probe)`);
3404
+ continue;
3405
+ }
3406
+ const suffix = tombstone ? " [tombstoned \u2014 key material still present]" : "";
3407
+ const probe = await (deps.probeHosted ?? probeHostedMcpTools)(identity.api_key, otherUrl, deps.fetch);
3408
+ if (probe.status === "ok") live.push({ label: `${otherAgent}${suffix}`, entry });
3409
+ else if (probe.status === "unauthorized") revoked.push(`${otherAgent}${suffix}`);
3410
+ else unverifiable.push(`${otherAgent} (${probe.status})${suffix}`);
2884
3411
  }
2885
- return status;
3412
+ const parts = [];
3413
+ if (live.length > 0) parts.push(`STILL SPEND-CAPABLE: ${live.map((item) => item.label).join(", ")}`);
3414
+ if (revoked.length > 0) parts.push(`already revoked: ${revoked.join(", ")}`);
3415
+ if (retired.length > 0) parts.push(`tombstoned (keys removed): ${retired.join(", ")}`);
3416
+ if (unverifiable.length > 0) parts.push(`could not verify: ${unverifiable.join(", ")}`);
3417
+ const supersededLive = live.filter((item) => item.entry.classification !== "wired").map((item) => item.label);
3418
+ checks.push({
3419
+ id: "superseded_agents",
3420
+ label: "Superseded agent credentials",
3421
+ ok: supersededLive.length === 0,
3422
+ 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("; ")}.`,
3423
+ ...supersededLive.length > 0 ? {
3424
+ 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.`
3425
+ } : {}
3426
+ });
2886
3427
  }
2887
- return getLocalSignerConsentStatus(input.signerPath);
2888
- }
2889
- function signerConsentErrorCode(signerCredentialReady, signerConsent) {
2890
- if (!signerCredentialReady) return "local_signer_credential_unavailable";
2891
- if (!signerConsent?.acknowledged) return "local_signer_ack_required";
2892
- return void 0;
2893
- }
2894
- function signerProbeErrorCode(probe) {
2895
- if (!probe || probe.status === "ok") return void 0;
2896
- return `local_signer_probe_${probe.status}`;
2897
- }
2898
- function hostedMcpErrorCode(hostedConfigured, hostedProbeStatus) {
2899
- if (!hostedConfigured || hostedProbeStatus === "ok") return void 0;
2900
- return `hosted_mcp_probe_${hostedProbeStatus}`;
2901
- }
2902
- function localMcpErrorCode(signerCredentialReady, localMcpConsent, localMcpProbeStatus) {
2903
- if (!signerCredentialReady) return "local_signer_credential_unavailable";
2904
- if (!localMcpConsent?.acknowledged) return "local_mcp_ack_required";
2905
- if (localMcpProbeStatus && localMcpProbeStatus !== "ok") return `local_mcp_probe_${localMcpProbeStatus}`;
2906
- return void 0;
2907
- }
2908
- function nextAction(runtime, restartMode, errorCode) {
2909
- if (errorCode) return "return_to_haven_for_wallet_approval_then_finish_runtime_setup";
2910
- if (restartMode === "hot-reload") return "return_to_haven_for_wallet_approval";
2911
- if (runtime === "codex-cli" || runtime === "codex-desktop") return "return_to_haven_for_wallet_approval_then_restart_codex";
2912
- if (runtime === "claude-code") return "return_to_haven_for_wallet_approval_then_restart_claude_code";
2913
- if (restartMode === "restart-app") return "return_to_haven_for_wallet_approval_then_restart_app";
2914
- if (restartMode === "restart-session") return "return_to_haven_for_wallet_approval_then_restart_agent_session";
2915
- return "return_to_haven_for_wallet_approval_then_configure_runtime";
2916
- }
2917
- function supportsLocalMcp(runtime) {
2918
- return runtime === "codex-cli" || runtime === "codex-desktop" || runtime === "claude-code";
2919
- }
2920
- async function prepareRuntimeForLocalMcp(input, deps) {
2921
- const prepare = deps.prepareLocalMcpRuntime ?? ((runtimeInput) => prepareLocalMcpRuntime(runtimeInput, { runCommand: deps.runCommand, onProgress: deps.onProgress }));
2922
- return prepare({
2923
- credentialDirectory: input.credentialDirectory,
2924
- identityPath: input.identityPath,
2925
- signerPath: input.signerPath,
2926
- homeDir: deps.homeDir,
2927
- serverName: input.serverName
2928
- });
2929
- }
2930
- async function prepareSignerForRuntime(input, deps) {
2931
- const prepare = deps.prepareSignerRuntime ?? ((runtimeInput) => (
2932
- // onProgress threaded through on purpose (#1586 review): without it the
2933
- // install heartbeat was dead code in production and the console still
2934
- // went silent for the whole cold install — the exact symptom the issue
2935
- // set out to remove, at a longer timeout.
2936
- prepareSignerRuntime(runtimeInput, { runCommand: deps.runCommand, onProgress: deps.onProgress })
2937
- ));
2938
- return prepare({
2939
- credentialDirectory: input.credentialDirectory,
2940
- signerPath: input.signerPath,
2941
- homeDir: deps.homeDir,
2942
- serverName: input.serverName
3428
+ const parkedElsewhere = inventory.filter((entry) => entry.directory !== primaryDirectory && entry.rekeyPending).map((entry) => ({ entry, pending: entry.rekeyPending }));
3429
+ if (parkedElsewhere.length > 0) {
3430
+ const abandoned = parkedElsewhere.filter((item) => item.pending.state !== "pending");
3431
+ const describe = (item) => `${item.entry.slug ?? item.entry.agentId ?? path.basename(item.entry.directory)} (${item.pending.state}, ${item.pending.path})`;
3432
+ checks.push({
3433
+ id: "rekey_pending_elsewhere",
3434
+ label: "Parked re-keys in other credential directories",
3435
+ ok: abandoned.length === 0,
3436
+ 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(", ")}.`,
3437
+ ...abandoned.length > 0 ? {
3438
+ 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."
3439
+ } : {}
3440
+ });
3441
+ }
3442
+ const signerProcess = primaryChecksById.get("signer_process");
3443
+ if (signerProcess) checks.push(signerProcess);
3444
+ const restart = restartRequiredForRuntime(input.runtime, deps.env);
3445
+ checks.push({
3446
+ id: "restart",
3447
+ label: "Runtime restart",
3448
+ ok: true,
3449
+ 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."
2943
3450
  });
3451
+ const wiredOk = inventory.filter((entry) => entry.classification === "wired").every((entry) => entry.checks.every((check) => check.ok));
3452
+ return {
3453
+ version: 1,
3454
+ ok: checks.every((check) => check.ok) && wiredOk,
3455
+ runtime: input.runtime,
3456
+ credentialDirectory: primaryDirectory,
3457
+ checks,
3458
+ agents: inventory,
3459
+ ...signerCapabilities ? { signerCapabilities } : {}
3460
+ };
2944
3461
  }
2945
- async function runLocalMcpProbe(runtimeInstall, deps) {
2946
- const probe = deps.probeLocalMcpTools ?? probeLocalMcpTools;
3462
+ async function runRepair(input, deps = {}) {
3463
+ const homeDir = deps.homeDir ?? os.homedir();
3464
+ const messages = [];
3465
+ const { directory, others } = await discoverCredentialDirectory(homeDir, input.credentialsDir);
3466
+ if (others.length > 0) {
3467
+ messages.push(`Note: ${others.length} other agent credential dir(s) exist \u2014 run --doctor for their status.`);
3468
+ }
3469
+ if (!directory) {
3470
+ return {
3471
+ ok: false,
3472
+ messages: [`No agent credentials found to repair \u2014 run the full setup: ${RERUN} --setup <token>.`]
3473
+ };
3474
+ }
3475
+ let identity;
2947
3476
  try {
2948
- return await probe(runtimeInstall.command, runtimeInstall.args, MCP_RUNTIME_MANIFEST.requiredTools);
3477
+ identity = JSON.parse(await promises.readFile(path.join(directory, "identity.json"), "utf8"));
2949
3478
  } catch {
2950
- return { status: "process_error" };
3479
+ return { ok: false, messages: ["identity.json is unreadable \u2014 re-run the full setup with a fresh token."] };
2951
3480
  }
2952
- }
2953
- function localRuntimePrepareErrorCode(err) {
2954
- if (err && typeof err === "object" && "code" in err && err.code === "local_mcp_unsupported_node_version") {
2955
- return "local_mcp_unsupported_node_version";
3481
+ if (!identity.api_key || !(identity.hosted_mcp_url || identity.api_url)) {
3482
+ return { ok: false, messages: ["identity.json lacks the stored API key / hosted URL \u2014 re-run the full setup."] };
2956
3483
  }
2957
- return "local_mcp_runtime_install_failed";
3484
+ const configPath = runtimeConfigPathFor(input.runtime, homeDir);
3485
+ if (configPath) {
3486
+ try {
3487
+ const existing = await promises.readFile(configPath, "utf8");
3488
+ if (existing.includes("bin/haven-mcp") || existing.includes(".haven/mcp-runtime")) {
3489
+ return {
3490
+ ok: false,
3491
+ messages: [
3492
+ `The config at ${configPath} is the LOCAL-stdio topology (--local). Repair currently rewrites only the hosted+signer shape and will not touch it.`,
3493
+ "Re-run your original setup command (with --local) to repair a local-stdio install."
3494
+ ]
3495
+ };
3496
+ }
3497
+ } catch {
3498
+ }
3499
+ }
3500
+ const existingSidecar = await readRuntimeSidecar(directory);
3501
+ const serverName = existingSidecar?.server_name;
3502
+ const signerPath = path.join(directory, "signer.json");
3503
+ const prepared = await prepareSignerRuntime(
3504
+ { credentialDirectory: directory, signerPath, homeDir, serverName },
3505
+ { runCommand: deps.runCommand }
3506
+ );
3507
+ messages.push(...prepared.messages);
3508
+ const names = serverNamesFor(serverName);
3509
+ messages.push(`Rewriting MCP entries ${names.hosted} / ${names.signer}${serverName ? ` (agent "${serverName}")` : " (unnamed pair)"} \u2014 no other pair is touched.`);
3510
+ const configResult = await writeRuntimeConfig({
3511
+ runtime: input.runtime,
3512
+ hostedMcpUrl: identity.hosted_mcp_url ?? `${identity.api_url}/mcp`,
3513
+ apiKey: identity.api_key,
3514
+ identityPath: path.join(directory, "identity.json"),
3515
+ signerPath,
3516
+ credentialDirectory: directory,
3517
+ signerCommand: { command: prepared.command, args: prepared.args },
3518
+ homeDir,
3519
+ mode: "hosted",
3520
+ serverName
3521
+ });
3522
+ messages.push(...configResult.messages);
3523
+ messages.push("Repair complete \u2014 restart the runtime, then verify with --doctor.");
3524
+ return { ok: true, messages };
2958
3525
  }
3526
+ var RERUN;
3527
+ var init_doctor = __esm({
3528
+ "src/doctor.ts"() {
3529
+ init_runtime_manifest();
3530
+ init_probes();
3531
+ init_signer_runtime();
3532
+ init_config_writers();
3533
+ init_runtime_registry();
3534
+ init_signer_consent();
3535
+ init_tombstone();
3536
+ init_server_names();
3537
+ init_storage();
3538
+ init_redact();
3539
+ RERUN = "npx @haven_ai/connect@alpha";
3540
+ }
3541
+ });
2959
3542
 
2960
3543
  // src/runtime.ts
3544
+ init_api();
3545
+ init_key();
3546
+ init_redact();
3547
+ init_server_names();
3548
+ init_storage();
3549
+ init_runtime_install();
2961
3550
  init_runtime_registry();
2962
3551
  init_connect_error();
2963
3552
 
@@ -3130,8 +3719,9 @@ function defaultPromptIo() {
3130
3719
  }
3131
3720
 
3132
3721
  // src/runtime.ts
3722
+ init_local_mcp_runtime();
3133
3723
  init_runtime_manifest();
3134
- var CONNECTOR_VERSION = "0.1.29-alpha.0";
3724
+ var CONNECTOR_VERSION = "0.1.31-alpha.0";
3135
3725
  var CONNECT_OUTCOME_SCHEMA_VERSION = 1;
3136
3726
  async function runConnect(options, deps = {}) {
3137
3727
  assertSupportedNodeVersion(deps.nodeVersion, MCP_RUNTIME_MANIFEST.minimumNodeVersion);
@@ -3156,7 +3746,14 @@ async function runConnect(options, deps = {}) {
3156
3746
  throw new ConnectError(
3157
3747
  "runtime_undetermined",
3158
3748
  `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.`,
3159
- "rerun_connect_with_explicit_runtime"
3749
+ "rerun_connect_with_explicit_runtime",
3750
+ // #2091: the values must ride structurally too. The backend's setup
3751
+ // prompt permits a retry only with "one of the values that refusal
3752
+ // lists" — and --json discards prose, so a prose-only list deadlocked
3753
+ // every automation run in an undetected runtime (Codex in the field:
3754
+ // npx needs network, Codex runs network commands unsandboxed, and the
3755
+ // unsandboxed path carries none of the CODEX_* detection vars).
3756
+ { allowedRuntimes: RUNTIME_FLAG_VALUE_LIST }
3160
3757
  );
3161
3758
  }
3162
3759
  const runtime = selection.runtime;
@@ -3178,11 +3775,16 @@ async function runConnect(options, deps = {}) {
3178
3775
  log(`runtime: ${runtime} (chosen at the prompt \u2014 nothing was detected in this environment)`);
3179
3776
  }
3180
3777
  log("Warming up your connection to Haven\u2026");
3181
- const setup = await api.resolveSetup({
3182
- setupToken: options.setupToken,
3183
- connectorVersion,
3184
- runtime
3185
- });
3778
+ let setup;
3779
+ try {
3780
+ setup = await api.resolveSetup({
3781
+ setupToken: options.setupToken,
3782
+ connectorVersion,
3783
+ runtime
3784
+ });
3785
+ } catch (err) {
3786
+ throw deadSetupTokenError(err) ?? err;
3787
+ }
3186
3788
  assertSetupChallengeIsUsable(setup.challenge.expires_at);
3187
3789
  printSetupSummary(setup, log);
3188
3790
  await preflightStorage({ baseDir: options.credentialsDir, warn: log });
@@ -3207,6 +3809,11 @@ async function runConnect(options, deps = {}) {
3207
3809
  proofSignature,
3208
3810
  apiKeyHash: hashAgentApiKey(localApiKey),
3209
3811
  apiKeyPrefix: agentApiKeyPrefix(localApiKey),
3812
+ // #1878: report the pair we are ACTUALLY wiring, bare pair included, so
3813
+ // the dashboard can name it. Derived here rather than sent as the raw
3814
+ // slug — `serverNamesFor` is the one place the naming rule lives, and
3815
+ // the hosted name is what a user pastes into an MCP config.
3816
+ mcpServerName: serverNamesFor(options.serverName).hosted,
3210
3817
  connectorContext: {
3211
3818
  environment_label: options.environmentLabel ?? "Local workspace",
3212
3819
  config_target: installCapabilities.canWriteRuntimeConfig ? "agent runtime MCP config" : "local credential files"
@@ -3214,6 +3821,8 @@ async function runConnect(options, deps = {}) {
3214
3821
  installCapabilities
3215
3822
  });
3216
3823
  } catch (err) {
3824
+ const dead = deadSetupTokenError(err);
3825
+ if (dead) throw dead;
3217
3826
  if (isExpiredSetupChallenge(err)) {
3218
3827
  throw new Error(
3219
3828
  "The Haven setup challenge expired while connecting. Return to Haven, start a fresh connection, and run its new Connect command. Do not reuse or paste credentials."
@@ -3411,7 +4020,17 @@ function failedConnectOutcome(runtimeHint, error) {
3411
4020
  tools: ["haven_get_agent", "haven_get_allowances"],
3412
4021
  instruction: "After a successful setup and activation, verify only with haven_get_agent and haven_get_allowances."
3413
4022
  },
3414
- error: { code, next_action: nextAction2 }
4023
+ error: {
4024
+ code,
4025
+ next_action: nextAction2,
4026
+ // Only a ConnectError's message enters the JSON record: the vocabulary's
4027
+ // prose is connector-authored and safe to serialize, while a plain
4028
+ // Error can carry arbitrary server or filesystem detail (that stance is
4029
+ // pinned by test). Redaction stays on as belt-and-braces; plain-Error
4030
+ // runs still get their redacted message on stderr via the CLI mirror.
4031
+ ...error instanceof ConnectError && message ? { message: redactForAutomation(message) } : {},
4032
+ ...error instanceof ConnectError && error.details.allowedRuntimes ? { allowed_runtimes: error.details.allowedRuntimes } : {}
4033
+ }
3415
4034
  };
3416
4035
  }
3417
4036
  function printSetupSummary(setup, log) {
@@ -3433,16 +4052,20 @@ function assertSetupChallengeIsUsable(expiresAt) {
3433
4052
  "This Haven setup challenge is expired or invalid. Return to Haven, start a fresh connection, and rerun Connect. No local credentials were written."
3434
4053
  );
3435
4054
  }
4055
+ function deadSetupTokenError(err) {
4056
+ if (!(err instanceof ConnectRequestError) || err.status !== 410 && err.status !== 401) return null;
4057
+ return new ConnectError(
4058
+ "setup_challenge_expired_or_invalid",
4059
+ "This Haven setup token is expired or invalid \u2014 tokens are single-use and expire 30 minutes after the dashboard issues them, and a mistyped token reads the same way. Return to Haven, start a fresh connection, and run its new Connect command. No local credentials were written.",
4060
+ "return_to_haven_for_fresh_setup"
4061
+ );
4062
+ }
3436
4063
  function isExpiredSetupChallenge(err) {
3437
4064
  return err instanceof Error && /(?:setup )?challenge.*expir|expir.*(?:setup )?challenge/i.test(err.message);
3438
4065
  }
3439
4066
  function secureLogger(log, redactPaths = false) {
3440
4067
  return (message) => {
3441
- let safe = redactSecrets(message);
3442
- if (redactPaths) {
3443
- safe = safe.replace(/(?:~|\/)[^\s`"']*\/(?:identity|signer|agent)\.json\b/g, "[credential-file-redacted]").replace(/(?:~|\/)[^\s`"']*\/\.env\b/g, "[credential-env-redacted]");
3444
- }
3445
- log(safe);
4068
+ log(redactPaths ? redactForAutomation(message) : redactSecrets(message));
3446
4069
  };
3447
4070
  }
3448
4071
  function printRuntimeInstall(result, log) {
@@ -3610,6 +4233,8 @@ function parseArgs(argv, env = process.env) {
3610
4233
  let json = false;
3611
4234
  let doctor = false;
3612
4235
  let repair = false;
4236
+ let rekeyPhase;
4237
+ let newApiKey;
3613
4238
  let tombstoneDir;
3614
4239
  let tombstoneReason;
3615
4240
  let tombstoneReplacedBy;
@@ -3623,6 +4248,12 @@ function parseArgs(argv, env = process.env) {
3623
4248
  doctor = true;
3624
4249
  } else if (arg === "--repair") {
3625
4250
  repair = true;
4251
+ } else if (arg === "--rekey") {
4252
+ rekeyPhase = "start";
4253
+ } else if (arg === "--rekey-finish") {
4254
+ rekeyPhase = "finish";
4255
+ } else if (arg === "--api-key") {
4256
+ newApiKey = requireValue(argv, ++i, arg);
3626
4257
  } else if (arg === "--tombstone") {
3627
4258
  tombstoneDir = requireValue(argv, ++i, arg);
3628
4259
  } else if (arg === "--reason") {
@@ -3660,20 +4291,38 @@ function parseArgs(argv, env = process.env) {
3660
4291
  }
3661
4292
  }
3662
4293
  const tombstone = tombstoneDir ? { directory: tombstoneDir, reason: tombstoneReason, replacedBy: tombstoneReplacedBy } : void 0;
4294
+ const rekey = rekeyPhase ? { phase: rekeyPhase, newApiKey } : void 0;
3663
4295
  if (help) {
3664
- return { options, help, json, doctor, repair, tombstone };
4296
+ return { options, help, json, doctor, repair, tombstone, rekey };
4297
+ }
4298
+ if (rekey) {
4299
+ if (options.setupToken) {
4300
+ throw new Error("--rekey replaces an existing agent's key; it does not take --setup. Drop one of them.");
4301
+ }
4302
+ if (rekey.phase === "start" && newApiKey !== void 0) {
4303
+ throw new Error(
4304
+ "--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."
4305
+ );
4306
+ }
4307
+ if (rekey.phase === "finish" && !newApiKey) {
4308
+ throw new Error("--rekey-finish needs --api-key <key> \u2014 the one the Haven agent page showed once.");
4309
+ }
4310
+ return { options, help, json, doctor, repair, tombstone, rekey };
4311
+ }
4312
+ if (newApiKey !== void 0) {
4313
+ throw new Error("--api-key requires --rekey-finish.");
3665
4314
  }
3666
4315
  if (!tombstoneDir && (tombstoneReason !== void 0 || tombstoneReplacedBy !== void 0)) {
3667
4316
  throw new Error("--reason and --replaced-by require --tombstone <dir>.");
3668
4317
  }
3669
4318
  if (tombstone) {
3670
- return { options, help, json, doctor, repair, tombstone };
4319
+ return { options, help, json, doctor, repair, tombstone, rekey };
3671
4320
  }
3672
4321
  if (doctor || repair) {
3673
4322
  if (!options.runtime) {
3674
4323
  throw new Error("--doctor/--repair need --runtime <runtime> (which config to examine).");
3675
4324
  }
3676
- return { options, help, json, doctor, repair, tombstone };
4325
+ return { options, help, json, doctor, repair, tombstone, rekey };
3677
4326
  }
3678
4327
  if (!options.setupToken) {
3679
4328
  throw new Error("Missing --setup <hv_setup_...> setup token.");
@@ -3682,7 +4331,7 @@ function parseArgs(argv, env = process.env) {
3682
4331
  throw new Error("Missing --api <Haven API URL>.");
3683
4332
  }
3684
4333
  options.apiBaseUrl = options.apiBaseUrl.replace(/\/+$/, "");
3685
- return { options, help, json, doctor, repair, tombstone };
4334
+ return { options, help, json, doctor, repair, tombstone, rekey };
3686
4335
  }
3687
4336
  function helpText() {
3688
4337
  return [
@@ -3719,6 +4368,14 @@ function helpText() {
3719
4368
  " --repair Repair, then re-diagnose (implies --doctor): reinstall the pinned signer",
3720
4369
  " runtime, rewrite the wrapper and runtime config from stored credentials.",
3721
4370
  " Hosted topology only (refuses to touch a --local config). No keys, no token.",
4371
+ " --rekey Replace this agent's signing key (no token). Generates a fresh keypair HERE and",
4372
+ " prints its public address to paste into the Haven agent page. Nothing changes",
4373
+ " until you finish; the agent keeps working on its old key throughout.",
4374
+ " Add --name <slug> for a named agent. Refuses a legacy-rail or revoked agent.",
4375
+ " --rekey-finish Second half of --rekey: writes the new key and the API key the agent page",
4376
+ " showed once, in place at the same path, and rewrites only this agent's MCP",
4377
+ " config pair. Server names do not change, so wired hosts need only a restart.",
4378
+ " --api-key <key> The new API key, for --rekey-finish.",
3722
4379
  " --tombstone <dir> Retire an agent credential directory in place (no token): replaces its signer",
3723
4380
  " wrapper with a diagnostic that names the retirement in MCP stderr logs, and",
3724
4381
  " writes TOMBSTONE.json. Touches NO key material and revokes nothing.",
@@ -3749,6 +4406,8 @@ async function runCli(argv, io = {
3749
4406
  parsed = parseArgs(argv);
3750
4407
  } catch (err) {
3751
4408
  if (wantsJson) {
4409
+ io.stderr(`${redactForAutomation(err instanceof Error ? err.message : String(err))}
4410
+ `);
3752
4411
  io.stdout(`${JSON.stringify(failedConnectOutcome(void 0, err))}
3753
4412
  `);
3754
4413
  } else {
@@ -3764,13 +4423,13 @@ async function runCli(argv, io = {
3764
4423
  }
3765
4424
  if (parsed.tombstone) {
3766
4425
  const { writeAgentTombstone: writeAgentTombstone2 } = await Promise.resolve().then(() => (init_tombstone(), tombstone_exports));
3767
- const { readFile: readFile11 } = await import('fs/promises');
4426
+ const { readFile: readFile12 } = await import('fs/promises');
3768
4427
  const { join: join10 } = await import('path');
3769
4428
  try {
3770
4429
  let agentId = "unknown";
3771
4430
  try {
3772
4431
  const identity = JSON.parse(
3773
- await readFile11(join10(parsed.tombstone.directory, "identity.json"), "utf8")
4432
+ await readFile12(join10(parsed.tombstone.directory, "identity.json"), "utf8")
3774
4433
  );
3775
4434
  agentId = identity.agent_id ?? "unknown";
3776
4435
  } catch {
@@ -3797,6 +4456,64 @@ async function runCli(argv, io = {
3797
4456
  return 0;
3798
4457
  } catch (err) {
3799
4458
  io.stderr(`${redactSecrets(err instanceof Error ? err.message : String(err))}
4459
+ `);
4460
+ return 1;
4461
+ }
4462
+ }
4463
+ if (parsed.rekey) {
4464
+ const { startRekey: startRekey2, finishRekey: finishRekey2 } = await Promise.resolve().then(() => (init_rekey(), rekey_exports));
4465
+ const { restartGuidance: restartGuidance2 } = await Promise.resolve().then(() => (init_rekey_restart(), rekey_restart_exports));
4466
+ const common = {
4467
+ serverName: parsed.options.serverName,
4468
+ credentialsDir: parsed.options.credentialsDir,
4469
+ runtime: parsed.options.runtime
4470
+ };
4471
+ try {
4472
+ if (parsed.rekey.phase === "start") {
4473
+ const result2 = await startRekey2(common);
4474
+ if (parsed.json) {
4475
+ io.stdout(
4476
+ `${redactSecrets(
4477
+ JSON.stringify({
4478
+ rekey: "started",
4479
+ agent_id: result2.agentId,
4480
+ new_delegate_address: result2.newDelegateAddress,
4481
+ expires_at: result2.expiresAt
4482
+ })
4483
+ )}
4484
+ `
4485
+ );
4486
+ } else {
4487
+ for (const line of result2.messages) io.stdout(redactSecrets(`${line}
4488
+ `));
4489
+ }
4490
+ return 0;
4491
+ }
4492
+ const result = await finishRekey2({ ...common, newApiKey: parsed.rekey.newApiKey });
4493
+ const restart = restartGuidance2(parsed.options.runtime);
4494
+ if (parsed.json) {
4495
+ io.stdout(
4496
+ `${redactSecrets(
4497
+ JSON.stringify({
4498
+ rekey: "finished",
4499
+ agent_id: result.agentId,
4500
+ new_delegate_address: result.newDelegateAddress,
4501
+ mcp_servers: result.serverNames,
4502
+ restart_commands: restart.commands
4503
+ })
4504
+ )}
4505
+ `
4506
+ );
4507
+ } else {
4508
+ for (const line of result.messages) io.stdout(redactSecrets(`${line}
4509
+ `));
4510
+ io.stdout("\n");
4511
+ for (const line of restart.lines) io.stdout(redactSecrets(`${line}
4512
+ `));
4513
+ }
4514
+ return 0;
4515
+ } catch (err) {
4516
+ io.stderr(`${redactSecrets(err instanceof Error ? err.message : String(err))}
3800
4517
  `);
3801
4518
  return 1;
3802
4519
  }
@@ -3829,7 +4546,7 @@ async function runCli(argv, io = {
3829
4546
  for (const agent of otherAgents) {
3830
4547
  const name = agent.slug ? `${agent.slug} (${agent.agentId ?? "unknown"})` : agent.agentId ?? "unknown";
3831
4548
  const failed = agent.checks.filter((check) => !check.ok);
3832
- const verdict = agent.classification === "wired" ? failed.length === 0 ? "wired, all checks passed" : `wired, ${failed.length} check(s) FAILED` : agent.classification;
4549
+ 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;
3833
4550
  io.stdout(redactSecrets(` ${failed.length > 0 ? "\u2717" : "\u2022"} ${name}: ${verdict}
3834
4551
  `));
3835
4552
  for (const check of failed) {
@@ -3871,6 +4588,8 @@ async function runCli(argv, io = {
3871
4588
  return 0;
3872
4589
  } catch (err) {
3873
4590
  if (parsed.json) {
4591
+ io.stderr(`${redactForAutomation(err instanceof Error ? err.message : String(err))}
4592
+ `);
3874
4593
  io.stdout(`${JSON.stringify(failedConnectOutcome(parsed.options.runtime, err))}
3875
4594
  `);
3876
4595
  } else {