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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs CHANGED
@@ -1,19 +1,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,6 +31,125 @@ 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]");
@@ -93,116 +212,412 @@ var init_server_names = __esm({
93
212
  SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
94
213
  }
95
214
  });
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}`;
215
+ async function preflightCredentialStorage(input = {}) {
216
+ const directory = defaultCredentialRoot(input.baseDir);
217
+ await promises.mkdir(directory, { recursive: true, mode: 448 });
218
+ await restrictPermissions(directory, 448, input.warn);
219
+ const probePath = path.join(directory, `.haven-connect-preflight-${crypto__default.default.randomBytes(8).toString("hex")}`);
220
+ try {
221
+ await writeOwnerOnlyJson(probePath, { ok: true }, input.warn);
222
+ } finally {
223
+ await promises.rm(probePath, { force: true }).catch(() => void 0);
224
+ }
225
+ return directory;
104
226
  }
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
- };
227
+ async function writeCredentialFiles(input) {
228
+ const directory = defaultAgentDirectory(input.serverName ?? input.agentId, input.baseDir);
229
+ await promises.mkdir(directory, { recursive: true, mode: 448 });
230
+ await restrictPermissions(directory, 448, input.warn);
231
+ const identityPath = path.join(directory, "identity.json");
232
+ const signerPath = path.join(directory, "signer.json");
233
+ const agentPath = path.join(directory, "agent.json");
234
+ await assertDoesNotExist(identityPath);
235
+ await assertDoesNotExist(signerPath);
236
+ await assertDoesNotExist(agentPath);
237
+ await writeOwnerOnlyJson(signerPath, signerPayload(input), input.warn);
238
+ try {
239
+ await writeOwnerOnlyJson(identityPath, identityPayload(input), input.warn);
240
+ } catch (err) {
241
+ await promises.rm(signerPath, { force: true }).catch(() => void 0);
242
+ throw err;
132
243
  }
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
- };
244
+ try {
245
+ await writeOwnerOnlyJson(agentPath, agentPayload(input), input.warn);
246
+ } catch (err) {
247
+ await promises.rm(signerPath, { force: true }).catch(() => void 0);
248
+ await promises.rm(identityPath, { force: true }).catch(() => void 0);
249
+ await promises.rm(agentPath, { force: true }).catch(() => void 0);
250
+ throw err;
161
251
  }
252
+ return { directory, identityPath, signerPath, agentPath };
162
253
  }
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
- }
254
+ function signerPayload(input) {
171
255
  return {
172
- url: hostedMcpUrl,
173
- headers: { Authorization: `Bearer ${apiKey}` }
256
+ delegate_key: input.delegateKey,
257
+ delegate_address: input.delegateAddress,
258
+ agent_id: input.agentId,
259
+ safe_address: input.safeAddress,
260
+ chain_id: input.chainId,
261
+ network: input.network,
262
+ x402_binding_signer: input.x402BindingSigner,
263
+ note: "Local signer credential. Haven backend never receives this private key."
174
264
  };
175
265
  }
176
- function resolveSignerLaunchSpec(input) {
177
- return input.signerCommand ?? {
178
- command: "npx",
179
- args: ["-y", signerPackageSpec(), "--credentials", input.signerPath]
266
+ function identityPayload(input) {
267
+ return {
268
+ api_key: input.apiKey,
269
+ agent_id: input.agentId,
270
+ safe_address: input.safeAddress,
271
+ chain_id: input.chainId,
272
+ network: input.network,
273
+ api_url: input.apiUrl,
274
+ hosted_mcp_url: input.hostedMcpUrl,
275
+ agent_budget: input.agentBudget,
276
+ note: "Haven API key identifies the agent only. It cannot spend without the local signer key and on-chain Haven wallet rules."
180
277
  };
181
278
  }
182
- function buildSignerServer(spec, runtime) {
183
- const server = {
184
- command: spec.command,
185
- args: spec.args
279
+ function agentPayload(input) {
280
+ return {
281
+ agent_id: input.agentId,
282
+ delegate_address: input.delegateAddress,
283
+ safe_address: input.safeAddress,
284
+ chain_id: input.chainId,
285
+ network: input.network,
286
+ agent_budget: input.agentBudget,
287
+ note: "Non-secret orientation for the agent: public delegate/Haven wallet identity + configured budget. Contains no API key or signing key. For the live remaining budget, call haven_get_allowances."
186
288
  };
187
- if (runtime === "vscode" || runtime === "vscode-insiders") return { type: "stdio", ...server };
188
- return server;
189
289
  }
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
290
+ async function readStoredCredentials(serverName, agentIdOrSlug, baseDir) {
291
+ const key = serverName ?? agentIdOrSlug;
292
+ const directory = key ? defaultAgentDirectory(key, baseDir) : await discoverSoleAgentDirectory(baseDir);
293
+ const identity = await readJsonFile(path.join(directory, "identity.json"));
294
+ if (!identity) {
295
+ throw new Error(
296
+ `No Haven credentials at ${directory}. Nothing to re-key \u2014 connect this agent first, or pass the --name you wired it under.`
297
+ );
298
+ }
299
+ const agent = await readJsonFile(path.join(directory, "agent.json")) ?? {};
300
+ const signer = await readJsonFile(path.join(directory, "signer.json")) ?? {};
301
+ const agentId = asString(identity.agent_id);
302
+ const apiKey = asString(identity.api_key);
303
+ const apiUrl = asString(identity.api_url);
304
+ const hostedMcpUrl = asString(identity.hosted_mcp_url);
305
+ if (!agentId || !apiKey || !apiUrl || !hostedMcpUrl) {
306
+ throw new Error(
307
+ `The credential set at ${directory} is incomplete (identity.json is missing agent_id, api_key, api_url or hosted_mcp_url). Re-key cannot rebuild it \u2014 reconnect the agent instead.`
308
+ );
309
+ }
310
+ return {
311
+ directory,
312
+ agentId,
313
+ apiKey,
314
+ apiUrl,
315
+ hostedMcpUrl,
316
+ delegateAddress: asString(agent.delegate_address) ?? asString(signer.delegate_address),
317
+ safeAddress: asString(identity.safe_address) ?? asString(agent.safe_address),
318
+ chainId: typeof identity.chain_id === "number" ? identity.chain_id : void 0,
319
+ network: asString(identity.network),
320
+ x402BindingSigner: asString(signer.x402_binding_signer),
321
+ agentBudget: Array.isArray(identity.agent_budget) ? identity.agent_budget : void 0
198
322
  };
199
- return `${JSON.stringify(config, null, 2)}
200
- `;
201
323
  }
202
- function mergeHermesYaml(existingYaml, hostedServer, signerServer, names = serverNamesFor(), configPath) {
203
- if (!existingYaml?.trim()) {
204
- return renderHermesYaml({ [names.hosted]: hostedServer, [names.signer]: signerServer });
205
- }
324
+ async function discoverSoleAgentDirectory(baseDir) {
325
+ const root = defaultCredentialRoot(baseDir);
326
+ let entries = [];
327
+ try {
328
+ entries = await promises.readdir(root);
329
+ } catch {
330
+ throw new Error(`No Haven credentials found under ${root}. Connect an agent on this machine first.`);
331
+ }
332
+ const candidates = [];
333
+ for (const entry of entries) {
334
+ const directory = path.join(root, entry);
335
+ if (!await readJsonFile(path.join(directory, "identity.json"))) continue;
336
+ if (await readJsonFile(path.join(directory, "TOMBSTONE.json"))) continue;
337
+ candidates.push(directory);
338
+ }
339
+ if (candidates.length === 1) return candidates[0];
340
+ if (candidates.length === 0) {
341
+ throw new Error(`No Haven credentials found under ${root}. Connect an agent on this machine first.`);
342
+ }
343
+ throw new Error(
344
+ `Several agents are wired on this machine, so --rekey cannot tell which one you mean:
345
+ ` + candidates.map((d) => ` ${d}`).join("\n") + "\nRe-run with --name <slug> to pick one."
346
+ );
347
+ }
348
+ async function rewriteCredentialFiles(input) {
349
+ const directory = defaultAgentDirectory(input.serverName ?? input.agentId, input.baseDir);
350
+ const identityPath = path.join(directory, "identity.json");
351
+ const signerPath = path.join(directory, "signer.json");
352
+ const agentPath = path.join(directory, "agent.json");
353
+ const targets = [
354
+ { path: signerPath, payload: signerPayload(input) },
355
+ { path: identityPath, payload: identityPayload(input) },
356
+ { path: agentPath, payload: agentPayload(input) }
357
+ ];
358
+ const originals = /* @__PURE__ */ new Map();
359
+ for (const { path } of targets) {
360
+ originals.set(path, await readRawFile(path));
361
+ }
362
+ const temps = [];
363
+ try {
364
+ for (const { path, payload } of targets) {
365
+ const temp = `${path}.rekey-${crypto__default.default.randomBytes(6).toString("hex")}.tmp`;
366
+ await writeOwnerOnlyJson(temp, payload, input.warn);
367
+ temps.push({ from: temp, to: path });
368
+ }
369
+ for (const { from, to } of temps) {
370
+ await promises.rename(from, to);
371
+ }
372
+ } catch (err) {
373
+ for (const { from } of temps) await promises.rm(from, { force: true }).catch(() => void 0);
374
+ for (const [path, contents] of originals) {
375
+ if (contents === null) {
376
+ await promises.rm(path, { force: true }).catch(() => void 0);
377
+ } else {
378
+ await promises.writeFile(path, contents, { mode: 384 }).catch(() => void 0);
379
+ }
380
+ }
381
+ throw err;
382
+ }
383
+ return { directory, identityPath, signerPath, agentPath };
384
+ }
385
+ async function writeRekeyPending(directory, pending, warn) {
386
+ const path$1 = path.join(directory, REKEY_PENDING_FILENAME);
387
+ await promises.rm(path$1, { force: true }).catch(() => void 0);
388
+ await writeOwnerOnlyJson(path$1, { ...pending }, warn);
389
+ return path$1;
390
+ }
391
+ async function readRekeyPending(directory, now = Date.now()) {
392
+ const path$1 = path.join(directory, REKEY_PENDING_FILENAME);
393
+ const raw = await readJsonFile(path$1);
394
+ if (!raw) {
395
+ throw new Error(
396
+ `No re-key in progress at ${directory}. Run the connector with --rekey first \u2014 it prints the new signing address to paste into the Haven agent page.`
397
+ );
398
+ }
399
+ const pending = raw;
400
+ if (!pending.new_delegate_key || !pending.new_delegate_address || !pending.agent_id) {
401
+ throw new Error(`The pending re-key at ${path$1} is unreadable. Delete it and start again with --rekey.`);
402
+ }
403
+ if (pending.expires_at && Date.parse(pending.expires_at) < now) {
404
+ throw new Error(
405
+ `The re-key started at ${pending.started_at} has expired. Start again with --rekey \u2014 the address currently shown in your dashboard is no longer the one this machine holds.`
406
+ );
407
+ }
408
+ return pending;
409
+ }
410
+ async function inspectRekeyPending(directory, now = Date.now()) {
411
+ const path$1 = path.join(directory, REKEY_PENDING_FILENAME);
412
+ const raw = await readJsonFile(path$1);
413
+ if (!raw) {
414
+ const present = await readRawFile(path$1) !== null;
415
+ return present ? { state: "unreadable", path: path$1 } : null;
416
+ }
417
+ const agentId = asString(raw.agent_id);
418
+ const newDelegateAddress = asString(raw.new_delegate_address);
419
+ const startedAt = asString(raw.started_at);
420
+ const expiresAt = asString(raw.expires_at);
421
+ if (!agentId || !newDelegateAddress) {
422
+ return { state: "unreadable", path: path$1, ...startedAt ? { startedAt } : {} };
423
+ }
424
+ const expired = expiresAt !== void 0 && Date.parse(expiresAt) < now;
425
+ return {
426
+ state: expired ? "expired" : "pending",
427
+ path: path$1,
428
+ agentId,
429
+ newDelegateAddress,
430
+ ...startedAt ? { startedAt } : {},
431
+ ...expiresAt ? { expiresAt } : {}
432
+ };
433
+ }
434
+ async function clearRekeyPending(directory) {
435
+ await promises.rm(path.join(directory, REKEY_PENDING_FILENAME), { force: true }).catch(() => void 0);
436
+ }
437
+ async function readJsonFile(path) {
438
+ const raw = await readRawFile(path);
439
+ if (raw === null) return null;
440
+ try {
441
+ const parsed = JSON.parse(raw);
442
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
443
+ } catch {
444
+ return null;
445
+ }
446
+ }
447
+ async function readRawFile(path) {
448
+ try {
449
+ return await promises.readFile(path, "utf8");
450
+ } catch {
451
+ return null;
452
+ }
453
+ }
454
+ function asString(value) {
455
+ return typeof value === "string" && value.length > 0 ? value : void 0;
456
+ }
457
+ async function assertServerSlugAvailable(serverName, baseDir) {
458
+ const directory = defaultAgentDirectory(serverName, baseDir);
459
+ try {
460
+ await promises.stat(path.join(directory, "identity.json"));
461
+ } catch {
462
+ return;
463
+ }
464
+ throw new Error(
465
+ `The name "${serverName}" is already wired on this machine (${directory} holds credentials). Pick a different --name, or revoke and remove that agent first \u2014 connect never overwrites credentials.`
466
+ );
467
+ }
468
+ function defaultAgentDirectory(agentId, baseDir = path.join(os.homedir(), ".haven", "agents")) {
469
+ return path.resolve(defaultCredentialRoot(baseDir), safePathPart(agentId));
470
+ }
471
+ function defaultCredentialRoot(baseDir = path.join(os.homedir(), ".haven", "agents")) {
472
+ return path.resolve(baseDir);
473
+ }
474
+ async function writeOwnerOnlyJson(path, value, warn) {
475
+ const json = JSON.stringify(dropUndefined(value), null, 2);
476
+ await promises.writeFile(path, `${json}
477
+ `, { mode: 384, flag: "wx" });
478
+ await restrictPermissions(path, 384, warn);
479
+ }
480
+ function safePathPart(value) {
481
+ return value.replace(/[^A-Za-z0-9_.-]/g, "_");
482
+ }
483
+ function dropUndefined(value) {
484
+ return Object.fromEntries(Object.entries(value).filter(([, field]) => field !== void 0));
485
+ }
486
+ async function assertDoesNotExist(path) {
487
+ try {
488
+ await promises.access(path);
489
+ } catch (err) {
490
+ if (err && typeof err === "object" && "code" in err && err.code === "ENOENT") return;
491
+ throw err;
492
+ }
493
+ throw new Error(`Refusing to overwrite existing Haven credential file: ${path}`);
494
+ }
495
+ async function restrictPermissions(path, mode, warn) {
496
+ try {
497
+ await promises.chmod(path, mode);
498
+ } catch (err) {
499
+ warn?.(
500
+ `Warning: could not restrict permissions on ${path} to ${mode.toString(8)}. Move this credential to a private location or run chmod ${mode.toString(8)} ${path}. ${err instanceof Error ? err.message : String(err)}`
501
+ );
502
+ }
503
+ }
504
+ var REKEY_PENDING_FILENAME, REKEY_PENDING_TTL_MS;
505
+ var init_storage = __esm({
506
+ "src/storage.ts"() {
507
+ REKEY_PENDING_FILENAME = "rekey-pending.json";
508
+ REKEY_PENDING_TTL_MS = 24 * 60 * 60 * 1e3;
509
+ }
510
+ });
511
+ function mcpPackageSpec() {
512
+ return `${MCP_RUNTIME_MANIFEST.mcpPackage}@${MCP_RUNTIME_MANIFEST.mcpVersion}`;
513
+ }
514
+ function sdkPackageSpec() {
515
+ return `${MCP_RUNTIME_MANIFEST.sdkPackage}@${MCP_RUNTIME_MANIFEST.sdkVersion}`;
516
+ }
517
+ function signerPackageSpec() {
518
+ return `${MCP_RUNTIME_MANIFEST.signerPackage}@${MCP_RUNTIME_MANIFEST.signerVersion}`;
519
+ }
520
+ var MCP_RUNTIME_MANIFEST;
521
+ var init_runtime_manifest = __esm({
522
+ "src/runtime-manifest.ts"() {
523
+ MCP_RUNTIME_MANIFEST = {
524
+ mcpPackage: "@haven_ai/mcp",
525
+ mcpVersion: mcp.MCP_VERSION,
526
+ sdkPackage: "@haven_ai/sdk",
527
+ sdkVersion: "0.1.30-alpha.0",
528
+ signerPackage: "@haven_ai/signer",
529
+ signerVersion: "0.1.30-alpha.0",
530
+ // Sourced from the SDK, never a literal (#1161). This field read '20.0.0'
531
+ // while every package's `engines` said `>=24` and the docs said `>=24.0.0`,
532
+ // so the guard that was supposed to enforce the floor waved Node v23 through
533
+ // — including on the `--local` path where it does run. A hand-maintained
534
+ // second copy of a number is a drift waiting to happen; a guard test pins
535
+ // this against `package.json`'s `engines.node`.
536
+ minimumNodeVersion: sdk.HAVEN_MINIMUM_NODE_VERSION,
537
+ supportedClients: ["codex-cli", "codex-desktop", "claude-code"],
538
+ requiredTools: mcp.registeredToolNames(),
539
+ /**
540
+ * The signer MCP's tool surface, DERIVED from the pinned @haven_ai/signer
541
+ * package (#1587) — same anti-drift rule as `requiredTools` above: a
542
+ * literal list here would rot the first time the signer gains a tool.
543
+ * The handshake probe requires all of them.
544
+ */
545
+ requiredSignerTools: Object.keys(signer.toolSchemas)
546
+ };
547
+ }
548
+ });
549
+ async function writeRuntimeConfig(input, deps = {}) {
550
+ switch (input.runtime) {
551
+ case "codex-cli":
552
+ case "codex-desktop":
553
+ return writeCodexConfig(input);
554
+ case "cursor":
555
+ return writeJsonRuntimeConfig(input, cursorConfigPath(input.homeDir), "mcpServers");
556
+ case "vscode":
557
+ return writeJsonRuntimeConfig(input, vscodeConfigPath(input.homeDir), "servers");
558
+ case "vscode-insiders":
559
+ return writeJsonRuntimeConfig(input, vscodeInsidersConfigPath(input.homeDir), "servers");
560
+ case "claude-desktop":
561
+ return writeJsonRuntimeConfig(input, claudeDesktopConfigPath(input.homeDir), "mcpServers");
562
+ case "hermes":
563
+ return writeHermesConfig(input, deps);
564
+ default:
565
+ return {
566
+ hostedConfigured: false,
567
+ signerConfigured: false,
568
+ localMcpConfigured: false,
569
+ runtimeMcpMode: "manual",
570
+ target: "manual runtime setup",
571
+ changed: false,
572
+ restartRequired: true,
573
+ messages: ["Runtime config needs to be added manually for this agent environment."],
574
+ errorCode: "manual_runtime_setup_required"
575
+ };
576
+ }
577
+ }
578
+ function buildHostedServer(hostedMcpUrl, apiKey, runtime) {
579
+ if (runtime === "vscode" || runtime === "vscode-insiders") {
580
+ return {
581
+ type: "http",
582
+ url: hostedMcpUrl,
583
+ headers: { Authorization: `Bearer ${apiKey}` }
584
+ };
585
+ }
586
+ return {
587
+ url: hostedMcpUrl,
588
+ headers: { Authorization: `Bearer ${apiKey}` }
589
+ };
590
+ }
591
+ function resolveSignerLaunchSpec(input) {
592
+ return input.signerCommand ?? {
593
+ command: "npx",
594
+ args: ["-y", signerPackageSpec(), "--credentials", input.signerPath]
595
+ };
596
+ }
597
+ function buildSignerServer(spec, runtime) {
598
+ const server = {
599
+ command: spec.command,
600
+ args: spec.args
601
+ };
602
+ if (runtime === "vscode" || runtime === "vscode-insiders") return { type: "stdio", ...server };
603
+ return server;
604
+ }
605
+ function mergeJsonMcpConfig(existingJson, serverRoot, hostedServer, signerServer, names = serverNamesFor(), configPath) {
606
+ const config = existingJson?.trim() ? parseJsonObject(existingJson, configPath) : {};
607
+ const existingRoot = config[serverRoot];
608
+ const servers = existingRoot && typeof existingRoot === "object" && !Array.isArray(existingRoot) ? existingRoot : {};
609
+ config[serverRoot] = {
610
+ ...servers,
611
+ [names.hosted]: hostedServer,
612
+ [names.signer]: signerServer
613
+ };
614
+ return `${JSON.stringify(config, null, 2)}
615
+ `;
616
+ }
617
+ function mergeHermesYaml(existingYaml, hostedServer, signerServer, names = serverNamesFor(), configPath) {
618
+ if (!existingYaml?.trim()) {
619
+ return renderHermesYaml({ [names.hosted]: hostedServer, [names.signer]: signerServer });
620
+ }
206
621
  const doc = yaml.parseDocument(existingYaml, { keepSourceTokens: true });
207
622
  if (doc.errors.length > 0 || !yaml.isMap(doc.contents)) {
208
623
  throw new UnreadableRuntimeConfigError(configPath ?? "the Hermes config", "it is not a YAML object");
@@ -852,34 +1267,114 @@ var init_config_writers = __esm({
852
1267
  };
853
1268
  }
854
1269
  });
855
- async function probeHostedAgentIdentity(apiKey, apiUrl, fetchImpl = fetch) {
856
- let response;
1270
+ async function acknowledgeLocalMcpConsent(identityPath, signerPath, log) {
857
1271
  try {
858
- response = await fetchWithTimeout(fetchImpl, `${apiUrl.replace(/\/+$/, "")}/machine-payments/agent`, {
859
- method: "GET",
860
- headers: { Authorization: `Bearer ${apiKey}`, Accept: "application/json" }
1272
+ const input = await buildLocalMcpConsentInput(identityPath, signerPath);
1273
+ const decision = await mcp.ensureConsent(input, {
1274
+ credentialsPath: identityPath,
1275
+ writeAck: true,
1276
+ out: log ? { write: (chunk) => writeLogChunk(log, chunk) } : void 0
861
1277
  });
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" };
1278
+ return {
1279
+ acknowledged: decision.ok,
1280
+ hash: decision.hash,
1281
+ reason: decision.reason
1282
+ };
1283
+ } catch (err) {
1284
+ return {
1285
+ acknowledged: false,
1286
+ error: err instanceof Error ? err.message : String(err)
1287
+ };
873
1288
  }
874
1289
  }
875
- async function probeHostedMcpTools(apiKey, hostedMcpUrl, fetchImpl = fetch) {
876
- let response;
1290
+ async function getLocalMcpConsentStatus(identityPath, signerPath) {
877
1291
  try {
878
- response = await fetchWithTimeout(fetchImpl, hostedMcpUrl, {
879
- method: "POST",
880
- headers: {
881
- Authorization: `Bearer ${apiKey}`,
882
- "Content-Type": "application/json",
1292
+ const input = await buildLocalMcpConsentInput(identityPath, signerPath);
1293
+ const hash = mcp.computeConsentHash(input);
1294
+ const stored = await readLocalMcpAckFile(localMcpAckPath(identityPath));
1295
+ if (stored === hash) {
1296
+ return { acknowledged: true, hash, reason: "ack_file_match" };
1297
+ }
1298
+ return {
1299
+ acknowledged: false,
1300
+ hash,
1301
+ reason: stored ? "ack_file_mismatch" : "ack_file_missing"
1302
+ };
1303
+ } catch (err) {
1304
+ return {
1305
+ acknowledged: false,
1306
+ error: err instanceof Error ? err.message : String(err)
1307
+ };
1308
+ }
1309
+ }
1310
+ function localMcpAckPath(identityPath) {
1311
+ return path.resolve(`${identityPath}.ack.json`);
1312
+ }
1313
+ async function buildLocalMcpConsentInput(identityPath, signerPath) {
1314
+ const credentials = await mcp.loadCredentials({ identityPath, signerPath });
1315
+ const unavailableDuringSetup = {
1316
+ getAllowances: async () => {
1317
+ throw new Error("Haven approval is not complete yet.");
1318
+ }
1319
+ };
1320
+ return mcp.consentInputFromClient(
1321
+ unavailableDuringSetup,
1322
+ {
1323
+ apiKey: credentials.apiKey,
1324
+ apiUrl: credentials.apiUrl,
1325
+ agentId: credentials.agentId,
1326
+ safeAddress: credentials.safeAddress,
1327
+ delegateAddress: credentials.delegateAddress,
1328
+ chainId: credentials.chainId,
1329
+ allowanceSummary: credentials.allowanceSummary
1330
+ },
1331
+ mcp.registeredToolNames()
1332
+ );
1333
+ }
1334
+ async function readLocalMcpAckFile(path) {
1335
+ try {
1336
+ const parsed = JSON.parse(await promises.readFile(path, "utf8"));
1337
+ return typeof parsed.ack === "string" ? parsed.ack : null;
1338
+ } catch {
1339
+ return null;
1340
+ }
1341
+ }
1342
+ function writeLogChunk(log, chunk) {
1343
+ const message = String(chunk).trimEnd();
1344
+ if (message) log(message);
1345
+ }
1346
+ var init_local_mcp_consent = __esm({
1347
+ "src/local-mcp-consent.ts"() {
1348
+ }
1349
+ });
1350
+ async function probeHostedAgentIdentity(apiKey, apiUrl, fetchImpl = fetch) {
1351
+ let response;
1352
+ try {
1353
+ response = await fetchWithTimeout(fetchImpl, `${apiUrl.replace(/\/+$/, "")}/machine-payments/agent`, {
1354
+ method: "GET",
1355
+ headers: { Authorization: `Bearer ${apiKey}`, Accept: "application/json" }
1356
+ });
1357
+ } catch {
1358
+ return { status: "network_error" };
1359
+ }
1360
+ if (response.status === 401 || response.status === 403) return { status: "unauthorized" };
1361
+ if (!response.ok) return { status: "bad_response" };
1362
+ try {
1363
+ const payload = JSON.parse(await response.text());
1364
+ if (typeof payload?.delegate_address !== "string") return { status: "bad_response" };
1365
+ return { status: "ok", agentId: payload.id, delegateAddress: payload.delegate_address };
1366
+ } catch {
1367
+ return { status: "bad_response" };
1368
+ }
1369
+ }
1370
+ async function probeHostedMcpTools(apiKey, hostedMcpUrl, fetchImpl = fetch) {
1371
+ let response;
1372
+ try {
1373
+ response = await fetchWithTimeout(fetchImpl, hostedMcpUrl, {
1374
+ method: "POST",
1375
+ headers: {
1376
+ Authorization: `Bearer ${apiKey}`,
1377
+ "Content-Type": "application/json",
883
1378
  Accept: "application/json, text/event-stream"
884
1379
  },
885
1380
  body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" })
@@ -1167,95 +1662,371 @@ var init_signer_runtime = __esm({
1167
1662
  SIGNER_INSTALL_HEARTBEAT_MS = 15e3;
1168
1663
  }
1169
1664
  });
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
- };
1665
+ async function prepareLocalMcpRuntime(input, deps = {}) {
1666
+ assertSupportedNodeVersion(input.nodeVersion);
1667
+ const homeDir = input.homeDir ?? os.homedir();
1668
+ const runtimeDirectory = path.resolve(homeDir, ".haven", "mcp-runtime", MCP_RUNTIME_MANIFEST.mcpVersion);
1669
+ const npmCacheDirectory = path.resolve(homeDir, ".haven", "npm-cache");
1670
+ const cliPath = path.join(runtimeDirectory, "node_modules", "@haven_ai", "mcp", "dist", "cli.js");
1671
+ const messages = [];
1672
+ await promises.mkdir(runtimeDirectory, { recursive: true, mode: 448 });
1673
+ await promises.chmod(runtimeDirectory, 448).catch(() => void 0);
1674
+ await promises.mkdir(npmCacheDirectory, { recursive: true, mode: 448 });
1675
+ await promises.chmod(npmCacheDirectory, 448).catch(() => void 0);
1676
+ if (await installedRuntimeMatches2(runtimeDirectory, cliPath)) {
1677
+ messages.push(`Using existing local Haven MCP runtime ${mcpPackageSpec()}.`);
1678
+ } else {
1679
+ await installRuntimePackages2(runtimeDirectory, npmCacheDirectory, deps);
1680
+ messages.push(`Installed local Haven MCP runtime ${mcpPackageSpec()}.`);
1185
1681
  }
1186
- });
1187
-
1188
- // src/runtime-registry.ts
1189
- function runtimeProfile(runtime, env = process.env) {
1190
- return RUNTIME_PROFILES[normalizeRuntime(runtime, env)];
1682
+ await assertFileExists2(cliPath, "local Haven MCP CLI");
1683
+ const wrapperPath = path.join(input.credentialDirectory, "bin", "haven-mcp");
1684
+ await writeWrapper2({
1685
+ wrapperPath,
1686
+ cliPath,
1687
+ identityPath: input.identityPath,
1688
+ signerPath: input.signerPath
1689
+ });
1690
+ await writeRuntimeSidecar2({
1691
+ path: path.join(input.credentialDirectory, "mcp-runtime.json"),
1692
+ wrapperPath,
1693
+ runtimeDirectory,
1694
+ npmCacheDirectory,
1695
+ cliPath,
1696
+ serverName: input.serverName
1697
+ });
1698
+ messages.push(`Prepared stable local Haven MCP wrapper: ${wrapperPath}`);
1699
+ return {
1700
+ command: wrapperPath,
1701
+ args: [],
1702
+ wrapperPath,
1703
+ runtimeDirectory,
1704
+ npmCacheDirectory,
1705
+ cliPath,
1706
+ messages
1707
+ };
1191
1708
  }
1192
- function normalizeRuntime(runtime, env = process.env) {
1193
- const explicit = normalizeRuntimeName(runtime);
1194
- if (explicit) return explicit;
1195
- return detectRuntime(env) ?? "other";
1709
+ function assertSupportedNodeVersion(nodeVersion = process.versions.node, minimumNodeVersion = MCP_RUNTIME_MANIFEST.minimumNodeVersion, subject = "Haven setup") {
1710
+ if (!sdk.isSupportedNodeVersion(nodeVersion, minimumNodeVersion)) {
1711
+ throw new UnsupportedNodeVersionError(nodeVersion, minimumNodeVersion, subject);
1712
+ }
1196
1713
  }
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
- );
1714
+ async function installRuntimePackages2(runtimeDirectory, npmCacheDirectory, deps) {
1715
+ const { runCommand, onProgress } = deps;
1716
+ const baseArgs = [
1717
+ "install",
1718
+ "--prefix",
1719
+ runtimeDirectory,
1720
+ "--no-audit",
1721
+ "--no-fund",
1722
+ "--omit=dev",
1723
+ "--prefer-offline",
1724
+ mcpPackageSpec(),
1725
+ sdkPackageSpec()
1726
+ ];
1727
+ const run = async (args) => {
1728
+ const startedAt = Date.now();
1729
+ const heartbeat = setInterval(() => {
1730
+ const seconds = Math.round((Date.now() - startedAt) / 1e3);
1731
+ onProgress?.(`Still installing the local Haven MCP runtime\u2026 (${seconds}s \u2014 a cold cache can take several minutes)`);
1732
+ }, SIGNER_INSTALL_HEARTBEAT_MS);
1733
+ heartbeat.unref?.();
1734
+ try {
1735
+ if (runCommand) await runCommand("npm", args);
1736
+ else await execFileAsync2("npm", args, { timeout: SIGNER_INSTALL_TIMEOUT_MS, maxBuffer: 1024 * 1024 });
1737
+ } finally {
1738
+ clearInterval(heartbeat);
1207
1739
  }
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
- );
1740
+ };
1741
+ try {
1742
+ await run(baseArgs);
1743
+ } catch {
1744
+ try {
1745
+ await run([...baseArgs, "--cache", npmCacheDirectory]);
1746
+ } catch (err) {
1747
+ throw new Error(`Could not install local Haven MCP runtime ${mcpPackageSpec()}: ${err instanceof Error ? err.message : String(err)}`);
1220
1748
  }
1221
- return { runtime: detected, source: "detected", discardedHint: supplied };
1222
- }
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
1749
  }
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
1750
  }
1241
- function normalizeRuntimeName(runtime) {
1242
- const key = runtime?.trim().toLowerCase();
1243
- if (!key) return null;
1244
- return RUNTIME_ALIASES[key.replace(/\s+/g, "-")] ?? null;
1751
+ async function installedRuntimeMatches2(runtimeDirectory, cliPath) {
1752
+ try {
1753
+ await assertFileExists2(cliPath, "local Haven MCP CLI");
1754
+ const [mcpPackage, sdkPackage] = await Promise.all([
1755
+ readPackageJson2(path.join(runtimeDirectory, "node_modules", "@haven_ai", "mcp", "package.json")),
1756
+ readPackageJson2(path.join(runtimeDirectory, "node_modules", "@haven_ai", "sdk", "package.json"))
1757
+ ]);
1758
+ return mcpPackage.version === MCP_RUNTIME_MANIFEST.mcpVersion && sdkPackage.version === MCP_RUNTIME_MANIFEST.sdkVersion;
1759
+ } catch {
1760
+ return false;
1761
+ }
1245
1762
  }
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;
1763
+ async function readPackageJson2(path) {
1764
+ return JSON.parse(await promises.readFile(path, "utf8"));
1252
1765
  }
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": {
1766
+ async function writeWrapper2(input) {
1767
+ await promises.mkdir(path.dirname(input.wrapperPath), { recursive: true, mode: 448 });
1768
+ await promises.chmod(path.dirname(input.wrapperPath), 448).catch(() => void 0);
1769
+ const source = [
1770
+ "#!/usr/bin/env node",
1771
+ "import { spawn } from 'node:child_process'",
1772
+ "",
1773
+ `const cliPath = ${JSON.stringify(input.cliPath)}`,
1774
+ `const identityPath = ${JSON.stringify(input.identityPath)}`,
1775
+ `const signerPath = ${JSON.stringify(input.signerPath)}`,
1776
+ "",
1777
+ "const child = spawn(process.execPath, [cliPath, '--identity', identityPath, '--signer', signerPath, ...process.argv.slice(2)], {",
1778
+ " stdio: 'inherit',",
1779
+ "})",
1780
+ "",
1781
+ "child.on('exit', (code, signal) => {",
1782
+ " if (signal) process.kill(process.pid, signal)",
1783
+ " else process.exit(code ?? 1)",
1784
+ "})",
1785
+ ""
1786
+ ].join("\n");
1787
+ await promises.writeFile(input.wrapperPath, source, { mode: 448 });
1788
+ await promises.chmod(input.wrapperPath, 448).catch(() => void 0);
1789
+ }
1790
+ async function writeRuntimeSidecar2(input) {
1791
+ const value = {
1792
+ ...input.serverName ? { server_name: input.serverName } : {},
1793
+ mcp_package: MCP_RUNTIME_MANIFEST.mcpPackage,
1794
+ mcp_version: MCP_RUNTIME_MANIFEST.mcpVersion,
1795
+ sdk_package: MCP_RUNTIME_MANIFEST.sdkPackage,
1796
+ sdk_version: MCP_RUNTIME_MANIFEST.sdkVersion,
1797
+ minimum_node_version: MCP_RUNTIME_MANIFEST.minimumNodeVersion,
1798
+ wrapper_path: input.wrapperPath,
1799
+ runtime_directory: input.runtimeDirectory,
1800
+ npm_cache_directory: input.npmCacheDirectory,
1801
+ cli_path: input.cliPath
1802
+ };
1803
+ await promises.writeFile(input.path, `${JSON.stringify(value, null, 2)}
1804
+ `, { mode: 384 });
1805
+ await promises.chmod(input.path, 384).catch(() => void 0);
1806
+ }
1807
+ async function assertFileExists2(path, label) {
1808
+ try {
1809
+ await promises.access(path);
1810
+ } catch {
1811
+ throw new Error(`Missing ${label}: ${path}`);
1812
+ }
1813
+ }
1814
+ var execFileAsync2, UnsupportedNodeVersionError;
1815
+ var init_local_mcp_runtime = __esm({
1816
+ "src/local-mcp-runtime.ts"() {
1817
+ init_signer_runtime();
1818
+ init_runtime_manifest();
1819
+ execFileAsync2 = util.promisify(child_process.execFile);
1820
+ UnsupportedNodeVersionError = class extends Error {
1821
+ code = "local_mcp_unsupported_node_version";
1822
+ nodeVersion;
1823
+ minimumNodeVersion;
1824
+ constructor(nodeVersion, minimumNodeVersion, subject = "Haven setup") {
1825
+ super(sdk.unsupportedNodeVersionMessage({ subject, nodeVersion, minimumNodeVersion }));
1826
+ this.name = "UnsupportedNodeVersionError";
1827
+ this.nodeVersion = nodeVersion;
1828
+ this.minimumNodeVersion = minimumNodeVersion;
1829
+ }
1830
+ };
1831
+ }
1832
+ });
1833
+ async function installSkillForRuntime(runtime, deps = {}) {
1834
+ switch (runtime) {
1835
+ case "claude-code":
1836
+ return installSkillFile(
1837
+ path.resolve(deps.homeDir ?? os.homedir(), ".claude", "skills", sdk.SKILL_FOLDER_NAME),
1838
+ "~/.claude/skills/haven-pay"
1839
+ );
1840
+ case "hermes":
1841
+ return installSkillFile(
1842
+ path.join(hermesHome(deps), "skills", sdk.SKILL_FOLDER_NAME),
1843
+ "the Hermes skills folder"
1844
+ );
1845
+ case "codex-cli":
1846
+ case "codex-desktop":
1847
+ return installCodexAgentsSection(deps);
1848
+ default:
1849
+ return void 0;
1850
+ }
1851
+ }
1852
+ async function installSkillFile(skillDir, label) {
1853
+ try {
1854
+ await promises.mkdir(skillDir, { recursive: true });
1855
+ const target = path.join(skillDir, "SKILL.md");
1856
+ await promises.writeFile(target, sdk.HAVEN_SKILL_MD, "utf8");
1857
+ return {
1858
+ installed: true,
1859
+ target,
1860
+ messages: [`Installed the generic Haven payment skill (${label}). It contains no secrets.`]
1861
+ };
1862
+ } catch (err) {
1863
+ return {
1864
+ installed: false,
1865
+ messages: [
1866
+ `Could not install the Haven payment skill: ${err instanceof Error ? err.message : String(err)}. Download it from the Haven dashboard instead.`
1867
+ ]
1868
+ };
1869
+ }
1870
+ }
1871
+ async function installCodexAgentsSection(deps) {
1872
+ try {
1873
+ const codexDir = path.resolve(deps.homeDir ?? os.homedir(), ".codex");
1874
+ const target = path.join(codexDir, "AGENTS.md");
1875
+ await promises.mkdir(codexDir, { recursive: true });
1876
+ const existing = await promises.readFile(target, "utf8").catch(() => null);
1877
+ const next = upsertManagedSection(existing, codexManagedSection());
1878
+ if (next !== existing) {
1879
+ await promises.writeFile(target, next, "utf8");
1880
+ }
1881
+ return {
1882
+ installed: true,
1883
+ target,
1884
+ messages: [
1885
+ "Installed the generic Haven payment guidance as a managed section in ~/.codex/AGENTS.md (Codex reads it as global instructions). It contains no secrets; your own content in that file is untouched."
1886
+ ]
1887
+ };
1888
+ } catch (err) {
1889
+ return {
1890
+ installed: false,
1891
+ messages: [
1892
+ `Could not install the Haven payment guidance into ~/.codex/AGENTS.md: ${err instanceof Error ? err.message : String(err)}. Download the skill from the Haven dashboard instead.`
1893
+ ]
1894
+ };
1895
+ }
1896
+ }
1897
+ function codexManagedSection() {
1898
+ return `${CODEX_AGENTS_BEGIN_MARKER}
1899
+
1900
+ ${sdk.HAVEN_SKILL_BODY_MD.trimEnd()}
1901
+
1902
+ ${CODEX_AGENTS_END_MARKER}
1903
+ `;
1904
+ }
1905
+ function upsertManagedSection(existing, section) {
1906
+ if (existing === null || existing.trim() === "") return section;
1907
+ const begins = markerLineIndexes(existing, CODEX_AGENTS_BEGIN_MARKER);
1908
+ const ends = markerLineIndexes(existing, CODEX_AGENTS_END_MARKER);
1909
+ if (begins.length === 1 && ends.length === 1 && ends[0] > begins[0]) {
1910
+ const afterEnd = ends[0] + CODEX_AGENTS_END_MARKER.length;
1911
+ const tail = existing.startsWith("\r\n", afterEnd) ? existing.slice(afterEnd + 2) : existing.startsWith("\n", afterEnd) ? existing.slice(afterEnd + 1) : existing.slice(afterEnd);
1912
+ return existing.slice(0, begins[0]) + section + tail;
1913
+ }
1914
+ if (begins.length > 0 || ends.length > 0) {
1915
+ throw new Error(
1916
+ "found a damaged Haven marker section (orphaned or duplicated markers); remove the leftover marker lines and re-run setup"
1917
+ );
1918
+ }
1919
+ return `${existing.replace(/\n*$/, "\n\n")}${section}`;
1920
+ }
1921
+ function markerLineIndexes(text, marker) {
1922
+ const indexes = [];
1923
+ for (let from = 0; ; ) {
1924
+ const at = text.indexOf(marker, from);
1925
+ if (at === -1) return indexes;
1926
+ if (at === 0 || text[at - 1] === "\n") indexes.push(at);
1927
+ from = at + marker.length;
1928
+ }
1929
+ }
1930
+ function hermesHome(deps) {
1931
+ const env = deps.env ?? process.env;
1932
+ return env.HERMES_HOME ?? path.join(deps.homeDir ?? os.homedir(), ".hermes");
1933
+ }
1934
+ var CODEX_AGENTS_BEGIN_MARKER, CODEX_AGENTS_END_MARKER;
1935
+ var init_skill_install = __esm({
1936
+ "src/skill-install.ts"() {
1937
+ CODEX_AGENTS_BEGIN_MARKER = "<!-- BEGIN haven-pay (managed by @haven_ai/connect; edits inside this section are overwritten on re-setup) -->";
1938
+ CODEX_AGENTS_END_MARKER = "<!-- END haven-pay -->";
1939
+ }
1940
+ });
1941
+
1942
+ // src/connect-error.ts
1943
+ var ConnectError;
1944
+ var init_connect_error = __esm({
1945
+ "src/connect-error.ts"() {
1946
+ ConnectError = class extends Error {
1947
+ code;
1948
+ nextAction;
1949
+ constructor(code, message, nextAction2) {
1950
+ super(message);
1951
+ this.name = "ConnectError";
1952
+ this.code = code;
1953
+ this.nextAction = nextAction2;
1954
+ }
1955
+ };
1956
+ }
1957
+ });
1958
+
1959
+ // src/runtime-registry.ts
1960
+ function runtimeProfile(runtime, env = process.env) {
1961
+ return RUNTIME_PROFILES[normalizeRuntime(runtime, env)];
1962
+ }
1963
+ function normalizeRuntime(runtime, env = process.env) {
1964
+ const explicit = normalizeRuntimeName(runtime);
1965
+ if (explicit) return explicit;
1966
+ return detectRuntime(env) ?? "other";
1967
+ }
1968
+ async function resolveRuntimeSelection(explicit, force, options = {}) {
1969
+ const env = options.env ?? process.env;
1970
+ if (force !== void 0) {
1971
+ const forced = normalizeRuntimeName(force);
1972
+ if (!forced) {
1973
+ throw new ConnectError(
1974
+ "runtime_force_unrecognized",
1975
+ `Unknown --runtime-force value "${force}". Valid values: ${RUNTIME_FLAG_VALUES}.`,
1976
+ "rerun_connect_with_a_valid_runtime_name"
1977
+ );
1978
+ }
1979
+ return { runtime: forced, source: "force" };
1980
+ }
1981
+ const detected = detectRuntime(env);
1982
+ const supplied = explicit?.trim() || options.selfReported?.trim() || void 0;
1983
+ const hint = normalizeRuntimeName(supplied);
1984
+ if (supplied && !hint) {
1985
+ if (!detected) {
1986
+ throw new ConnectError(
1987
+ "runtime_unrecognized",
1988
+ `"${supplied}" is not an agent runtime Haven knows. Valid values: ${RUNTIME_FLAG_VALUES} (the aliases cowork, codex and openclaw are accepted too). Re-run with one of those, or --runtime other to store credentials and finish the MCP setup by hand. Nothing was written and the Haven setup token is still unused.`,
1989
+ "rerun_connect_with_a_valid_runtime_name"
1990
+ );
1991
+ }
1992
+ return { runtime: detected, source: "detected", discardedHint: supplied };
1993
+ }
1994
+ if (detected && hint && detected !== hint) {
1995
+ return { runtime: detected, source: "detected", overrodeHint: hint };
1996
+ }
1997
+ if (hint) return { runtime: hint, source: "explicit" };
1998
+ if (detected) return { runtime: detected, source: "detected" };
1999
+ if (options.promptForRuntime) {
2000
+ return { runtime: await options.promptForRuntime(), source: "prompted" };
2001
+ }
2002
+ return { runtime: null, source: "none" };
2003
+ }
2004
+ function restartRequiredForRuntime(runtime, env = process.env) {
2005
+ const mode = runtimeProfile(runtime, env).restartMode;
2006
+ return mode === "restart-session" || mode === "restart-app";
2007
+ }
2008
+ function runtimeVerificationInstruction(runtime) {
2009
+ const label = RUNTIME_PROFILES[runtime].label;
2010
+ return `In ${label}, run the read-only \`haven_get_agent\` and \`haven_get_allowances\` tools to confirm the Haven wallet and live budget. Do not sign, fund, or create a payment to verify setup.`;
2011
+ }
2012
+ function normalizeRuntimeName(runtime) {
2013
+ const key = runtime?.trim().toLowerCase();
2014
+ if (!key) return null;
2015
+ return RUNTIME_ALIASES[key.replace(/\s+/g, "-")] ?? null;
2016
+ }
2017
+ function detectRuntime(env) {
2018
+ if (env.CLAUDECODE || env.CLAUDE_CODE || env.CLAUDECODE_CWD) return "claude-code";
2019
+ if (env.CODEX_SANDBOX || env.CODEX_HOME || env.CODEX_CWD) return "codex-cli";
2020
+ if (env.VSCODE_CWD || env.VSCODE_IPC_HOOK_CLI || env.TERM_PROGRAM === "vscode") return "vscode";
2021
+ if (env.HERMES_HOME || env.HERMES_AGENT) return "hermes";
2022
+ return null;
2023
+ }
2024
+ var RUNTIME_PROFILES, RUNTIME_ALIASES, RUNTIME_FLAG_VALUES;
2025
+ var init_runtime_registry = __esm({
2026
+ "src/runtime-registry.ts"() {
2027
+ init_connect_error();
2028
+ RUNTIME_PROFILES = {
2029
+ "claude-code": {
1259
2030
  id: "claude-code",
1260
2031
  label: "Claude Code",
1261
2032
  restartMode: "restart-session",
@@ -1445,1519 +2216,1319 @@ var init_signer_consent = __esm({
1445
2216
  "src/signer-consent.ts"() {
1446
2217
  }
1447
2218
  });
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: [] };
2219
+ async function installRuntime(input, deps = {}) {
2220
+ const runtime = normalizeRuntime(input.runtime, deps.env);
2221
+ const profile = runtimeProfile(runtime, deps.env);
2222
+ const progress = deps.onProgress ?? (() => void 0);
2223
+ const localRuntime = input.localMcp === true && supportsLocalMcp(runtime);
2224
+ const consentMessages = [];
2225
+ const localMcpConsent = localRuntime ? await resolveLocalMcpConsent(input, consentMessages) : void 0;
2226
+ const signerConsent = localRuntime ? void 0 : await resolveSignerConsent(input, consentMessages);
2227
+ if (runtime === "other") {
2228
+ const signerCredentialReady2 = await probeLocalSignerCredential(input.signerPath);
2229
+ const signerReady = signerCredentialReady2 && signerConsent?.acknowledged;
2230
+ return {
2231
+ runtime,
2232
+ runtimeMcpMode: "manual",
2233
+ hostedMcpConfigured: false,
2234
+ localSignerConfigured: false,
2235
+ localMcpConfigured: false,
2236
+ probeResult: signerReady ? "manual_runtime_setup_required_local_signer_ready" : "manual_runtime_setup_required_local_signer_unavailable",
2237
+ restartRequired: true,
2238
+ nextUserAction: "return_to_haven_for_wallet_approval_then_configure_runtime",
2239
+ errorCode: "manual_runtime_setup_required",
2240
+ configTarget: "manual runtime setup",
2241
+ signerAcknowledged: signerConsent?.acknowledged,
2242
+ localMcpAcknowledged: false,
2243
+ messages: [
2244
+ ...consentMessages,
2245
+ "Custom runtime: Haven did not auto-configure it. Your credentials are on disk (chmod 600) \u2014 read them at runtime; never paste a key into the agent prompt, memory, or logs.",
2246
+ ` identity (hosted MCP Bearer): ${input.identityPath}`,
2247
+ ` signer (local signing key): ${input.signerPath}`,
2248
+ "After wallet approval, wire the runtime to Haven by reference:",
2249
+ ` Hosted MCP + local signer: point your MCP client at ${input.hostedMcpUrl} with the api_key from identity.json, then run npx -y ${signerPackageSpec()} --credentials ${input.signerPath}`,
2250
+ ` Fully local MCP (no hosted dependency): npx -y ${mcpPackageSpec()} --identity ${input.identityPath} --signer ${input.signerPath}`
2251
+ ]
2252
+ };
1538
2253
  }
1539
- const candidates = [];
1540
- const tombstonedOnly = [];
1541
- for (const entry of entries) {
1542
- const directory = path.join(root, entry);
2254
+ let localRuntimeInstall;
2255
+ let localRuntimeError;
2256
+ if (localRuntime) {
1543
2257
  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
- }
2258
+ localRuntimeInstall = await prepareRuntimeForLocalMcp(input, deps);
2259
+ } catch (err) {
2260
+ localRuntimeError = err;
1552
2261
  }
1553
2262
  }
1554
- candidates.sort((a, b) => b.mtimeMs - a.mtimeMs);
1555
- if (explicit) {
2263
+ if (localRuntimeError) {
2264
+ const errorCode2 = localRuntimePrepareErrorCode(localRuntimeError);
1556
2265
  return {
1557
- directory: explicit,
1558
- others: [...candidates.map((c) => c.directory), ...tombstonedOnly].filter((d) => d !== explicit)
2266
+ runtime,
2267
+ runtimeMcpMode: "local_stdio",
2268
+ hostedMcpConfigured: false,
2269
+ localSignerConfigured: false,
2270
+ localMcpConfigured: false,
2271
+ probeResult: errorCode2 === "local_mcp_unsupported_node_version" ? "local_stdio_mcp_unsupported_node_version" : "local_stdio_mcp_runtime_install_failed",
2272
+ restartRequired: true,
2273
+ nextUserAction: nextAction(runtime, profile.restartMode, errorCode2),
2274
+ errorCode: errorCode2,
2275
+ configTarget: profile.label,
2276
+ signerAcknowledged: signerConsent?.acknowledged,
2277
+ localMcpAcknowledged: localMcpConsent?.acknowledged,
2278
+ activationCommand: void 0,
2279
+ messages: [
2280
+ ...consentMessages,
2281
+ `Could not prepare local Haven MCP runtime: ${localRuntimeError instanceof Error ? localRuntimeError.message : String(localRuntimeError)}`
2282
+ ]
1559
2283
  };
1560
2284
  }
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;
2285
+ let signerCommand;
2286
+ if (!localRuntime) {
2287
+ progress("Getting the signer ready\u2026");
2288
+ try {
2289
+ const signerRuntime = await prepareSignerForRuntime(input, deps);
2290
+ signerCommand = { command: signerRuntime.command, args: signerRuntime.args };
2291
+ consentMessages.push(...signerRuntime.messages);
2292
+ } catch (err) {
2293
+ return {
2294
+ runtime,
2295
+ runtimeMcpMode: "hosted_plus_signer",
2296
+ hostedMcpConfigured: false,
2297
+ localSignerConfigured: false,
2298
+ localMcpConfigured: false,
2299
+ probeResult: "signer_runtime_install_failed",
2300
+ restartRequired: false,
2301
+ nextUserAction: "The local Haven signer runtime could not be installed, so no configuration was written. Check your network (a cold install downloads the signer package set) and re-run: npx @haven_ai/connect@alpha",
2302
+ errorCode: "signer_runtime_install_failed",
2303
+ configTarget: profile.label,
2304
+ signerAcknowledged: signerConsent?.acknowledged,
2305
+ localMcpAcknowledged: localMcpConsent?.acknowledged,
2306
+ activationCommand: void 0,
2307
+ signerRuntimePrepared: false,
2308
+ messages: [
2309
+ ...consentMessages,
2310
+ `Could not pre-install the local Haven signer: ${err instanceof Error ? err.message : String(err)}`,
2311
+ "No runtime configuration was written (fail-closed): a config pointing at an uninstalled signer looks wired but cannot start.",
2312
+ "Re-run `npx @haven_ai/connect@alpha` to retry the setup."
2313
+ ]
2314
+ };
1572
2315
  }
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
2316
  }
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;
2317
+ const signerRuntimePrepared = localRuntime ? void 0 : signerCommand !== void 0;
2318
+ progress("Setting up your Haven tools\u2026");
2319
+ const configResult = localRuntime ? runtime === "claude-code" ? await configureClaudeCode(deps, localRuntimeInstall?.command ?? "", input.serverName) : await writeRuntimeConfig({
2320
+ runtime,
2321
+ hostedMcpUrl: input.hostedMcpUrl,
2322
+ apiKey: input.apiKey,
2323
+ identityPath: input.identityPath,
2324
+ signerPath: input.signerPath,
2325
+ serverName: input.serverName,
2326
+ credentialDirectory: input.credentialDirectory,
2327
+ localMcpCommand: localRuntimeInstall?.command,
2328
+ signerCommand,
2329
+ homeDir: deps.homeDir,
2330
+ mode: "local"
2331
+ }) : await writeHostedRuntimeConfig(deps, { ...input, runtime }, signerCommand);
2332
+ if (deps.onRuntimeConfigured) {
2333
+ const signerCredentialOnDisk = await probeLocalSignerCredential(input.signerPath);
2334
+ const earlyLocalMcpOk = configResult.runtimeMcpMode === "local_stdio" && configResult.localMcpConfigured && signerCredentialOnDisk && Boolean(localMcpConsent?.acknowledged);
2335
+ const earlySignerOk = configResult.runtimeMcpMode === "local_stdio" ? earlyLocalMcpOk : configResult.signerConfigured && signerCredentialOnDisk && Boolean(signerConsent?.acknowledged);
2336
+ try {
2337
+ await deps.onRuntimeConfigured({
2338
+ runtime,
2339
+ runtimeMcpMode: configResult.runtimeMcpMode,
2340
+ hostedMcpConfigured: configResult.hostedConfigured,
2341
+ localSignerConfigured: earlySignerOk,
2342
+ localMcpConfigured: earlyLocalMcpOk,
2343
+ signerAcknowledged: signerConsent?.acknowledged,
2344
+ localMcpAcknowledged: localMcpConsent?.acknowledged,
2345
+ restartRequired: configResult.restartRequired || restartRequiredForRuntime(runtime, deps.env),
2346
+ nextUserAction: nextAction(runtime, profile.restartMode, configResult.errorCode),
2347
+ errorCode: configResult.errorCode
2348
+ });
2349
+ } catch {
2350
+ }
1596
2351
  }
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));
2352
+ progress("Almost there \u2014 just confirming everything connects\u2026");
2353
+ const localProbePromise = configResult.runtimeMcpMode === "local_stdio" && localRuntimeInstall ? runLocalMcpProbe(localRuntimeInstall, deps) : Promise.resolve(void 0);
2354
+ const signerProbePromise = configResult.runtimeMcpMode !== "local_stdio" && signerCommand ? (deps.probeSignerTools ?? probeLocalMcpTools)(
2355
+ signerCommand.command,
2356
+ signerCommand.args,
2357
+ MCP_RUNTIME_MANIFEST.requiredSignerTools
2358
+ ) : Promise.resolve(void 0);
2359
+ const [hostedProbe, signerCredentialReady, localMcpProbe, signerProbe] = await Promise.all([
2360
+ configResult.hostedConfigured ? probeHostedMcpTools(input.apiKey, input.hostedMcpUrl, deps.fetch) : Promise.resolve({ status: "bad_response" }),
2361
+ probeLocalSignerCredential(input.signerPath),
2362
+ localProbePromise,
2363
+ signerProbePromise
2364
+ ]);
2365
+ const hostedOk = configResult.hostedConfigured && hostedProbe.status === "ok";
2366
+ const localMcpOk = configResult.runtimeMcpMode === "local_stdio" && configResult.localMcpConfigured && signerCredentialReady && Boolean(localMcpConsent?.acknowledged) && localMcpProbe?.status === "ok";
2367
+ const signerOk = configResult.runtimeMcpMode === "local_stdio" ? localMcpOk : configResult.signerConfigured && signerCredentialReady && Boolean(signerConsent?.acknowledged) && // #1587: no handshake, no green. A signer command that was registered
2368
+ // but not probed (manual topology) keeps the old semantics.
2369
+ (signerProbe === void 0 || signerProbe.status === "ok");
2370
+ const restartRequired = configResult.restartRequired || restartRequiredForRuntime(runtime, deps.env);
2371
+ const errorCode = configResult.errorCode ?? (configResult.runtimeMcpMode === "local_stdio" ? localMcpErrorCode(signerCredentialReady, localMcpConsent, localMcpProbe?.status) : hostedMcpErrorCode(configResult.hostedConfigured, hostedProbe.status) ?? signerConsentErrorCode(signerCredentialReady, signerConsent) ?? signerProbeErrorCode(signerProbe));
2372
+ const hostedProbeMessages = configResult.hostedConfigured && hostedProbe.status !== "ok" ? [`Hosted Haven MCP probe failed: ${hostedProbe.status}.`] : configResult.hostedConfigured ? ["Verified hosted Haven MCP tools with a read-only handshake."] : [];
2373
+ const signerProbeMessages = signerProbe ? signerProbe.status === "ok" ? ["Verified local Haven signer with a stdio handshake."] : [
2374
+ `Local Haven signer handshake failed: ${signerProbe.status}.`,
2375
+ "Re-run `npx @haven_ai/connect@alpha` to repair the signer setup."
2376
+ ] : [];
2377
+ const localProbeMessages = localMcpProbe && localMcpProbe.status !== "ok" ? [`Local Haven MCP handshake failed: ${localMcpProbe.status}.`] : localMcpProbe?.status === "ok" ? ["Verified local Haven MCP tools with a stdio handshake."] : [];
2378
+ const skillInstall = !configResult.errorCode ? await installSkillForRuntime(runtime, { homeDir: deps.homeDir, env: deps.env }) : void 0;
1892
2379
  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 } : {}
2380
+ runtime,
2381
+ runtimeMcpMode: configResult.runtimeMcpMode,
2382
+ hostedMcpConfigured: hostedOk,
2383
+ localSignerConfigured: signerOk,
2384
+ localMcpConfigured: localMcpOk,
2385
+ probeResult: buildProbeResult(configResult.runtimeMcpMode, configResult.hostedConfigured, hostedProbe.status, signerOk, localMcpOk, localMcpProbe?.status),
2386
+ restartRequired,
2387
+ nextUserAction: nextAction(runtime, profile.restartMode, errorCode),
2388
+ errorCode,
2389
+ configTarget: configResult.target,
2390
+ signerAcknowledged: signerConsent?.acknowledged,
2391
+ localMcpAcknowledged: localMcpConsent?.acknowledged,
2392
+ activationCommand: configResult.activationCommand,
2393
+ skillInstalled: skillInstall?.installed,
2394
+ signerRuntimePrepared,
2395
+ messages: [...consentMessages, ...localRuntimeInstall?.messages ?? [], ...configResult.messages, ...hostedProbeMessages, ...signerProbeMessages, ...localProbeMessages, ...skillInstall?.messages ?? []]
1900
2396
  };
1901
2397
  }
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(/\/+$/, "");
2398
+ function runtimeInstallCapabilities(runtime, env = process.env) {
2399
+ const profile = runtimeProfile(runtime, env);
1980
2400
  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
- }
2401
+ canWriteRuntimeConfig: profile.canWriteRuntimeConfig,
2402
+ restartRequired: restartRequiredForRuntime(runtime, env)
2035
2403
  };
