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