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

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