2036
2404
  }
2037
- var ConnectRequestError = class extends Error {
2038
- constructor(message, status) {
2039
- super(message);
2040
- this.status = status;
2041
- this.name = "ConnectRequestError";
2405
+ async function configureClaudeCode(deps, localMcpCommand, serverName) {
2406
+ const runCommand = deps.runCommand ?? defaultRunCommand;
2407
+ const serverJson = JSON.stringify({
2408
+ type: "stdio",
2409
+ command: localMcpCommand,
2410
+ args: [],
2411
+ env: {}
2412
+ });
2413
+ try {
2414
+ if (!localMcpCommand) throw new Error("local MCP wrapper command is required");
2415
+ const names = serverNamesFor(serverName);
2416
+ await runCommand("claude", ["mcp", "remove", names.hosted]).catch(() => void 0);
2417
+ await runCommand("claude", ["mcp", "remove", names.signer]).catch(() => void 0);
2418
+ await runCommand("claude", ["mcp", "add-json", names.hosted, serverJson, "--scope", "user"]).catch(async () => {
2419
+ await runCommand("claude", ["mcp", "add", names.hosted, "--scope", "user", "--", localMcpCommand]);
2420
+ });
2421
+ const verified = await runCommand("claude", ["mcp", "get", names.hosted]).then(() => true).catch(() => false);
2422
+ return {
2423
+ hostedConfigured: false,
2424
+ signerConfigured: true,
2425
+ localMcpConfigured: true,
2426
+ runtimeMcpMode: "local_stdio",
2427
+ target: "Claude Code MCP config",
2428
+ changed: true,
2429
+ restartRequired: true,
2430
+ messages: [
2431
+ "Updated local Haven MCP entry with Claude Code.",
2432
+ ...verified ? ["Verified Claude Code MCP entry."] : []
2433
+ ]
2434
+ };
2435
+ } catch (err) {
2436
+ return {
2437
+ hostedConfigured: false,
2438
+ signerConfigured: false,
2439
+ localMcpConfigured: false,
2440
+ runtimeMcpMode: "local_stdio",
2441
+ target: "Claude Code MCP config",
2442
+ changed: false,
2443
+ restartRequired: true,
2444
+ messages: [
2445
+ `Could not update Claude Code MCP config: ${err instanceof Error ? err.message : String(err)}`,
2446
+ "Install Claude Code or rerun the Haven setup command inside a Claude Code terminal."
2447
+ ],
2448
+ errorCode: "claude_code_config_failed"
2449
+ };
2450
+ }
2451
+ }
2452
+ async function writeHostedRuntimeConfig(deps, input, signerCommand) {
2453
+ if (input.runtime === "claude-code") {
2454
+ return configureClaudeCodeHosted(deps, input, signerCommand);
2042
2455
  }
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
- }
2456
+ return writeRuntimeConfig({
2457
+ runtime: input.runtime,
2458
+ hostedMcpUrl: input.hostedMcpUrl,
2459
+ apiKey: input.apiKey,
2460
+ identityPath: input.identityPath,
2461
+ signerPath: input.signerPath,
2462
+ serverName: input.serverName,
2463
+ credentialDirectory: input.credentialDirectory,
2464
+ signerCommand,
2465
+ homeDir: deps.homeDir,
2466
+ mode: "hosted"
2052
2467
  });
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
2468
  }
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")}`);
2469
+ async function configureClaudeCodeHosted(deps, input, signerCommand) {
2470
+ const runCommand = deps.runCommand ?? defaultRunCommand;
2471
+ const hostedJson = JSON.stringify({
2472
+ type: "http",
2473
+ url: input.hostedMcpUrl,
2474
+ headers: { Authorization: `Bearer ${input.apiKey}` }
2475
+ });
2476
+ const signerJson = JSON.stringify({
2477
+ type: "stdio",
2478
+ command: signerCommand?.command ?? "npx",
2479
+ args: signerCommand?.args ?? ["-y", signerPackageSpec(), "--credentials", input.signerPath],
2480
+ env: {}
2481
+ });
2090
2482
  try {
2091
- await writeOwnerOnlyJson(probePath, { ok: true }, input.warn);
2092
- } finally {
2093
- await promises.rm(probePath, { force: true }).catch(() => void 0);
2483
+ const names = serverNamesFor(input.serverName);
2484
+ await runCommand("claude", ["mcp", "remove", names.hosted]).catch(() => void 0);
2485
+ await runCommand("claude", ["mcp", "remove", names.signer]).catch(() => void 0);
2486
+ await runCommand("claude", ["mcp", "add-json", names.hosted, hostedJson, "--scope", "user"]);
2487
+ await runCommand("claude", ["mcp", "add-json", names.signer, signerJson, "--scope", "user"]);
2488
+ const verified = await runCommand("claude", ["mcp", "get", names.hosted]).then(() => true).catch(() => false);
2489
+ return {
2490
+ hostedConfigured: true,
2491
+ signerConfigured: true,
2492
+ localMcpConfigured: false,
2493
+ runtimeMcpMode: "hosted_plus_signer",
2494
+ target: "Claude Code MCP config",
2495
+ changed: true,
2496
+ restartRequired: true,
2497
+ messages: [
2498
+ "Updated hosted Haven MCP and local signer entries with Claude Code.",
2499
+ ...verified ? ["Verified Claude Code MCP entry."] : []
2500
+ ]
2501
+ };
2502
+ } catch (err) {
2503
+ return {
2504
+ hostedConfigured: false,
2505
+ signerConfigured: false,
2506
+ localMcpConfigured: false,
2507
+ runtimeMcpMode: "hosted_plus_signer",
2508
+ target: "Claude Code MCP config",
2509
+ changed: false,
2510
+ restartRequired: true,
2511
+ messages: [
2512
+ `Could not update Claude Code MCP config: ${err instanceof Error ? err.message : String(err)}`,
2513
+ "Install Claude Code or rerun the Haven setup command inside a Claude Code terminal."
2514
+ ],
2515
+ errorCode: "claude_code_config_failed"
2516
+ };
2094
2517
  }
2095
- return directory;
2096
2518
  }
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;
2519
+ async function defaultRunCommand(command, args) {
2520
+ await execFileAsync3(command, args, { timeout: 1e4 });
2521
+ }
2522
+ function buildProbeResult(mode, hostedConfigured, hostedStatus, signerReady, localMcpReady, localMcpProbeStatus) {
2523
+ if (mode === "local_stdio") {
2524
+ if (localMcpReady) return "local_stdio_mcp_ready";
2525
+ return localMcpProbeStatus ? `local_stdio_mcp_${localMcpProbeStatus}` : "local_stdio_mcp_unavailable";
2140
2526
  }
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;
2527
+ const hostedPart = hostedConfigured ? `hosted_${hostedStatus}` : "hosted_not_configured";
2528
+ const signerPart = signerReady ? "local_signer_ready" : "local_signer_unavailable";
2529
+ return `${hostedPart}_${signerPart}`.slice(0, 120);
2530
+ }
2531
+ async function resolveLocalMcpConsent(input, messages) {
2532
+ if (input.ackLocalTools || input.ackSigner) {
2533
+ const status = await acknowledgeLocalMcpConsent(input.identityPath, input.signerPath, (message) => messages.push(message));
2534
+ if (status.acknowledged) {
2535
+ messages.push("Prepared the local Haven tools acknowledgement.");
2536
+ } else {
2537
+ messages.push("Local Haven tools acknowledgement still needs attention.");
2538
+ }
2539
+ return status;
2160
2540
  }
2161
- return { directory, identityPath, signerPath, agentPath };
2541
+ return getLocalMcpConsentStatus(input.identityPath, input.signerPath);
2162
2542
  }
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;
2543
+ async function resolveSignerConsent(input, messages) {
2544
+ if (input.ackSigner || input.ackLocalTools) {
2545
+ const status = await acknowledgeLocalSignerConsent(input.signerPath, (message) => messages.push(message));
2546
+ if (status.acknowledged) {
2547
+ messages.push("Prepared the local Haven signer acknowledgement.");
2548
+ } else {
2549
+ messages.push("Local Haven signer acknowledgement still needs attention.");
2550
+ }
2551
+ return status;
2169
2552
  }
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
- );
2553
+ return getLocalSignerConsentStatus(input.signerPath);
2173
2554
  }
2174
- function defaultAgentDirectory(agentId, baseDir = path.join(os.homedir(), ".haven", "agents")) {
2175
- return path.resolve(defaultCredentialRoot(baseDir), safePathPart(agentId));
2555
+ function signerConsentErrorCode(signerCredentialReady, signerConsent) {
2556
+ if (!signerCredentialReady) return "local_signer_credential_unavailable";
2557
+ if (!signerConsent?.acknowledged) return "local_signer_ack_required";
2558
+ return void 0;
2176
2559
  }
2177
- function defaultCredentialRoot(baseDir = path.join(os.homedir(), ".haven", "agents")) {
2178
- return path.resolve(baseDir);
2560
+ function signerProbeErrorCode(probe) {
2561
+ if (!probe || probe.status === "ok") return void 0;
2562
+ return `local_signer_probe_${probe.status}`;
2179
2563
  }
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);
2564
+ function hostedMcpErrorCode(hostedConfigured, hostedProbeStatus) {
2565
+ if (!hostedConfigured || hostedProbeStatus === "ok") return void 0;
2566
+ return `hosted_mcp_probe_${hostedProbeStatus}`;
2185
2567
  }
2186
- function safePathPart(value) {
2187
- return value.replace(/[^A-Za-z0-9_.-]/g, "_");
2568
+ function localMcpErrorCode(signerCredentialReady, localMcpConsent, localMcpProbeStatus) {
2569
+ if (!signerCredentialReady) return "local_signer_credential_unavailable";
2570
+ if (!localMcpConsent?.acknowledged) return "local_mcp_ack_required";
2571
+ if (localMcpProbeStatus && localMcpProbeStatus !== "ok") return `local_mcp_probe_${localMcpProbeStatus}`;
2572
+ return void 0;
2188
2573
  }
2189
- function dropUndefined(value) {
2190
- return Object.fromEntries(Object.entries(value).filter(([, field]) => field !== void 0));
2574
+ function nextAction(runtime, restartMode, errorCode) {
2575
+ if (errorCode) return "return_to_haven_for_wallet_approval_then_finish_runtime_setup";
2576
+ if (restartMode === "hot-reload") return "return_to_haven_for_wallet_approval";
2577
+ if (runtime === "codex-cli" || runtime === "codex-desktop") return "return_to_haven_for_wallet_approval_then_restart_codex";
2578
+ if (runtime === "claude-code") return "return_to_haven_for_wallet_approval_then_restart_claude_code";
2579
+ if (restartMode === "restart-app") return "return_to_haven_for_wallet_approval_then_restart_app";
2580
+ if (restartMode === "restart-session") return "return_to_haven_for_wallet_approval_then_restart_agent_session";
2581
+ return "return_to_haven_for_wallet_approval_then_configure_runtime";
2582
+ }
2583
+ function supportsLocalMcp(runtime) {
2584
+ return runtime === "codex-cli" || runtime === "codex-desktop" || runtime === "claude-code";
2585
+ }
2586
+ async function prepareRuntimeForLocalMcp(input, deps) {
2587
+ const prepare = deps.prepareLocalMcpRuntime ?? ((runtimeInput) => prepareLocalMcpRuntime(runtimeInput, { runCommand: deps.runCommand, onProgress: deps.onProgress }));
2588
+ return prepare({
2589
+ credentialDirectory: input.credentialDirectory,
2590
+ identityPath: input.identityPath,
2591
+ signerPath: input.signerPath,
2592
+ homeDir: deps.homeDir,
2593
+ serverName: input.serverName
2594
+ });
2595
+ }
2596
+ async function prepareSignerForRuntime(input, deps) {
2597
+ const prepare = deps.prepareSignerRuntime ?? ((runtimeInput) => (
2598
+ // onProgress threaded through on purpose (#1586 review): without it the
2599
+ // install heartbeat was dead code in production and the console still
2600
+ // went silent for the whole cold install — the exact symptom the issue
2601
+ // set out to remove, at a longer timeout.
2602
+ prepareSignerRuntime(runtimeInput, { runCommand: deps.runCommand, onProgress: deps.onProgress })
2603
+ ));
2604
+ return prepare({
2605
+ credentialDirectory: input.credentialDirectory,
2606
+ signerPath: input.signerPath,
2607
+ homeDir: deps.homeDir,
2608
+ serverName: input.serverName
2609
+ });
2191
2610
  }
2192
- async function assertDoesNotExist(path) {
2611
+ async function runLocalMcpProbe(runtimeInstall, deps) {
2612
+ const probe = deps.probeLocalMcpTools ?? probeLocalMcpTools;
2193
2613
  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;
2614
+ return await probe(runtimeInstall.command, runtimeInstall.args, MCP_RUNTIME_MANIFEST.requiredTools);
2615
+ } catch {
2616
+ return { status: "process_error" };
2198
2617
  }
2199
- throw new Error(`Refusing to overwrite existing Haven credential file: ${path}`);
2200
2618
  }
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
- );
2619
+ function localRuntimePrepareErrorCode(err) {
2620
+ if (err && typeof err === "object" && "code" in err && err.code === "local_mcp_unsupported_node_version") {
2621
+ return "local_mcp_unsupported_node_version";
2208
2622
  }
2623
+ return "local_mcp_runtime_install_failed";
2209
2624
  }
2210
-
2211
- // src/runtime-install.ts
2212
- init_config_writers();
2213
- init_server_names();
2214
- async function acknowledgeLocalMcpConsent(identityPath, signerPath, log) {
2215
- 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
2221
- });
2222
- return {
2223
- acknowledged: decision.ok,
2224
- hash: decision.hash,
2225
- reason: decision.reason
2226
- };
2227
- } catch (err) {
2228
- return {
2229
- acknowledged: false,
2230
- error: err instanceof Error ? err.message : String(err)
2231
- };
2625
+ var execFileAsync3;
2626
+ var init_runtime_install = __esm({
2627
+ "src/runtime-install.ts"() {
2628
+ init_config_writers();
2629
+ init_server_names();
2630
+ init_local_mcp_consent();
2631
+ init_probes();
2632
+ init_local_mcp_runtime();
2633
+ init_signer_runtime();
2634
+ init_runtime_manifest();
2635
+ init_skill_install();
2636
+ init_runtime_registry();
2637
+ init_signer_consent();
2638
+ execFileAsync3 = util.promisify(child_process.execFile);
2232
2639
  }
2640
+ });
2641
+
2642
+ // src/tombstone.ts
2643
+ var tombstone_exports = {};
2644
+ __export(tombstone_exports, {
2645
+ TOMBSTONE_FILENAME: () => TOMBSTONE_FILENAME,
2646
+ TOMBSTONE_MARKER: () => TOMBSTONE_MARKER,
2647
+ readAgentTombstone: () => readAgentTombstone,
2648
+ writeAgentTombstone: () => writeAgentTombstone
2649
+ });
2650
+ function tombstoneScript(info) {
2651
+ const lines = [
2652
+ `${TOMBSTONE_MARKER}: this Haven agent was retired.`,
2653
+ "",
2654
+ ` agent: ${info.agent_id}`,
2655
+ ` retired at: ${info.retired_at}`,
2656
+ ` reason: ${info.reason}`,
2657
+ ...info.replaced_by ? [` replaced by: ${info.replaced_by}`] : [],
2658
+ "",
2659
+ "This process is running with a wiring snapshot that predates the",
2660
+ "retirement \u2014 it loaded its MCP config at startup and has kept it since.",
2661
+ "Restart THIS host to pick up the current wiring. If several long-lived",
2662
+ "hosts are running (a gateway, a TUI worker, an editor), restart EVERY",
2663
+ "one of them: each holds the snapshot from its own start time, so after",
2664
+ "a chain of recreations each can be parked on a DIFFERENT old agent.",
2665
+ "",
2666
+ "Then verify with: npx @haven_ai/connect@alpha --doctor --runtime <runtime>"
2667
+ ];
2668
+ return [
2669
+ "#!/usr/bin/env node",
2670
+ `// ${TOMBSTONE_MARKER} \u2014 written by @haven_ai/connect (#1681). Safe to delete`,
2671
+ "// once every long-lived MCP host on this machine has been restarted.",
2672
+ `process.stderr.write(${JSON.stringify(lines.join("\n") + "\n")})`,
2673
+ "process.exit(1)",
2674
+ ""
2675
+ ].join("\n");
2233
2676
  }
2234
- async function getLocalMcpConsentStatus(identityPath, signerPath) {
2235
- 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
- }
2242
- return {
2243
- acknowledged: false,
2244
- hash,
2245
- reason: stored ? "ack_file_mismatch" : "ack_file_missing"
2246
- };
2247
- } catch (err) {
2248
- return {
2249
- acknowledged: false,
2250
- error: err instanceof Error ? err.message : String(err)
2251
- };
2677
+ async function writeAgentTombstone(input) {
2678
+ const dirStat = await promises.stat(input.directory).catch(() => null);
2679
+ if (!dirStat?.isDirectory()) {
2680
+ throw new Error(`Not a directory: ${input.directory} \u2014 nothing to tombstone.`);
2252
2681
  }
2253
- }
2254
- function localMcpAckPath(identityPath) {
2255
- return path.resolve(`${identityPath}.ack.json`);
2256
- }
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
- }
2682
+ const info = {
2683
+ // reason / replaced_by are persisted to disk and re-emitted to the host's
2684
+ // MCP stderr log on EVERY stale probe, potentially for months — redact
2685
+ // like every other output path, at the write layer so any future caller
2686
+ // inherits it. (#1681 review, finding 1)
2687
+ agent_id: input.agentId,
2688
+ retired_at: input.retiredAt ?? (/* @__PURE__ */ new Date()).toISOString(),
2689
+ reason: redactSecrets(input.reason),
2690
+ ...input.replacedBy ? { replaced_by: redactSecrets(input.replacedBy) } : {}
2263
2691
  };
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
- );
2692
+ const binDir = path.join(input.directory, "bin");
2693
+ await promises.mkdir(binDir, { recursive: true });
2694
+ const wrapperPath = path.join(binDir, "haven-signer.mjs");
2695
+ await promises.writeFile(wrapperPath, tombstoneScript(info), "utf8");
2696
+ await promises.chmod(wrapperPath, 493);
2697
+ await promises.writeFile(path.join(input.directory, TOMBSTONE_FILENAME), JSON.stringify(info, null, 2) + "\n", "utf8");
2698
+ return info;
2277
2699
  }
2278
- async function readLocalMcpAckFile(path) {
2700
+ async function readAgentTombstone(directory) {
2279
2701
  try {
2280
- const parsed = JSON.parse(await promises.readFile(path, "utf8"));
2281
- return typeof parsed.ack === "string" ? parsed.ack : null;
2702
+ const parsed = JSON.parse(await promises.readFile(path.join(directory, TOMBSTONE_FILENAME), "utf8"));
2703
+ if (typeof parsed?.agent_id !== "string") return null;
2704
+ return parsed;
2282
2705
  } catch {
2283
2706
  return null;
2284
2707
  }
2285
2708
  }
2286
- function writeLogChunk(log, chunk) {
2287
- const message = String(chunk).trimEnd();
2288
- if (message) log(message);
2289
- }
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()}.`);
2709
+ var TOMBSTONE_FILENAME, TOMBSTONE_MARKER;
2710
+ var init_tombstone = __esm({
2711
+ "src/tombstone.ts"() {
2712
+ init_redact();
2713
+ TOMBSTONE_FILENAME = "TOMBSTONE.json";
2714
+ TOMBSTONE_MARKER = "HAVEN-TOMBSTONE";
2325
2715
  }
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,
2331
- 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,
2340
- serverName: input.serverName
2716
+ });
2717
+
2718
+ // src/rekey.ts
2719
+ var rekey_exports = {};
2720
+ __export(rekey_exports, {
2721
+ finishRekey: () => finishRekey,
2722
+ startRekey: () => startRekey
2723
+ });
2724
+ async function startRekey(options, deps = {}) {
2725
+ const now = deps.now ?? (() => Date.now());
2726
+ const stored = await readStoredCredentials(
2727
+ options.serverName,
2728
+ options.agentId,
2729
+ options.credentialsDir
2730
+ );
2731
+ const api = (deps.createApi ?? ((url) => createConnectApiClient(url)))(stored.apiUrl);
2732
+ const identity = await probeIdentity(api, stored.apiKey, "current");
2733
+ assertRekeyable(identity, stored);
2734
+ const key = (deps.generateKey ?? generateDelegateKey)();
2735
+ const startedAt = new Date(now()).toISOString();
2736
+ const expiresAt = new Date(now() + REKEY_PENDING_TTL_MS).toISOString();
2737
+ await writeRekeyPending(stored.directory, {
2738
+ agent_id: stored.agentId,
2739
+ new_delegate_address: key.address,
2740
+ new_delegate_key: key.privateKey,
2741
+ started_at: startedAt,
2742
+ expires_at: expiresAt
2341
2743
  });
2342
- messages.push(`Prepared stable local Haven MCP wrapper: ${wrapperPath}`);
2744
+ const finishCommand = [
2745
+ "npx @haven_ai/connect@alpha --rekey-finish",
2746
+ options.serverName ? `--name ${options.serverName}` : void 0,
2747
+ "--api-key <the key the dashboard showed you>",
2748
+ options.runtime ? `--runtime ${options.runtime}` : "--runtime <your runtime>"
2749
+ ].filter(Boolean).join(" ");
2343
2750
  return {
2344
- command: wrapperPath,
2345
- args: [],
2346
- wrapperPath,
2347
- runtimeDirectory,
2348
- npmCacheDirectory,
2349
- cliPath,
2350
- messages
2751
+ started: true,
2752
+ agentId: stored.agentId,
2753
+ directory: stored.directory,
2754
+ newDelegateAddress: key.address,
2755
+ expiresAt,
2756
+ messages: [
2757
+ `New signing key generated on this machine for agent ${identity.name || stored.agentId}.`,
2758
+ "",
2759
+ ` New signing address: ${key.address}`,
2760
+ "",
2761
+ "The private half stays here \u2014 Haven never receives it, and there is no way to move it",
2762
+ "between machines. That is what keeps the account non-custodial.",
2763
+ "",
2764
+ 'Next, on the Haven agent page: choose "Replace signing key" and paste that address.',
2765
+ "When it finishes it shows a new API key ONCE. Come back here and run:",
2766
+ "",
2767
+ ` ${finishCommand}`,
2768
+ "",
2769
+ `Nothing has changed yet \u2014 the agent keeps working on its old key until you finish.`,
2770
+ `This pending re-key expires ${expiresAt}.`
2771
+ ]
2351
2772
  };
2352
2773
  }
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);
2774
+ async function finishRekey(options, deps = {}) {
2775
+ const now = deps.now ?? (() => Date.now());
2776
+ if (!options.newApiKey) {
2777
+ throw new Error("--rekey-finish needs --api-key <key> \u2014 the one the Haven agent page showed once.");
2356
2778
  }
2357
- }
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);
2779
+ const stored = await readStoredCredentials(
2780
+ options.serverName,
2781
+ options.agentId,
2782
+ options.credentialsDir
2783
+ );
2784
+ const pending = await readRekeyPending(stored.directory, now());
2785
+ if (pending.agent_id !== stored.agentId) {
2786
+ throw new Error(
2787
+ `The pending re-key at ${stored.directory} belongs to agent ${pending.agent_id}, but that directory now holds ${stored.agentId}. Refusing to write a key into the wrong agent.`
2788
+ );
2789
+ }
2790
+ const api = (deps.createApi ?? ((url) => createConnectApiClient(url)))(stored.apiUrl);
2791
+ const identity = await probeIdentity(api, options.newApiKey, "new");
2792
+ if (identity.id !== stored.agentId) {
2793
+ throw new Error(
2794
+ `That API key belongs to agent ${identity.id}, not ${stored.agentId}. Nothing was changed.`
2795
+ );
2796
+ }
2797
+ const onChain = (identity.delegate_address ?? "").toLowerCase();
2798
+ const expected = pending.new_delegate_address.toLowerCase();
2799
+ if (onChain !== expected) {
2800
+ throw new Error(
2801
+ `Haven says this agent's signing address is ${identity.delegate_address ?? "unset"}, but this machine generated ${pending.new_delegate_address}. Nothing was changed. Either the re-key on the agent page used a different address, or it has not finished yet.`
2802
+ );
2803
+ }
2804
+ await rewriteCredentialFiles({
2805
+ baseDir: options.credentialsDir,
2806
+ agentId: stored.agentId,
2807
+ serverName: options.serverName,
2808
+ apiKey: options.newApiKey,
2809
+ delegateKey: pending.new_delegate_key,
2810
+ delegateAddress: pending.new_delegate_address,
2811
+ safeAddress: stored.safeAddress ?? identity.safe_address ?? void 0,
2812
+ chainId: stored.chainId ?? identity.chain_id ?? void 0,
2813
+ network: stored.network,
2814
+ agentBudget: stored.agentBudget,
2815
+ apiUrl: stored.apiUrl,
2816
+ hostedMcpUrl: stored.hostedMcpUrl,
2817
+ x402BindingSigner: stored.x402BindingSigner,
2818
+ warn: deps.log
2819
+ });
2820
+ await clearRekeyPending(stored.directory);
2821
+ const names = serverNamesFor(options.serverName);
2822
+ const messages = [
2823
+ `Agent ${identity.name || stored.agentId} is now on its new signing key.`,
2824
+ ` Signing address: ${pending.new_delegate_address}`,
2825
+ ` Credentials: ${stored.directory} (rewritten in place)`,
2826
+ ` MCP servers: ${names.hosted} / ${names.signer} (unchanged names)`
2827
+ ];
2828
+ let configRewritten = false;
2829
+ if (options.runtime) {
2830
+ const prepared = await (deps.prepareSigner ?? prepareSignerRuntime)(
2831
+ {
2832
+ credentialDirectory: stored.directory,
2833
+ signerPath: `${stored.directory}/signer.json`,
2834
+ homeDir: options.homeDir
2835
+ },
2836
+ { runCommand: deps.runCommand }
2837
+ );
2838
+ const result = await (deps.writeConfig ?? writeHostedRuntimeConfig)(
2839
+ { runCommand: deps.runCommand, homeDir: options.homeDir },
2840
+ {
2841
+ runtime: options.runtime,
2842
+ hostedMcpUrl: stored.hostedMcpUrl,
2843
+ apiKey: options.newApiKey,
2844
+ identityPath: `${stored.directory}/identity.json`,
2845
+ signerPath: `${stored.directory}/signer.json`,
2846
+ credentialDirectory: stored.directory,
2847
+ serverName: options.serverName
2848
+ },
2849
+ { command: prepared.command, args: prepared.args }
2850
+ );
2851
+ configRewritten = result.hostedConfigured;
2852
+ messages.push(` Config: ${result.target}`);
2853
+ messages.push(...result.messages.map((line) => ` ${line}`));
2854
+ if (!configRewritten) {
2855
+ messages.push(
2856
+ "",
2857
+ "WARNING: the MCP config was NOT updated, so it still carries the OLD API key and every",
2858
+ `wired host will fail with 401. Fix the cause above and re-run with --runtime ${options.runtime},`,
2859
+ "or update the config by hand. The credential files on disk are already on the new key."
2860
+ );
2383
2861
  }
2862
+ } else {
2863
+ messages.push(
2864
+ "",
2865
+ "NOTE: no --runtime was given, so the MCP config still carries the OLD API key and every",
2866
+ "wired host will fail with 401. Re-run with --runtime <name> to rewrite it."
2867
+ );
2868
+ }
2869
+ return {
2870
+ finished: true,
2871
+ agentId: stored.agentId,
2872
+ directory: stored.directory,
2873
+ newDelegateAddress: pending.new_delegate_address,
2874
+ serverNames: { hosted: names.hosted, signer: names.signer },
2875
+ configRewritten,
2876
+ messages
2384
2877
  };
2878
+ }
2879
+ async function probeIdentity(api, apiKey, which) {
2385
2880
  try {
2386
- await run(baseArgs);
2387
- } 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)}`);
2881
+ return await api.getAgentIdentity(apiKey);
2882
+ } catch (err) {
2883
+ const status = err?.status;
2884
+ if (status === 401 || status === 403) {
2885
+ throw new Error(
2886
+ which === "current" ? "This machine's Haven API key is no longer accepted. If a re-key already finished elsewhere, run --rekey-finish with the key that re-key produced instead of starting a new one." : "Haven rejected that API key. Check you pasted the whole key from the agent page \u2014 nothing was changed."
2887
+ );
2392
2888
  }
2889
+ throw new Error(
2890
+ `Could not reach Haven to check this agent (${redactSecrets(
2891
+ err instanceof Error ? err.message : String(err)
2892
+ )}). Nothing was changed.`
2893
+ );
2393
2894
  }
2394
2895
  }
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;
2896
+ function assertRekeyable(identity, stored) {
2897
+ if (identity.id !== stored.agentId) {
2898
+ throw new Error(
2899
+ `The credentials at ${stored.directory} say agent ${stored.agentId}, but Haven says that key belongs to ${identity.id}. Refusing to re-key an agent this directory does not own.`
2900
+ );
2405
2901
  }
2406
- }
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'",
2416
- "",
2417
- `const cliPath = ${JSON.stringify(input.cliPath)}`,
2418
- `const identityPath = ${JSON.stringify(input.identityPath)}`,
2419
- `const signerPath = ${JSON.stringify(input.signerPath)}`,
2420
- "",
2421
- "const child = spawn(process.execPath, [cliPath, '--identity', identityPath, '--signer', signerPath, ...process.argv.slice(2)], {",
2422
- " stdio: 'inherit',",
2423
- "})",
2424
- "",
2425
- "child.on('exit', (code, signal) => {",
2426
- " if (signal) process.kill(process.pid, signal)",
2427
- " else process.exit(code ?? 1)",
2428
- "})",
2429
- ""
2430
- ].join("\n");
2431
- await promises.writeFile(input.wrapperPath, source, { mode: 448 });
2432
- await promises.chmod(input.wrapperPath, 448).catch(() => void 0);
2433
- }
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
2446
- };
2447
- await promises.writeFile(input.path, `${JSON.stringify(value, null, 2)}
2448
- `, { mode: 384 });
2449
- await promises.chmod(input.path, 384).catch(() => void 0);
2450
- }
2451
- async function assertFileExists2(path, label) {
2452
- try {
2453
- await promises.access(path);
2454
- } catch {
2455
- throw new Error(`Missing ${label}: ${path}`);
2902
+ if (identity.execution_rail === "legacy") {
2903
+ throw new Error(
2904
+ `Agent ${identity.name || identity.id} is on the legacy rail, which cannot be re-keyed \u2014 its authority is per-token Safe allowances, not a signed delegation there is anything to re-issue. Re-onboard the agent on the delegation rail instead.`
2905
+ );
2906
+ }
2907
+ if (identity.status === "revoked") {
2908
+ throw new Error(
2909
+ `Agent ${identity.name || identity.id} is revoked. Re-keying would hand a revoked agent fresh credentials \u2014 create a new agent instead.`
2910
+ );
2456
2911
  }
2457
2912
  }
2913
+ var init_rekey = __esm({
2914
+ "src/rekey.ts"() {
2915
+ init_api();
2916
+ init_runtime_install();
2917
+ init_signer_runtime();
2918
+ init_key();
2919
+ init_redact();
2920
+ init_server_names();
2921
+ init_storage();
2922
+ }
2923
+ });
2458
2924
 
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"
2475
- );
2476
- case "codex-cli":
2477
- case "codex-desktop":
2478
- return installCodexAgentsSection(deps);
2479
- default:
2480
- return void 0;
2925
+ // src/rekey-restart.ts
2926
+ var rekey_restart_exports = {};
2927
+ __export(rekey_restart_exports, {
2928
+ restartGuidance: () => restartGuidance
2929
+ });
2930
+ function restartGuidance(runtime) {
2931
+ const profile = runtime ? BY_RUNTIME[runtime] : void 0;
2932
+ const lines = ["The new key is only live in a process that started after now.", ""];
2933
+ if (profile) {
2934
+ lines.push(profile.how);
2935
+ for (const command of profile.commands) lines.push(` ${command}`);
2936
+ if (profile.commands.length > 0) lines.push("");
2937
+ } else {
2938
+ lines.push(
2939
+ runtime ? `No standard restart command is known for "${runtime}" \u2014 restart it the way you start it.` : "Pass --runtime <name> to get the restart command for a specific host."
2940
+ );
2941
+ lines.push("");
2481
2942
  }
2943
+ lines.push(SWEEP);
2944
+ return { commands: profile?.commands ?? [], lines };
2482
2945
  }
2483
- async function installSkillFile(skillDir, label) {
2484
- 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.`]
2946
+ var SWEEP, BY_RUNTIME;
2947
+ var init_rekey_restart = __esm({
2948
+ "src/rekey-restart.ts"() {
2949
+ SWEEP = "Then restart EVERY other long-lived MCP host on this machine \u2014 gateways, TUI workers, editors. Each holds the wiring snapshot from its own start time, so after a re-key each one is still presenting the OLD API key and will fail with 401 until it restarts.";
2950
+ BY_RUNTIME = {
2951
+ "claude-code": {
2952
+ commands: ["claude --continue"],
2953
+ how: "Exit this Claude Code session and start a new one:"
2954
+ },
2955
+ "codex-cli": {
2956
+ commands: ["codex resume --last"],
2957
+ how: "Start a fresh Codex CLI session:"
2958
+ },
2959
+ "codex-desktop": {
2960
+ commands: [],
2961
+ how: "Quit Codex Desktop completely (not just the window) and reopen it."
2962
+ },
2963
+ "claude-desktop": {
2964
+ commands: [],
2965
+ how: "Quit Claude Desktop completely (not just the window) and reopen it."
2966
+ },
2967
+ hermes: {
2968
+ commands: ["systemctl --user restart hermes-gateway", "/restart"],
2969
+ how: "Restart the Hermes gateway, or run /restart inside a Hermes session. The first form is the one that matters if you run it as a user service:"
2970
+ },
2971
+ cursor: {
2972
+ commands: [],
2973
+ how: 'Cursor hot-reloads MCP config, so it will pick the new key up on its own. If a tool call still fails with 401, reload the window (Cmd/Ctrl+Shift+P \u2192 "Reload Window").'
2974
+ },
2975
+ vscode: {
2976
+ commands: [],
2977
+ how: 'VS Code hot-reloads MCP config. If a tool call still fails with 401, reload the window (Cmd/Ctrl+Shift+P \u2192 "Reload Window").'
2978
+ },
2979
+ "vscode-insiders": {
2980
+ commands: [],
2981
+ how: 'VS Code Insiders hot-reloads MCP config. If a tool call still fails with 401, reload the window (Cmd/Ctrl+Shift+P \u2192 "Reload Window").'
2982
+ }
2492
2983
  };
2493
- } catch (err) {
2984
+ }
2985
+ });
2986
+
2987
+ // src/doctor.ts
2988
+ var doctor_exports = {};
2989
+ __export(doctor_exports, {
2990
+ runDoctor: () => runDoctor,
2991
+ runRepair: () => runRepair
2992
+ });
2993
+ async function discoverCredentialDirectory(homeDir, explicit) {
2994
+ const root = explicit ? path.dirname(explicit) : path.join(homeDir, ".haven", "agents");
2995
+ let entries = [];
2996
+ try {
2997
+ entries = await promises.readdir(root);
2998
+ } catch {
2999
+ return explicit ? { directory: explicit, others: [], parkedOnly: /* @__PURE__ */ new Set() } : { others: [], parkedOnly: /* @__PURE__ */ new Set() };
3000
+ }
3001
+ const candidates = [];
3002
+ const tombstonedOnly = [];
3003
+ const parkedOnly = [];
3004
+ for (const entry of entries) {
3005
+ const directory = path.join(root, entry);
3006
+ try {
3007
+ const s = await promises.stat(path.join(directory, "identity.json"));
3008
+ candidates.push({ directory, mtimeMs: s.mtimeMs });
3009
+ } catch {
3010
+ try {
3011
+ await promises.stat(path.join(directory, TOMBSTONE_FILENAME));
3012
+ tombstonedOnly.push(directory);
3013
+ } catch {
3014
+ try {
3015
+ await promises.stat(path.join(directory, REKEY_PENDING_FILENAME));
3016
+ parkedOnly.push(directory);
3017
+ } catch {
3018
+ }
3019
+ }
3020
+ }
3021
+ }
3022
+ const parkedOnlySet = new Set(parkedOnly);
3023
+ candidates.sort((a, b) => b.mtimeMs - a.mtimeMs);
3024
+ if (explicit) {
2494
3025
  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
- ]
3026
+ directory: explicit,
3027
+ others: [...candidates.map((c) => c.directory), ...tombstonedOnly, ...parkedOnly].filter((d) => d !== explicit),
3028
+ parkedOnly: parkedOnlySet
2499
3029
  };
2500
3030
  }
3031
+ if (candidates.length === 0 && tombstonedOnly.length === 0 && parkedOnly.length === 0) {
3032
+ return { others: [], parkedOnly: parkedOnlySet };
3033
+ }
3034
+ return {
3035
+ directory: candidates[0]?.directory,
3036
+ others: [...candidates.slice(1).map((c) => c.directory), ...tombstonedOnly, ...parkedOnly],
3037
+ parkedOnly: parkedOnlySet
3038
+ };
2501
3039
  }
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");
3040
+ function agentIsWired(configText, names, slug, identity, sidecar, isPrimary, bareOwnerExists) {
3041
+ if (configText === null) return isPrimary;
3042
+ if (slug) {
3043
+ for (const name of [names.hosted, names.codexHosted, names.signer, names.codexSigner]) {
3044
+ if (new RegExp(`(^|[."'\\s\\[])${name}(["'\\]:\\s]|$)`, "m").test(configText)) return true;
2511
3045
  }
3046
+ return false;
3047
+ }
3048
+ if (sidecar?.wrapper_path && configText.includes(sidecar.wrapper_path)) return true;
3049
+ if (bareOwnerExists) return false;
3050
+ return isPrimary && Boolean(identity?.hosted_mcp_url && configText.includes(identity.hosted_mcp_url));
3051
+ }
3052
+ function rekeyPendingCheck(status, hostedDelegateAddress, runtime, slug) {
3053
+ const label = "Pending re-key";
3054
+ const nameFlag = slug ? ` --name ${slug}` : "";
3055
+ if (status.state === "unreadable") {
2512
3056
  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
- ]
3057
+ id: "rekey_pending",
3058
+ label,
3059
+ ok: false,
3060
+ detail: `A re-key was started here but ${status.path} does not parse, so neither the address it generated nor when it started can be read. The file still holds what was a private key.`,
3061
+ repair: `Delete ${status.path}, then start again: ${RERUN} --rekey${nameFlag}`
2518
3062
  };
2519
- } catch (err) {
3063
+ }
3064
+ const started = status.startedAt ?? "an unknown time";
3065
+ const address = status.newDelegateAddress ?? "unknown";
3066
+ const completedOnHaven = hostedDelegateAddress !== void 0 && status.newDelegateAddress !== void 0 && hostedDelegateAddress.toLowerCase() === status.newDelegateAddress.toLowerCase();
3067
+ if (completedOnHaven) {
2520
3068
  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
- ]
3069
+ id: "rekey_pending",
3070
+ label,
3071
+ ok: false,
3072
+ detail: `A re-key started ${started} has COMPLETED on Haven \u2014 the agent's signing address is already ${address}, the one this machine generated \u2014 but the local half was never finished, so the credential files here still hold the old key. Parked at ${status.path}.` + (status.state === "expired" ? " The local file is also past its 24h TTL, which --rekey-finish refuses, so the finish command below will not accept it any more." : ""),
3073
+ repair: status.state === "expired" ? `The parked key expired. Start again \u2014 ${RERUN} --rekey${nameFlag} \u2014 and re-run "Replace signing key" on the Haven agent page with the new address it prints.` : `Run: ${RERUN} --rekey-finish${nameFlag} --api-key <the key the agent page showed you> --runtime ${runtime}`
3074
+ };
3075
+ }
3076
+ const wedgeNote = "Haven is NOT yet on this address, so the re-key did not complete. This machine cannot tell whether the on-chain revoke on the agent page already ran: if it did not, closing this costs nothing; if it did, the agent's old delegations are revoked, no new ones were issued, and only an owner re-grant restores its spend authority (#1868). Check the agent page before assuming the harmless case.";
3077
+ if (status.state === "expired") {
3078
+ return {
3079
+ id: "rekey_pending",
3080
+ label,
3081
+ ok: false,
3082
+ detail: `A re-key started ${started} EXPIRED ${status.expiresAt ?? ""} without being finished. Its address was ${address}; the private half it generated is still on disk at ${status.path}. ` + wedgeNote,
3083
+ repair: `Either delete ${status.path} to drop the parked key, or start over: ${RERUN} --rekey${nameFlag}. Connect never deletes it for you \u2014 an expired TTL is a refusal to USE the key, not a licence to destroy key material you may still be mid-flow on.`
2525
3084
  };
2526
3085
  }
2527
- }
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;
3086
+ return {
3087
+ id: "rekey_pending",
3088
+ label,
3089
+ ok: true,
3090
+ detail: `A re-key started ${started} is still open (expires ${status.expiresAt ?? "unknown"}). Paste this address into "Replace signing key" on the Haven agent page: ${address}. Parked at ${status.path}. ` + wedgeNote
3091
+ };
3092
+ }
3093
+ async function readIdentity(directory) {
3094
+ try {
3095
+ return JSON.parse(await promises.readFile(path.join(directory, "identity.json"), "utf8"));
3096
+ } catch {
3097
+ return void 0;
3098
+ }
3099
+ }
3100
+ async function checksForAgent(entry, input, deps) {
3101
+ const { directory, identity, sidecar } = entry;
3102
+ const checks = [];
3103
+ let signerCapabilities;
3104
+ let signerFile;
3105
+ try {
3106
+ const parsed = JSON.parse(await promises.readFile(path.join(directory, "signer.json"), "utf8"));
3107
+ signerFile = typeof parsed === "object" && parsed !== null ? parsed : void 0;
3108
+ } catch {
3109
+ signerFile = void 0;
3110
+ }
3111
+ const credentialsOk = Boolean(identity?.api_key) && signerFile !== void 0;
3112
+ checks.push({
3113
+ id: "credentials",
3114
+ label: "Agent credentials",
3115
+ ok: credentialsOk,
3116
+ detail: credentialsOk ? `identity.json and signer.json parse (agent ${identity?.agent_id ?? "unknown"})` : "identity.json or signer.json is missing or unparseable.",
3117
+ ...credentialsOk ? {} : { repair: `Re-run the full setup with a fresh token: ${RERUN} --setup <token>.` }
3118
+ });
3119
+ if (!sidecar) {
3120
+ checks.push({
3121
+ id: "signer_runtime",
3122
+ label: "Signer runtime (preinstalled wrapper)",
3123
+ ok: false,
3124
+ detail: "No signer-runtime.json sidecar \u2014 the pinned signer runtime was never prepared (or a pre-#1586 npx config).",
3125
+ repair: `Run: ${RERUN} --doctor --repair --runtime ${input.runtime}`
3126
+ });
3127
+ } else {
3128
+ const matches = await installedRuntimeMatches(sidecar.runtime_directory, sidecar.cli_path);
3129
+ const versionOk = sidecar.signer_version === MCP_RUNTIME_MANIFEST.signerVersion;
3130
+ const ok = matches && versionOk;
3131
+ checks.push({
3132
+ id: "signer_runtime",
3133
+ label: "Signer runtime (preinstalled wrapper)",
3134
+ ok,
3135
+ detail: ok ? `Installed ${sidecar.signer_package}@${sidecar.signer_version} at ${sidecar.runtime_directory}` : matches ? `Installed version ${sidecar.signer_version} does not match the connector's pinned ${MCP_RUNTIME_MANIFEST.signerVersion}.` : `Runtime directory is stale or empty (${sidecar.runtime_directory}) \u2014 the CLI or package versions are missing.`,
3136
+ ...ok ? {} : { repair: `Run: ${RERUN} --doctor --repair --runtime ${input.runtime}` }
3137
+ });
3138
+ }
3139
+ const hostedUrl = identity?.hosted_mcp_url ?? (identity?.api_url ? `${identity.api_url}/mcp` : void 0);
3140
+ if (identity?.api_key && hostedUrl) {
3141
+ const probe = await (deps.probeHosted ?? probeHostedMcpTools)(identity.api_key, hostedUrl, deps.fetch);
3142
+ checks.push({
3143
+ id: "hosted_mcp",
3144
+ label: "Hosted Haven MCP",
3145
+ ok: probe.status === "ok",
3146
+ detail: probe.status === "ok" ? `Reachable and authorized (${hostedUrl}).` : `Probe failed: ${probe.status} (${hostedUrl}).`,
3147
+ ...probe.status === "ok" ? {} : {
3148
+ repair: probe.status === "unauthorized" ? `The stored API key was rejected \u2014 re-run the full setup with a fresh token: ${RERUN} --setup <token>.` : "Check network access to the hosted MCP URL, then re-run --doctor."
3149
+ }
3150
+ });
3151
+ } else {
3152
+ checks.push({
3153
+ id: "hosted_mcp",
3154
+ label: "Hosted Haven MCP",
3155
+ ok: false,
3156
+ detail: "No stored API key / hosted MCP URL to probe with.",
3157
+ repair: `Re-run the full setup: ${RERUN} --setup <token>.`
3158
+ });
2544
3159
  }
2545
- if (begins.length > 0 || ends.length > 0) {
2546
- throw new Error(
2547
- "found a damaged Haven marker section (orphaned or duplicated markers); remove the leftover marker lines and re-run setup"
3160
+ const localDelegate = typeof signerFile?.delegate_address === "string" ? signerFile.delegate_address : void 0;
3161
+ let hostedDelegateAddress;
3162
+ if (identity?.api_key && identity.api_url) {
3163
+ const probe = await (deps.probeHostedIdentity ?? probeHostedAgentIdentity)(
3164
+ identity.api_key,
3165
+ identity.api_url,
3166
+ deps.fetch
2548
3167
  );
3168
+ if (probe.status === "ok") hostedDelegateAddress = probe.delegateAddress;
3169
+ if (probe.status !== "ok") {
3170
+ checks.push({
3171
+ id: "identity_match",
3172
+ label: "Hosted identity matches the local signing key",
3173
+ ok: false,
3174
+ detail: probe.status === "unauthorized" ? "The stored API key was rejected, so the agent it authenticates as cannot be compared with the local signing key." : `Could not read the hosted identity (${probe.status}) \u2014 the comparison did not happen, so it cannot be reported as a match.`,
3175
+ repair: probe.status === "unauthorized" ? `Re-run the full setup with a fresh token: ${RERUN} --setup <token>.` : `Restore network access to the Haven API, then re-run: ${RERUN} --doctor --runtime ${input.runtime}`
3176
+ });
3177
+ } else if (!localDelegate) {
3178
+ checks.push({
3179
+ id: "identity_match",
3180
+ label: "Hosted identity matches the local signing key",
3181
+ ok: false,
3182
+ detail: "signer.json holds no delegate_address to compare against the hosted identity.",
3183
+ repair: `Re-run the full setup with a fresh token: ${RERUN} --setup <token>.`
3184
+ });
3185
+ } else {
3186
+ const same = probe.delegateAddress?.toLowerCase() === localDelegate.toLowerCase();
3187
+ checks.push({
3188
+ id: "identity_match",
3189
+ label: "Hosted identity matches the local signing key",
3190
+ ok: same,
3191
+ detail: same ? `The stored API key authenticates as the agent whose signing key is in this directory (${shortAddress(localDelegate)}).` : `MISMATCH: the stored API key authenticates as agent ${probe.agentId ?? "unknown"} with delegate ${shortAddress(probe.delegateAddress ?? "unknown")}, but signer.json here holds ${shortAddress(localDelegate)}. This runtime would quote as one agent and sign as another.`,
3192
+ ...same ? {} : {
3193
+ repair: `Re-run setup for this agent so its API key and signing key come from one run: ${RERUN} --setup <token>. Do not hand-edit either file.`
3194
+ }
3195
+ });
3196
+ }
2549
3197
  }
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;
3198
+ const pending = await inspectRekeyPending(directory, deps.now?.() ?? Date.now());
3199
+ if (pending) {
3200
+ checks.push(rekeyPendingCheck(pending, hostedDelegateAddress, input.runtime, sidecar?.server_name));
2559
3201
  }
2560
- }
2561
- function hermesHome(deps) {
2562
- const env = deps.env ?? process.env;
2563
- return env.HERMES_HOME ?? path.join(deps.homeDir ?? os.homedir(), ".hermes");
2564
- }
2565
-
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
- ]
2603
- };
3202
+ if (sidecar) {
3203
+ const consent = await getLocalSignerConsentStatus(path.join(directory, "signer.json"));
3204
+ if (!consent.acknowledged) {
3205
+ checks.push({
3206
+ id: "signer_process",
3207
+ label: "Signer stdio handshake",
3208
+ ok: false,
3209
+ detail: "The local-tools consent is not acknowledged, so the signer refuses to start (by design).",
3210
+ repair: `Run: ${RERUN} --ack-local-tools --setup <token> (or re-run your original setup command with --ack-local-tools).`
3211
+ });
3212
+ } else {
3213
+ const probe = await (deps.probeSignerTools ?? probeLocalMcpTools)(
3214
+ sidecar.wrapper_path,
3215
+ [],
3216
+ MCP_RUNTIME_MANIFEST.requiredSignerTools
3217
+ );
3218
+ const experimental = probe.capabilities?.experimental ?? probe.capabilities;
3219
+ const compat = experimental?.["haven/signer-compatibility"];
3220
+ signerCapabilities = compat ? { "haven/signer-compatibility": compat } : void 0;
3221
+ const compatDetail = compat ? ` Compat: x402 expected-context v${JSON.stringify(compat.x402_expected_context_versions ?? "?")}.` : "";
3222
+ checks.push({
3223
+ id: "signer_process",
3224
+ label: "Signer stdio handshake",
3225
+ ok: probe.status === "ok",
3226
+ detail: probe.status === "ok" ? `Signer started, listed ${probe.toolNames?.length ?? 0} tools${probe.serverInfo?.version ? ` (v${probe.serverInfo.version})` : ""}.${compatDetail}` : `Handshake failed: ${probe.status}.`,
3227
+ ...probe.status === "ok" ? {} : { repair: `Run: ${RERUN} --doctor --repair --runtime ${input.runtime}` }
3228
+ });
3229
+ }
3230
+ } else {
3231
+ checks.push({
3232
+ id: "signer_process",
3233
+ label: "Signer stdio handshake",
3234
+ ok: false,
3235
+ detail: "Skipped \u2014 no prepared signer runtime to probe.",
3236
+ repair: `Run: ${RERUN} --doctor --repair --runtime ${input.runtime}`
3237
+ });
2604
3238
  }
2605
- let localRuntimeInstall;
2606
- let localRuntimeError;
2607
- if (localRuntime) {
3239
+ return { checks, ...signerCapabilities ? { signerCapabilities } : {} };
3240
+ }
3241
+ async function runDoctor(input, deps = {}) {
3242
+ const homeDir = deps.homeDir ?? os.homedir();
3243
+ const checks = [];
3244
+ let signerCapabilities;
3245
+ const { directory, others, parkedOnly } = await discoverCredentialDirectory(homeDir, input.credentialsDir);
3246
+ const configPath = runtimeConfigPathFor(input.runtime, homeDir);
3247
+ let configText = null;
3248
+ if (configPath !== null) {
2608
3249
  try {
2609
- localRuntimeInstall = await prepareRuntimeForLocalMcp(input, deps);
2610
- } catch (err) {
2611
- localRuntimeError = err;
3250
+ configText = await promises.readFile(configPath, "utf8");
3251
+ } catch {
3252
+ configText = null;
2612
3253
  }
2613
3254
  }
2614
- if (localRuntimeError) {
2615
- const errorCode2 = localRuntimePrepareErrorCode(localRuntimeError);
2616
- 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
- ]
2634
- };
2635
- }
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
- };
3255
+ const allDirectories = directory ? [directory, ...others] : others;
3256
+ let bareOwnerExists = false;
3257
+ for (const dir of allDirectories) {
3258
+ const sidecar = await readRuntimeSidecar(dir);
3259
+ if (!sidecar?.server_name && sidecar?.wrapper_path && configText?.includes(sidecar.wrapper_path)) {
3260
+ bareOwnerExists = true;
3261
+ break;
2666
3262
  }
2667
3263
  }
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"
2682
- });
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
3264
+ const inventory = [];
3265
+ const capabilitiesByDirectory = /* @__PURE__ */ new Map();
3266
+ const primaryChecksById = /* @__PURE__ */ new Map();
3267
+ for (const dir of allDirectories) {
3268
+ const identity = await readIdentity(dir);
3269
+ const sidecar = await readRuntimeSidecar(dir);
3270
+ const tombstone = await readAgentTombstone(dir);
3271
+ const slug = sidecar?.server_name;
3272
+ const names = serverNamesFor(slug);
3273
+ const rekeyPending = await inspectRekeyPending(dir, deps.now?.() ?? Date.now());
3274
+ if (!identity?.api_key) {
3275
+ const agentId = tombstone?.agent_id ?? rekeyPending?.agentId;
3276
+ inventory.push({
3277
+ ...slug ? { slug } : {},
3278
+ ...agentId ? { agentId } : {},
3279
+ directory: dir,
3280
+ // A tombstone is a deliberate record and outranks the discovery tell:
3281
+ // a retired directory that also holds a parked key stays `retired`.
3282
+ classification: tombstone ? "retired" : parkedOnly.has(dir) ? "parked" : "orphaned",
3283
+ checks: rekeyPending ? [rekeyPendingCheck(rekeyPending, void 0, input.runtime, slug)] : [],
3284
+ ...rekeyPending ? { rekeyPending } : {}
2699
3285
  });
2700
- } catch {
3286
+ continue;
3287
+ }
3288
+ const wired = agentIsWired(configText, names, slug, identity, sidecar, dir === directory, bareOwnerExists);
3289
+ const entry = {
3290
+ ...slug ? { slug } : {},
3291
+ ...identity.agent_id ? { agentId: identity.agent_id } : {},
3292
+ directory: dir,
3293
+ classification: wired ? "wired" : "superseded",
3294
+ checks: [],
3295
+ ...rekeyPending ? { rekeyPending } : {}
3296
+ };
3297
+ if (wired) {
3298
+ const result = await checksForAgent({ directory: dir, identity, sidecar }, input, deps);
3299
+ entry.checks = result.checks;
3300
+ capabilitiesByDirectory.set(dir, result.signerCapabilities);
3301
+ } else if (rekeyPending) {
3302
+ entry.checks = [rekeyPendingCheck(rekeyPending, void 0, input.runtime, slug)];
2701
3303
  }
3304
+ inventory.push(entry);
2702
3305
  }
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]);
3306
+ const wiredDirectories = inventory.filter((entry) => entry.classification === "wired").map((entry) => entry.directory);
3307
+ const primaryDirectory = input.credentialsDir ? directory : wiredDirectories.includes(directory ?? "") ? directory : wiredDirectories[0] ?? directory;
3308
+ if (primaryDirectory) {
3309
+ const primaryEntry = inventory.find((entry) => entry.directory === primaryDirectory);
3310
+ signerCapabilities = capabilitiesByDirectory.get(primaryDirectory);
3311
+ for (const check of primaryEntry?.checks ?? []) primaryChecksById.set(check.id, check);
3312
+ }
3313
+ if (!primaryDirectory) {
3314
+ checks.push({
3315
+ id: "credentials",
3316
+ label: "Agent credentials",
3317
+ ok: false,
3318
+ detail: "No agent credential directory with an identity.json under ~/.haven/agents.",
3319
+ repair: `Run the full setup once: ${RERUN} --setup <token from the Haven dashboard>.`
2771
3320
  });
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
- };
3321
+ } else {
3322
+ const primaryIdentity = await readIdentity(primaryDirectory);
3323
+ const primarySidecar = await readRuntimeSidecar(primaryDirectory);
3324
+ if (!primaryChecksById.has("credentials")) {
3325
+ const result = await checksForAgent(
3326
+ { directory: primaryDirectory, identity: primaryIdentity, sidecar: primarySidecar },
3327
+ input,
3328
+ deps
3329
+ );
3330
+ signerCapabilities = result.signerCapabilities;
3331
+ for (const check of result.checks) primaryChecksById.set(check.id, check);
3332
+ }
3333
+ for (const id of ["credentials", "signer_runtime"]) {
3334
+ const check = primaryChecksById.get(id);
3335
+ if (check) checks.push(check);
3336
+ }
2801
3337
  }
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"
2850
- };
3338
+ if (configPath === null) {
3339
+ checks.push({
3340
+ id: "runtime_config",
3341
+ label: "Runtime MCP config",
3342
+ ok: true,
3343
+ detail: `Runtime '${input.runtime}' has no file-based config the connector owns (CLI-managed) \u2014 skipping the file check.`
3344
+ });
3345
+ } else if (configText === null) {
3346
+ checks.push({
3347
+ id: "runtime_config",
3348
+ label: "Runtime MCP config",
3349
+ ok: false,
3350
+ detail: `No runtime config at ${configPath}.`,
3351
+ repair: `Run: ${RERUN} --doctor --repair --runtime ${input.runtime}`
3352
+ });
3353
+ } else {
3354
+ const primaryIdentity = await readIdentity(primaryDirectory ?? "");
3355
+ const primarySidecar = primaryDirectory ? await readRuntimeSidecar(primaryDirectory) : null;
3356
+ const hasHaven = primaryIdentity?.hosted_mcp_url ? configText.includes(primaryIdentity.hosted_mcp_url) : configText.includes("haven");
3357
+ const signerViaNpx = configText.includes("@haven_ai/signer");
3358
+ const wrapperReferenced = primarySidecar ? configText.includes(primarySidecar.wrapper_path) : false;
3359
+ const ok = hasHaven && !signerViaNpx && (primarySidecar ? wrapperReferenced : true);
3360
+ checks.push({
3361
+ id: "runtime_config",
3362
+ label: "Runtime MCP config",
3363
+ ok,
3364
+ detail: ok ? `Config at ${configPath} references the hosted server and the prepared signer wrapper.` : signerViaNpx ? `Config at ${configPath} still launches the signer via npx \u2014 the pre-#1586 shape that cannot start under a 120s startup timeout.` : `Config at ${configPath} is missing the Haven entries${primarySidecar && !wrapperReferenced ? " (or references a different signer wrapper)" : ""}.`,
3365
+ ...ok ? {} : { repair: `Run: ${RERUN} --doctor --repair --runtime ${input.runtime}` }
3366
+ });
2851
3367
  }
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";
3368
+ for (const id of ["hosted_mcp", "identity_match", "rekey_pending"]) {
3369
+ const check = primaryChecksById.get(id);
3370
+ if (check) checks.push(check);
2860
3371
  }
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.");
3372
+ const otherEntries = inventory.filter((entry) => entry.directory !== primaryDirectory);
3373
+ if (otherEntries.length > 0) {
3374
+ const live = [];
3375
+ const revoked = [];
3376
+ const unverifiable = [];
3377
+ const retired = [];
3378
+ for (const entry of otherEntries) {
3379
+ const identity = await readIdentity(entry.directory);
3380
+ const tombstone = await readAgentTombstone(entry.directory);
3381
+ const otherAgent = entry.agentId ?? path.basename(entry.directory);
3382
+ const otherUrl = identity?.hosted_mcp_url ?? (identity?.api_url ? `${identity.api_url}/mcp` : void 0);
3383
+ if (!identity?.api_key || !otherUrl) {
3384
+ if (tombstone) retired.push(`${otherAgent} (retired ${tombstone.retired_at})`);
3385
+ else unverifiable.push(`${otherAgent} (no stored key/URL to probe)`);
3386
+ continue;
3387
+ }
3388
+ const suffix = tombstone ? " [tombstoned \u2014 key material still present]" : "";
3389
+ const probe = await (deps.probeHosted ?? probeHostedMcpTools)(identity.api_key, otherUrl, deps.fetch);
3390
+ if (probe.status === "ok") live.push({ label: `${otherAgent}${suffix}`, entry });
3391
+ else if (probe.status === "unauthorized") revoked.push(`${otherAgent}${suffix}`);
3392
+ else unverifiable.push(`${otherAgent} (${probe.status})${suffix}`);
2872
3393
  }
2873
- return status;
3394
+ const parts = [];
3395
+ if (live.length > 0) parts.push(`STILL SPEND-CAPABLE: ${live.map((item) => item.label).join(", ")}`);
3396
+ if (revoked.length > 0) parts.push(`already revoked: ${revoked.join(", ")}`);
3397
+ if (retired.length > 0) parts.push(`tombstoned (keys removed): ${retired.join(", ")}`);
3398
+ if (unverifiable.length > 0) parts.push(`could not verify: ${unverifiable.join(", ")}`);
3399
+ const supersededLive = live.filter((item) => item.entry.classification !== "wired").map((item) => item.label);
3400
+ checks.push({
3401
+ id: "superseded_agents",
3402
+ label: "Superseded agent credentials",
3403
+ ok: supersededLive.length === 0,
3404
+ detail: supersededLive.length > 0 ? `${otherEntries.length} other credential dir(s) found \u2014 ${parts.join("; ")}. A host started before your latest setup keeps authenticating (and spending) as the old agent.` : `${otherEntries.length} other credential dir(s) found \u2014 ${parts.join("; ")}.`,
3405
+ ...supersededLive.length > 0 ? {
3406
+ repair: `Revoke ${supersededLive.join(", ")} on the Haven agent page, then remove the old director(y/ies) under ~/.haven/agents. Connect never revokes or deletes for you.`
3407
+ } : {}
3408
+ });
2874
3409
  }
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.");
2884
- }
2885
- return status;
3410
+ const parkedElsewhere = inventory.filter((entry) => entry.directory !== primaryDirectory && entry.rekeyPending).map((entry) => ({ entry, pending: entry.rekeyPending }));
3411
+ if (parkedElsewhere.length > 0) {
3412
+ const abandoned = parkedElsewhere.filter((item) => item.pending.state !== "pending");
3413
+ const describe = (item) => `${item.entry.slug ?? item.entry.agentId ?? path.basename(item.entry.directory)} (${item.pending.state}, ${item.pending.path})`;
3414
+ checks.push({
3415
+ id: "rekey_pending_elsewhere",
3416
+ label: "Parked re-keys in other credential directories",
3417
+ ok: abandoned.length === 0,
3418
+ detail: abandoned.length > 0 ? `ABANDONED re-key key material outside the agent this report describes: ${abandoned.map(describe).join(", ")}. Each holds a private key that was generated for a re-key nobody finished.` : `${parkedElsewhere.length} other director(y/ies) hold an open pending re-key: ${parkedElsewhere.map(describe).join(", ")}.`,
3419
+ ...abandoned.length > 0 ? {
3420
+ repair: "Check the Haven agent page for each before deleting: if its on-chain revoke already ran, the agent has no spend authority until you re-grant it (#1868), and that is not visible from this machine. Connect never deletes key material for you."
3421
+ } : {}
3422
+ });
2886
3423
  }
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
3424
+ const signerProcess = primaryChecksById.get("signer_process");
3425
+ if (signerProcess) checks.push(signerProcess);
3426
+ const restart = restartRequiredForRuntime(input.runtime, deps.env);
3427
+ checks.push({
3428
+ id: "restart",
3429
+ label: "Runtime restart",
3430
+ ok: true,
3431
+ detail: restart ? "This runtime loads MCP config at startup \u2014 restart it after any repair before expecting the tools to appear." : "No restart requirement known for this runtime."
2943
3432
  });
3433
+ const wiredOk = inventory.filter((entry) => entry.classification === "wired").every((entry) => entry.checks.every((check) => check.ok));
3434
+ return {
3435
+ version: 1,
3436
+ ok: checks.every((check) => check.ok) && wiredOk,
3437
+ runtime: input.runtime,
3438
+ credentialDirectory: primaryDirectory,
3439
+ checks,
3440
+ agents: inventory,
3441
+ ...signerCapabilities ? { signerCapabilities } : {}
3442
+ };
2944
3443
  }
2945
- async function runLocalMcpProbe(runtimeInstall, deps) {
2946
- const probe = deps.probeLocalMcpTools ?? probeLocalMcpTools;
3444
+ async function runRepair(input, deps = {}) {
3445
+ const homeDir = deps.homeDir ?? os.homedir();
3446
+ const messages = [];
3447
+ const { directory, others } = await discoverCredentialDirectory(homeDir, input.credentialsDir);
3448
+ if (others.length > 0) {
3449
+ messages.push(`Note: ${others.length} other agent credential dir(s) exist \u2014 run --doctor for their status.`);
3450
+ }
3451
+ if (!directory) {
3452
+ return {
3453
+ ok: false,
3454
+ messages: [`No agent credentials found to repair \u2014 run the full setup: ${RERUN} --setup <token>.`]
3455
+ };
3456
+ }
3457
+ let identity;
2947
3458
  try {
2948
- return await probe(runtimeInstall.command, runtimeInstall.args, MCP_RUNTIME_MANIFEST.requiredTools);
3459
+ identity = JSON.parse(await promises.readFile(path.join(directory, "identity.json"), "utf8"));
2949
3460
  } catch {
2950
- return { status: "process_error" };
3461
+ return { ok: false, messages: ["identity.json is unreadable \u2014 re-run the full setup with a fresh token."] };
2951
3462
  }
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";
3463
+ if (!identity.api_key || !(identity.hosted_mcp_url || identity.api_url)) {
3464
+ return { ok: false, messages: ["identity.json lacks the stored API key / hosted URL \u2014 re-run the full setup."] };
2956
3465
  }
2957
- return "local_mcp_runtime_install_failed";
3466
+ const configPath = runtimeConfigPathFor(input.runtime, homeDir);
3467
+ if (configPath) {
3468
+ try {
3469
+ const existing = await promises.readFile(configPath, "utf8");
3470
+ if (existing.includes("bin/haven-mcp") || existing.includes(".haven/mcp-runtime")) {
3471
+ return {
3472
+ ok: false,
3473
+ messages: [
3474
+ `The config at ${configPath} is the LOCAL-stdio topology (--local). Repair currently rewrites only the hosted+signer shape and will not touch it.`,
3475
+ "Re-run your original setup command (with --local) to repair a local-stdio install."
3476
+ ]
3477
+ };
3478
+ }
3479
+ } catch {
3480
+ }
3481
+ }
3482
+ const existingSidecar = await readRuntimeSidecar(directory);
3483
+ const serverName = existingSidecar?.server_name;
3484
+ const signerPath = path.join(directory, "signer.json");
3485
+ const prepared = await prepareSignerRuntime(
3486
+ { credentialDirectory: directory, signerPath, homeDir, serverName },
3487
+ { runCommand: deps.runCommand }
3488
+ );
3489
+ messages.push(...prepared.messages);
3490
+ const names = serverNamesFor(serverName);
3491
+ messages.push(`Rewriting MCP entries ${names.hosted} / ${names.signer}${serverName ? ` (agent "${serverName}")` : " (unnamed pair)"} \u2014 no other pair is touched.`);
3492
+ const configResult = await writeRuntimeConfig({
3493
+ runtime: input.runtime,
3494
+ hostedMcpUrl: identity.hosted_mcp_url ?? `${identity.api_url}/mcp`,
3495
+ apiKey: identity.api_key,
3496
+ identityPath: path.join(directory, "identity.json"),
3497
+ signerPath,
3498
+ credentialDirectory: directory,
3499
+ signerCommand: { command: prepared.command, args: prepared.args },
3500
+ homeDir,
3501
+ mode: "hosted",
3502
+ serverName
3503
+ });
3504
+ messages.push(...configResult.messages);
3505
+ messages.push("Repair complete \u2014 restart the runtime, then verify with --doctor.");
3506
+ return { ok: true, messages };
2958
3507
  }
3508
+ var RERUN;
3509
+ var init_doctor = __esm({
3510
+ "src/doctor.ts"() {
3511
+ init_runtime_manifest();
3512
+ init_probes();
3513
+ init_signer_runtime();
3514
+ init_config_writers();
3515
+ init_runtime_registry();
3516
+ init_signer_consent();
3517
+ init_tombstone();
3518
+ init_server_names();
3519
+ init_storage();
3520
+ init_redact();
3521
+ RERUN = "npx @haven_ai/connect@alpha";
3522
+ }
3523
+ });
2959
3524
 
2960
3525
  // src/runtime.ts
3526
+ init_api();
3527
+ init_key();
3528
+ init_redact();
3529
+ init_server_names();
3530
+ init_storage();
3531
+ init_runtime_install();
2961
3532
  init_runtime_registry();
2962
3533
  init_connect_error();
2963
3534
 
@@ -3130,8 +3701,9 @@ function defaultPromptIo() {
3130
3701
  }
3131
3702
 
3132
3703
  // src/runtime.ts
3704
+ init_local_mcp_runtime();
3133
3705
  init_runtime_manifest();
3134
- var CONNECTOR_VERSION = "0.1.29-alpha.0";
3706
+ var CONNECTOR_VERSION = "0.1.30-alpha.0";
3135
3707
  var CONNECT_OUTCOME_SCHEMA_VERSION = 1;
3136
3708
  async function runConnect(options, deps = {}) {
3137
3709
  assertSupportedNodeVersion(deps.nodeVersion, MCP_RUNTIME_MANIFEST.minimumNodeVersion);
@@ -3207,6 +3779,11 @@ async function runConnect(options, deps = {}) {
3207
3779
  proofSignature,
3208
3780
  apiKeyHash: hashAgentApiKey(localApiKey),
3209
3781
  apiKeyPrefix: agentApiKeyPrefix(localApiKey),
3782
+ // #1878: report the pair we are ACTUALLY wiring, bare pair included, so
3783
+ // the dashboard can name it. Derived here rather than sent as the raw
3784
+ // slug — `serverNamesFor` is the one place the naming rule lives, and
3785
+ // the hosted name is what a user pastes into an MCP config.
3786
+ mcpServerName: serverNamesFor(options.serverName).hosted,
3210
3787
  connectorContext: {
3211
3788
  environment_label: options.environmentLabel ?? "Local workspace",
3212
3789
  config_target: installCapabilities.canWriteRuntimeConfig ? "agent runtime MCP config" : "local credential files"
@@ -3610,6 +4187,8 @@ function parseArgs(argv, env = process.env) {
3610
4187
  let json = false;
3611
4188
  let doctor = false;
3612
4189
  let repair = false;
4190
+ let rekeyPhase;
4191
+ let newApiKey;
3613
4192
  let tombstoneDir;
3614
4193
  let tombstoneReason;
3615
4194
  let tombstoneReplacedBy;
@@ -3623,6 +4202,12 @@ function parseArgs(argv, env = process.env) {
3623
4202
  doctor = true;
3624
4203
  } else if (arg === "--repair") {
3625
4204
  repair = true;
4205
+ } else if (arg === "--rekey") {
4206
+ rekeyPhase = "start";
4207
+ } else if (arg === "--rekey-finish") {
4208
+ rekeyPhase = "finish";
4209
+ } else if (arg === "--api-key") {
4210
+ newApiKey = requireValue(argv, ++i, arg);
3626
4211
  } else if (arg === "--tombstone") {
3627
4212
  tombstoneDir = requireValue(argv, ++i, arg);
3628
4213
  } else if (arg === "--reason") {
@@ -3660,20 +4245,38 @@ function parseArgs(argv, env = process.env) {
3660
4245
  }
3661
4246
  }
3662
4247
  const tombstone = tombstoneDir ? { directory: tombstoneDir, reason: tombstoneReason, replacedBy: tombstoneReplacedBy } : void 0;
4248
+ const rekey = rekeyPhase ? { phase: rekeyPhase, newApiKey } : void 0;
3663
4249
  if (help) {
3664
- return { options, help, json, doctor, repair, tombstone };
4250
+ return { options, help, json, doctor, repair, tombstone, rekey };
4251
+ }
4252
+ if (rekey) {
4253
+ if (options.setupToken) {
4254
+ throw new Error("--rekey replaces an existing agent's key; it does not take --setup. Drop one of them.");
4255
+ }
4256
+ if (rekey.phase === "start" && newApiKey !== void 0) {
4257
+ throw new Error(
4258
+ "--api-key belongs to --rekey-finish. --rekey generates the new key here and prints the address to paste into Haven; the API key does not exist yet."
4259
+ );
4260
+ }
4261
+ if (rekey.phase === "finish" && !newApiKey) {
4262
+ throw new Error("--rekey-finish needs --api-key <key> \u2014 the one the Haven agent page showed once.");
4263
+ }
4264
+ return { options, help, json, doctor, repair, tombstone, rekey };
4265
+ }
4266
+ if (newApiKey !== void 0) {
4267
+ throw new Error("--api-key requires --rekey-finish.");
3665
4268
  }
3666
4269
  if (!tombstoneDir && (tombstoneReason !== void 0 || tombstoneReplacedBy !== void 0)) {
3667
4270
  throw new Error("--reason and --replaced-by require --tombstone <dir>.");
3668
4271
  }
3669
4272
  if (tombstone) {
3670
- return { options, help, json, doctor, repair, tombstone };
4273
+ return { options, help, json, doctor, repair, tombstone, rekey };
3671
4274
  }
3672
4275
  if (doctor || repair) {
3673
4276
  if (!options.runtime) {
3674
4277
  throw new Error("--doctor/--repair need --runtime <runtime> (which config to examine).");
3675
4278
  }
3676
- return { options, help, json, doctor, repair, tombstone };
4279
+ return { options, help, json, doctor, repair, tombstone, rekey };
3677
4280
  }
3678
4281
  if (!options.setupToken) {
3679
4282
  throw new Error("Missing --setup <hv_setup_...> setup token.");
@@ -3682,7 +4285,7 @@ function parseArgs(argv, env = process.env) {
3682
4285
  throw new Error("Missing --api <Haven API URL>.");
3683
4286
  }
3684
4287
  options.apiBaseUrl = options.apiBaseUrl.replace(/\/+$/, "");
3685
- return { options, help, json, doctor, repair, tombstone };
4288
+ return { options, help, json, doctor, repair, tombstone, rekey };
3686
4289
  }
3687
4290
  function helpText() {
3688
4291
  return [
@@ -3719,6 +4322,14 @@ function helpText() {
3719
4322
  " --repair Repair, then re-diagnose (implies --doctor): reinstall the pinned signer",
3720
4323
  " runtime, rewrite the wrapper and runtime config from stored credentials.",
3721
4324
  " Hosted topology only (refuses to touch a --local config). No keys, no token.",
4325
+ " --rekey Replace this agent's signing key (no token). Generates a fresh keypair HERE and",
4326
+ " prints its public address to paste into the Haven agent page. Nothing changes",
4327
+ " until you finish; the agent keeps working on its old key throughout.",
4328
+ " Add --name <slug> for a named agent. Refuses a legacy-rail or revoked agent.",
4329
+ " --rekey-finish Second half of --rekey: writes the new key and the API key the agent page",
4330
+ " showed once, in place at the same path, and rewrites only this agent's MCP",
4331
+ " config pair. Server names do not change, so wired hosts need only a restart.",
4332
+ " --api-key <key> The new API key, for --rekey-finish.",
3722
4333
  " --tombstone <dir> Retire an agent credential directory in place (no token): replaces its signer",
3723
4334
  " wrapper with a diagnostic that names the retirement in MCP stderr logs, and",
3724
4335
  " writes TOMBSTONE.json. Touches NO key material and revokes nothing.",
@@ -3764,13 +4375,13 @@ async function runCli(argv, io = {
3764
4375
  }
3765
4376
  if (parsed.tombstone) {
3766
4377
  const { writeAgentTombstone: writeAgentTombstone2 } = await Promise.resolve().then(() => (init_tombstone(), tombstone_exports));
3767
- const { readFile: readFile11 } = await import('fs/promises');
4378
+ const { readFile: readFile12 } = await import('fs/promises');
3768
4379
  const { join: join10 } = await import('path');
3769
4380
  try {
3770
4381
  let agentId = "unknown";
3771
4382
  try {
3772
4383
  const identity = JSON.parse(
3773
- await readFile11(join10(parsed.tombstone.directory, "identity.json"), "utf8")
4384
+ await readFile12(join10(parsed.tombstone.directory, "identity.json"), "utf8")
3774
4385
  );
3775
4386
  agentId = identity.agent_id ?? "unknown";
3776
4387
  } catch {
@@ -3797,6 +4408,64 @@ async function runCli(argv, io = {
3797
4408
  return 0;
3798
4409
  } catch (err) {
3799
4410
  io.stderr(`${redactSecrets(err instanceof Error ? err.message : String(err))}
4411
+ `);
4412
+ return 1;
4413
+ }
4414
+ }
4415
+ if (parsed.rekey) {
4416
+ const { startRekey: startRekey2, finishRekey: finishRekey2 } = await Promise.resolve().then(() => (init_rekey(), rekey_exports));
4417
+ const { restartGuidance: restartGuidance2 } = await Promise.resolve().then(() => (init_rekey_restart(), rekey_restart_exports));
4418
+ const common = {
4419
+ serverName: parsed.options.serverName,
4420
+ credentialsDir: parsed.options.credentialsDir,
4421
+ runtime: parsed.options.runtime
4422
+ };
4423
+ try {
4424
+ if (parsed.rekey.phase === "start") {
4425
+ const result2 = await startRekey2(common);
4426
+ if (parsed.json) {
4427
+ io.stdout(
4428
+ `${redactSecrets(
4429
+ JSON.stringify({
4430
+ rekey: "started",
4431
+ agent_id: result2.agentId,
4432
+ new_delegate_address: result2.newDelegateAddress,
4433
+ expires_at: result2.expiresAt
4434
+ })
4435
+ )}
4436
+ `
4437
+ );
4438
+ } else {
4439
+ for (const line of result2.messages) io.stdout(redactSecrets(`${line}
4440
+ `));
4441
+ }
4442
+ return 0;
4443
+ }
4444
+ const result = await finishRekey2({ ...common, newApiKey: parsed.rekey.newApiKey });
4445
+ const restart = restartGuidance2(parsed.options.runtime);
4446
+ if (parsed.json) {
4447
+ io.stdout(
4448
+ `${redactSecrets(
4449
+ JSON.stringify({
4450
+ rekey: "finished",
4451
+ agent_id: result.agentId,
4452
+ new_delegate_address: result.newDelegateAddress,
4453
+ mcp_servers: result.serverNames,
4454
+ restart_commands: restart.commands
4455
+ })
4456
+ )}
4457
+ `
4458
+ );
4459
+ } else {
4460
+ for (const line of result.messages) io.stdout(redactSecrets(`${line}
4461
+ `));
4462
+ io.stdout("\n");
4463
+ for (const line of restart.lines) io.stdout(redactSecrets(`${line}
4464
+ `));
4465
+ }
4466
+ return 0;
4467
+ } catch (err) {
4468
+ io.stderr(`${redactSecrets(err instanceof Error ? err.message : String(err))}
3800
4469
  `);
3801
4470
  return 1;
3802
4471
  }
@@ -3829,7 +4498,7 @@ async function runCli(argv, io = {
3829
4498
  for (const agent of otherAgents) {
3830
4499
  const name = agent.slug ? `${agent.slug} (${agent.agentId ?? "unknown"})` : agent.agentId ?? "unknown";
3831
4500
  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;
4501
+ const verdict = agent.classification === "wired" ? failed.length === 0 ? "wired, all checks passed" : `wired, ${failed.length} check(s) FAILED` : agent.classification === "parked" ? "parked re-key only \u2014 no identity.json in this directory, but key material is still there" : agent.classification;
3833
4502
  io.stdout(redactSecrets(` ${failed.length > 0 ? "\u2717" : "\u2022"} ${name}: ${verdict}
3834
4503
  `));
3835
4504
  for (const check of failed) {