@haven_ai/connect 0.0.0-dev.202609250737.3bd5a51 → 0.0.0-dev.202609251409.98ed67a
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.cjs +2162 -2148
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +2166 -2152
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +2166 -2152
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +12 -5
- package/dist/index.d.ts +12 -5
- package/dist/index.js +2149 -2133
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/dist/index.cjs
CHANGED
|
@@ -31,10 +31,11 @@ var __export = (target, all) => {
|
|
|
31
31
|
};
|
|
32
32
|
|
|
33
33
|
// src/api.ts
|
|
34
|
-
function createConnectApiClient(baseUrl, fetchImpl = fetch) {
|
|
34
|
+
function createConnectApiClient(baseUrl, fetchImpl = fetch, clientIdentity) {
|
|
35
35
|
const root = baseUrl.replace(/\/+$/, "");
|
|
36
|
+
const send = (url, init) => request(fetchImpl, url, clientIdentity ? { ...init, headers: { ...init.headers, "X-Haven-Client": clientIdentity } } : init);
|
|
36
37
|
return {
|
|
37
|
-
resolveSetup: (input) =>
|
|
38
|
+
resolveSetup: (input) => send(`${root}/agent-connection-setups/resolve`, {
|
|
38
39
|
method: "POST",
|
|
39
40
|
body: JSON.stringify({
|
|
40
41
|
setup_token: input.setupToken,
|
|
@@ -42,7 +43,7 @@ function createConnectApiClient(baseUrl, fetchImpl = fetch) {
|
|
|
42
43
|
runtime: input.runtime
|
|
43
44
|
})
|
|
44
45
|
}),
|
|
45
|
-
registerSetup: (input) =>
|
|
46
|
+
registerSetup: (input) => send(`${root}/agent-connection-setups/register`, {
|
|
46
47
|
method: "POST",
|
|
47
48
|
body: JSON.stringify({
|
|
48
49
|
setup_token: input.setupToken,
|
|
@@ -62,16 +63,16 @@ function createConnectApiClient(baseUrl, fetchImpl = fetch) {
|
|
|
62
63
|
}
|
|
63
64
|
})
|
|
64
65
|
}),
|
|
65
|
-
getAgentIdentity: (apiKey) =>
|
|
66
|
+
getAgentIdentity: (apiKey) => send(`${root}/machine-payments/agent`, {
|
|
66
67
|
method: "GET",
|
|
67
68
|
headers: { Authorization: `Bearer ${apiKey}` }
|
|
68
69
|
}),
|
|
69
|
-
getConnectorStatus: (setupId, apiKey) =>
|
|
70
|
+
getConnectorStatus: (setupId, apiKey) => send(`${root}/agent-connection-setups/${encodeURIComponent(setupId)}/connector-status`, {
|
|
70
71
|
method: "GET",
|
|
71
72
|
headers: { Authorization: `Bearer ${apiKey}` }
|
|
72
73
|
}),
|
|
73
74
|
updateInstallStatus: async (setupId, apiKey, input) => {
|
|
74
|
-
await
|
|
75
|
+
await send(`${root}/agent-connection-setups/${encodeURIComponent(setupId)}/install-status`, {
|
|
75
76
|
method: "POST",
|
|
76
77
|
headers: { Authorization: `Bearer ${apiKey}` },
|
|
77
78
|
body: JSON.stringify({
|
|
@@ -618,9 +619,9 @@ var init_runtime_manifest = __esm({
|
|
|
618
619
|
mcpPackage: "@haven_ai/mcp",
|
|
619
620
|
mcpVersion: mcp.MCP_VERSION,
|
|
620
621
|
sdkPackage: "@haven_ai/sdk",
|
|
621
|
-
sdkVersion: "0.0.0-dev.
|
|
622
|
+
sdkVersion: "0.0.0-dev.202609251409.98ed67a",
|
|
622
623
|
signerPackage: "@haven_ai/signer",
|
|
623
|
-
signerVersion: "0.0.0-dev.
|
|
624
|
+
signerVersion: "0.0.0-dev.202609251409.98ed67a",
|
|
624
625
|
// Sourced from the SDK, never a literal (#1161). This field read '20.0.0'
|
|
625
626
|
// while every package's `engines` said `>=24` and the docs said `>=24.0.0`,
|
|
626
627
|
// so the guard that was supposed to enforce the floor waved Node v23 through
|
|
@@ -2995,6 +2996,185 @@ var init_runtime_install = __esm({
|
|
|
2995
2996
|
execFileAsync3 = util.promisify(child_process.execFile);
|
|
2996
2997
|
}
|
|
2997
2998
|
});
|
|
2999
|
+
function installedClientTargets(homeDir = os.homedir(), cwd = process.cwd(), env = process.env) {
|
|
3000
|
+
const targets = [
|
|
3001
|
+
{
|
|
3002
|
+
runtime: "claude-code",
|
|
3003
|
+
label: "Claude Code",
|
|
3004
|
+
// Claude Code is configured through its own CLI (`claude mcp add-json`),
|
|
3005
|
+
// not by writing a file this module owns — so its evidence is the
|
|
3006
|
+
// client directory, never a config path.
|
|
3007
|
+
configPath: null,
|
|
3008
|
+
markers: [path.join(homeDir, ".claude"), path.join(homeDir, ".claude.json")]
|
|
3009
|
+
},
|
|
3010
|
+
{
|
|
3011
|
+
runtime: "codex-cli",
|
|
3012
|
+
// Both Codex surfaces write the same ~/.codex/config.toml, so they are
|
|
3013
|
+
// ONE candidate. Splitting them would ask the user to answer a question
|
|
3014
|
+
// whose answers are the same write.
|
|
3015
|
+
label: "Codex (CLI or Desktop)",
|
|
3016
|
+
configPath: runtimeConfigPathFor("codex-cli", homeDir),
|
|
3017
|
+
markers: [path.join(homeDir, ".codex")]
|
|
3018
|
+
},
|
|
3019
|
+
{
|
|
3020
|
+
runtime: "cursor",
|
|
3021
|
+
label: "Cursor",
|
|
3022
|
+
configPath: runtimeConfigPathFor("cursor", homeDir),
|
|
3023
|
+
markers: [path.join(homeDir, ".cursor")]
|
|
3024
|
+
},
|
|
3025
|
+
{
|
|
3026
|
+
runtime: "vscode",
|
|
3027
|
+
label: "VS Code",
|
|
3028
|
+
configPath: runtimeConfigPathFor("vscode", homeDir),
|
|
3029
|
+
markers: [path.resolve(cwd, ".vscode")]
|
|
3030
|
+
},
|
|
3031
|
+
{
|
|
3032
|
+
runtime: "vscode-insiders",
|
|
3033
|
+
label: "VS Code Insiders",
|
|
3034
|
+
configPath: runtimeConfigPathFor("vscode-insiders", homeDir),
|
|
3035
|
+
markers: []
|
|
3036
|
+
},
|
|
3037
|
+
{
|
|
3038
|
+
runtime: "claude-desktop",
|
|
3039
|
+
label: "Claude Desktop",
|
|
3040
|
+
configPath: runtimeConfigPathFor("claude-desktop", homeDir),
|
|
3041
|
+
markers: []
|
|
3042
|
+
},
|
|
3043
|
+
{
|
|
3044
|
+
runtime: "hermes",
|
|
3045
|
+
label: "Hermes Agent",
|
|
3046
|
+
configPath: runtimeConfigPathFor("hermes", homeDir),
|
|
3047
|
+
markers: [env.HERMES_HOME ?? path.join(homeDir, ".hermes")]
|
|
3048
|
+
}
|
|
3049
|
+
];
|
|
3050
|
+
return targets.filter((target) => runtimeProfile(target.runtime, {}).canWriteRuntimeConfig);
|
|
3051
|
+
}
|
|
3052
|
+
async function scanInstalledClients(options = {}) {
|
|
3053
|
+
const exists = options.exists ?? pathExists;
|
|
3054
|
+
const targets = installedClientTargets(options.homeDir, options.cwd, options.env ?? process.env);
|
|
3055
|
+
const found = [];
|
|
3056
|
+
for (const target of targets) {
|
|
3057
|
+
if (target.configPath && await exists(target.configPath)) {
|
|
3058
|
+
found.push({
|
|
3059
|
+
runtime: target.runtime,
|
|
3060
|
+
label: target.label,
|
|
3061
|
+
detail: `MCP config found at ${target.configPath}`,
|
|
3062
|
+
configPath: target.configPath,
|
|
3063
|
+
evidence: "config-file"
|
|
3064
|
+
});
|
|
3065
|
+
continue;
|
|
3066
|
+
}
|
|
3067
|
+
for (const marker of target.markers) {
|
|
3068
|
+
if (!await exists(marker)) continue;
|
|
3069
|
+
found.push({
|
|
3070
|
+
runtime: target.runtime,
|
|
3071
|
+
label: target.label,
|
|
3072
|
+
detail: `installed (${marker})`,
|
|
3073
|
+
configPath: target.configPath,
|
|
3074
|
+
evidence: "client-directory"
|
|
3075
|
+
});
|
|
3076
|
+
break;
|
|
3077
|
+
}
|
|
3078
|
+
}
|
|
3079
|
+
return found.sort((a, b) => {
|
|
3080
|
+
if (a.evidence !== b.evidence) return a.evidence === "config-file" ? -1 : 1;
|
|
3081
|
+
return SCAN_ORDER.indexOf(a.runtime) - SCAN_ORDER.indexOf(b.runtime);
|
|
3082
|
+
});
|
|
3083
|
+
}
|
|
3084
|
+
function installedClientHint(candidates) {
|
|
3085
|
+
const installedClients = candidates.map((candidate) => candidate.runtime);
|
|
3086
|
+
if (candidates.length === 1) {
|
|
3087
|
+
return { installedClients, suggestedRuntime: candidates[0].runtime };
|
|
3088
|
+
}
|
|
3089
|
+
const configured = candidates.filter((candidate) => candidate.evidence === "config-file");
|
|
3090
|
+
return configured.length === 1 ? { installedClients, suggestedRuntime: configured[0].runtime } : { installedClients };
|
|
3091
|
+
}
|
|
3092
|
+
async function promptForInstalledClient(candidates, io = defaultPromptIo()) {
|
|
3093
|
+
if (candidates.length === 0) throw noInstalledClientsError();
|
|
3094
|
+
io.write("Haven could not detect which agent runtime this is.\n");
|
|
3095
|
+
io.write("These agent clients are installed on this machine:\n");
|
|
3096
|
+
candidates.forEach((candidate, index) => {
|
|
3097
|
+
io.write(` ${index + 1}) ${candidate.label} \u2014 ${candidate.detail}
|
|
3098
|
+
`);
|
|
3099
|
+
});
|
|
3100
|
+
io.write("Haven writes an API key and a signing key into the client you pick, so pick the one your agent actually runs in.\n");
|
|
3101
|
+
for (let attempt = 0; attempt < MAX_PROMPT_ATTEMPTS; attempt += 1) {
|
|
3102
|
+
const answer = await io.question(`Which one? [1-${candidates.length}] (default 1 \u2014 ${candidates[0].label}): `);
|
|
3103
|
+
if (answer === null) throw promptAbortedError("the prompt was cancelled");
|
|
3104
|
+
const trimmed = answer.trim();
|
|
3105
|
+
if (trimmed === "") return candidates[0].runtime;
|
|
3106
|
+
const picked = Number.parseInt(trimmed, 10);
|
|
3107
|
+
if (Number.isInteger(picked) && picked >= 1 && picked <= candidates.length) {
|
|
3108
|
+
return candidates[picked - 1].runtime;
|
|
3109
|
+
}
|
|
3110
|
+
io.write(`"${trimmed}" is not one of 1-${candidates.length}.
|
|
3111
|
+
`);
|
|
3112
|
+
}
|
|
3113
|
+
throw promptAbortedError(`no valid choice after ${MAX_PROMPT_ATTEMPTS} attempts`);
|
|
3114
|
+
}
|
|
3115
|
+
async function resolveRuntimeByInstalledClientPrompt(options = {}) {
|
|
3116
|
+
const candidates = await scanInstalledClients(options);
|
|
3117
|
+
if (candidates.length === 0) throw noInstalledClientsError();
|
|
3118
|
+
return promptForInstalledClient(candidates, options.io ?? defaultPromptIo());
|
|
3119
|
+
}
|
|
3120
|
+
function noInstalledClientsError() {
|
|
3121
|
+
return new exports.ConnectError(
|
|
3122
|
+
"runtime_no_installed_clients",
|
|
3123
|
+
"Could not determine the agent runtime: nothing was detected in this environment, and no agent client Haven can configure is installed on this machine. Re-run with --runtime <name> naming the client you want configured, or --runtime other to store credentials and finish the MCP setup by hand.",
|
|
3124
|
+
"rerun_connect_with_explicit_runtime"
|
|
3125
|
+
);
|
|
3126
|
+
}
|
|
3127
|
+
function promptAbortedError(reason) {
|
|
3128
|
+
return new exports.ConnectError(
|
|
3129
|
+
"runtime_prompt_aborted",
|
|
3130
|
+
`Runtime not chosen (${reason}). Nothing was written: no agent was created, no credentials were stored, and the Haven setup token is still unused. Run the connector command again, or pass --runtime <name> to skip the prompt.`,
|
|
3131
|
+
"rerun_connect_and_choose_a_runtime"
|
|
3132
|
+
);
|
|
3133
|
+
}
|
|
3134
|
+
async function pathExists(path) {
|
|
3135
|
+
try {
|
|
3136
|
+
await promises.access(path);
|
|
3137
|
+
return true;
|
|
3138
|
+
} catch {
|
|
3139
|
+
return false;
|
|
3140
|
+
}
|
|
3141
|
+
}
|
|
3142
|
+
function defaultPromptIo() {
|
|
3143
|
+
return {
|
|
3144
|
+
write: (text) => process.stdout.write(text),
|
|
3145
|
+
question: (query) => new Promise((resolvePromise) => {
|
|
3146
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
3147
|
+
let settled = false;
|
|
3148
|
+
const settle = (value) => {
|
|
3149
|
+
if (settled) return;
|
|
3150
|
+
settled = true;
|
|
3151
|
+
rl.close();
|
|
3152
|
+
resolvePromise(value);
|
|
3153
|
+
};
|
|
3154
|
+
rl.once("SIGINT", () => settle(null));
|
|
3155
|
+
rl.once("close", () => settle(null));
|
|
3156
|
+
rl.question(query, (answer) => settle(answer));
|
|
3157
|
+
})
|
|
3158
|
+
};
|
|
3159
|
+
}
|
|
3160
|
+
var SCAN_ORDER, MAX_PROMPT_ATTEMPTS;
|
|
3161
|
+
var init_installed_clients = __esm({
|
|
3162
|
+
"src/installed-clients.ts"() {
|
|
3163
|
+
init_connect_error();
|
|
3164
|
+
init_config_writers();
|
|
3165
|
+
init_runtime_registry();
|
|
3166
|
+
SCAN_ORDER = [
|
|
3167
|
+
"claude-code",
|
|
3168
|
+
"codex-cli",
|
|
3169
|
+
"cursor",
|
|
3170
|
+
"vscode",
|
|
3171
|
+
"vscode-insiders",
|
|
3172
|
+
"claude-desktop",
|
|
3173
|
+
"hermes"
|
|
3174
|
+
];
|
|
3175
|
+
MAX_PROMPT_ATTEMPTS = 3;
|
|
3176
|
+
}
|
|
3177
|
+
});
|
|
2998
3178
|
|
|
2999
3179
|
// src/tombstone.ts
|
|
3000
3180
|
var tombstone_exports = {};
|
|
@@ -3127,49 +3307,160 @@ var init_tombstone = __esm({
|
|
|
3127
3307
|
TOMBSTONE_MARKER = "HAVEN-TOMBSTONE";
|
|
3128
3308
|
}
|
|
3129
3309
|
});
|
|
3130
|
-
|
|
3131
|
-
|
|
3132
|
-
|
|
3133
|
-
|
|
3134
|
-
|
|
3135
|
-
|
|
3136
|
-
|
|
3137
|
-
|
|
3138
|
-
|
|
3139
|
-
|
|
3140
|
-
|
|
3141
|
-
|
|
3142
|
-
|
|
3143
|
-
|
|
3144
|
-
|
|
3145
|
-
|
|
3146
|
-
|
|
3147
|
-
|
|
3148
|
-
|
|
3149
|
-
|
|
3310
|
+
async function detectWiringCollision(input) {
|
|
3311
|
+
const root = defaultCredentialRoot(input.credentialsDir);
|
|
3312
|
+
let entries = [];
|
|
3313
|
+
try {
|
|
3314
|
+
entries = await promises.readdir(root);
|
|
3315
|
+
} catch {
|
|
3316
|
+
return null;
|
|
3317
|
+
}
|
|
3318
|
+
const superseded = [];
|
|
3319
|
+
const taken = /* @__PURE__ */ new Set();
|
|
3320
|
+
for (const entry of entries) {
|
|
3321
|
+
const directory = path.join(root, entry);
|
|
3322
|
+
let identityRaw;
|
|
3323
|
+
try {
|
|
3324
|
+
identityRaw = await promises.readFile(path.join(directory, "identity.json"), "utf8");
|
|
3325
|
+
} catch {
|
|
3326
|
+
continue;
|
|
3327
|
+
}
|
|
3328
|
+
taken.add(entry);
|
|
3329
|
+
let identity;
|
|
3330
|
+
try {
|
|
3331
|
+
identity = JSON.parse(identityRaw);
|
|
3332
|
+
} catch {
|
|
3333
|
+
identity = void 0;
|
|
3334
|
+
}
|
|
3335
|
+
if (!identity?.api_key) continue;
|
|
3336
|
+
if (await pathExists2(path.join(directory, TOMBSTONE_FILENAME))) continue;
|
|
3337
|
+
const sidecar = await readRuntimeSidecar(directory);
|
|
3338
|
+
if (sidecar?.server_name) continue;
|
|
3339
|
+
superseded.push({ directory, agentId: identity.agent_id ?? entry });
|
|
3150
3340
|
}
|
|
3341
|
+
if (superseded.length === 0) return null;
|
|
3342
|
+
return {
|
|
3343
|
+
superseded,
|
|
3344
|
+
suggestedServerName: proposeServerSlug(input.agentName, taken)
|
|
3345
|
+
};
|
|
3151
3346
|
}
|
|
3152
|
-
function
|
|
3153
|
-
|
|
3154
|
-
if (!
|
|
3155
|
-
|
|
3156
|
-
|
|
3157
|
-
|
|
3158
|
-
|
|
3347
|
+
function proposeServerSlug(agentName, taken) {
|
|
3348
|
+
let base = agentName.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").replace(/-{2,}/g, "-").slice(0, 32).replace(/-+$/g, "");
|
|
3349
|
+
if (!slugIsValid(base)) base = "agent";
|
|
3350
|
+
if (!taken.has(base)) return base;
|
|
3351
|
+
for (let n = 2; n < 1e3; n += 1) {
|
|
3352
|
+
const suffix = `-${n}`;
|
|
3353
|
+
const candidate = `${base.slice(0, 32 - suffix.length).replace(/-+$/g, "")}${suffix}`;
|
|
3354
|
+
if (slugIsValid(candidate) && !taken.has(candidate)) return candidate;
|
|
3159
3355
|
}
|
|
3160
|
-
|
|
3356
|
+
throw new Error(`Could not propose an unused server name for ${JSON.stringify(agentName)}.`);
|
|
3161
3357
|
}
|
|
3162
|
-
|
|
3358
|
+
function slugIsValid(slug) {
|
|
3163
3359
|
try {
|
|
3164
|
-
|
|
3360
|
+
assertValidServerSlug(slug);
|
|
3361
|
+
return true;
|
|
3165
3362
|
} catch {
|
|
3166
|
-
return
|
|
3363
|
+
return false;
|
|
3167
3364
|
}
|
|
3168
3365
|
}
|
|
3169
|
-
async function
|
|
3170
|
-
const
|
|
3171
|
-
|
|
3172
|
-
|
|
3366
|
+
async function promptWiringCollisionResolution(collision, agentName, io) {
|
|
3367
|
+
const ids = collision.superseded.map((entry) => entry.agentId).join(", ");
|
|
3368
|
+
io.write(`This machine is already wired to a Haven agent with a live key: ${ids}.
|
|
3369
|
+
`);
|
|
3370
|
+
io.write(`Setting up "${agentName}" on the bare haven / haven-signer pair would replace that wiring.
|
|
3371
|
+
`);
|
|
3372
|
+
io.write(" r) replace \u2014 re-point haven / haven-signer at the new agent and retire the previous directory locally\n");
|
|
3373
|
+
io.write(" (tombstoned, local key files removed; you still revoke it on the Haven agent page)\n");
|
|
3374
|
+
io.write(` a) alongside \u2014 install as a named agent (suggested: ${collision.suggestedServerName}) with its own
|
|
3375
|
+
`);
|
|
3376
|
+
io.write(` haven-<name> / haven-signer-<name> pair, leaving the current wiring untouched
|
|
3377
|
+
`);
|
|
3378
|
+
io.write(" q) quit \u2014 nothing is written and the setup token stays unused\n");
|
|
3379
|
+
for (let attempt = 0; attempt < MAX_PROMPT_ATTEMPTS2; attempt += 1) {
|
|
3380
|
+
const answer = await io.question("Replace, install alongside, or quit? [r/a/q]: ");
|
|
3381
|
+
if (answer === null) return { action: "abort" };
|
|
3382
|
+
const trimmed = answer.trim().toLowerCase();
|
|
3383
|
+
if (trimmed === "r" || trimmed === "replace") return { action: "replace" };
|
|
3384
|
+
if (trimmed === "q" || trimmed === "quit") return { action: "abort" };
|
|
3385
|
+
if (trimmed === "a" || trimmed === "alongside") {
|
|
3386
|
+
const typed = await io.question(`Server name [${collision.suggestedServerName}]: `);
|
|
3387
|
+
if (typed === null) return { action: "abort" };
|
|
3388
|
+
const serverName = typed.trim() === "" ? collision.suggestedServerName : typed.trim();
|
|
3389
|
+
try {
|
|
3390
|
+
assertValidServerSlug(serverName);
|
|
3391
|
+
} catch (err) {
|
|
3392
|
+
io.write(`${err instanceof Error ? err.message : String(err)}
|
|
3393
|
+
`);
|
|
3394
|
+
continue;
|
|
3395
|
+
}
|
|
3396
|
+
return { action: "alongside", serverName };
|
|
3397
|
+
}
|
|
3398
|
+
io.write(`"${trimmed}" is not one of r, a, q.
|
|
3399
|
+
`);
|
|
3400
|
+
}
|
|
3401
|
+
return { action: "abort" };
|
|
3402
|
+
}
|
|
3403
|
+
async function pathExists2(path) {
|
|
3404
|
+
try {
|
|
3405
|
+
await promises.stat(path);
|
|
3406
|
+
return true;
|
|
3407
|
+
} catch {
|
|
3408
|
+
return false;
|
|
3409
|
+
}
|
|
3410
|
+
}
|
|
3411
|
+
var MAX_PROMPT_ATTEMPTS2;
|
|
3412
|
+
var init_wiring_collision = __esm({
|
|
3413
|
+
"src/wiring-collision.ts"() {
|
|
3414
|
+
init_server_names();
|
|
3415
|
+
init_signer_runtime();
|
|
3416
|
+
init_storage();
|
|
3417
|
+
init_tombstone();
|
|
3418
|
+
MAX_PROMPT_ATTEMPTS2 = 3;
|
|
3419
|
+
}
|
|
3420
|
+
});
|
|
3421
|
+
|
|
3422
|
+
// src/unwire.ts
|
|
3423
|
+
var unwire_exports = {};
|
|
3424
|
+
__export(unwire_exports, {
|
|
3425
|
+
readIdentityFile: () => readIdentityFile,
|
|
3426
|
+
teardownLocalKeyMaterial: () => teardownLocalKeyMaterial,
|
|
3427
|
+
tombstoneDirectoryIfAbsent: () => tombstoneDirectoryIfAbsent,
|
|
3428
|
+
unwireAgent: () => unwireAgent
|
|
3429
|
+
});
|
|
3430
|
+
function identityAt(directory) {
|
|
3431
|
+
return promises.readFile(path.join(directory, "identity.json"), "utf8").then((raw) => JSON.parse(raw)).catch(() => null);
|
|
3432
|
+
}
|
|
3433
|
+
function removeForModel(text, model, names, path) {
|
|
3434
|
+
switch (model.kind) {
|
|
3435
|
+
case "yaml":
|
|
3436
|
+
return removeHermesYaml(text, names, path);
|
|
3437
|
+
case "toml":
|
|
3438
|
+
return removeCodexToml(text, names);
|
|
3439
|
+
case "json":
|
|
3440
|
+
return removeJsonMcpConfig(text, model.serverRoot ?? "mcpServers", names, path);
|
|
3441
|
+
}
|
|
3442
|
+
}
|
|
3443
|
+
function envLineValue(envText, envKey) {
|
|
3444
|
+
const line = envText.split(/\r?\n/).find((candidate) => new RegExp(`^\\s*(?:export[ \\t]+)?${envKey}[ \\t]*=`).test(candidate));
|
|
3445
|
+
if (!line) return void 0;
|
|
3446
|
+
let value = line.slice(line.indexOf("=") + 1);
|
|
3447
|
+
value = value.trim();
|
|
3448
|
+
if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
|
|
3449
|
+
value = value.slice(1, -1);
|
|
3450
|
+
}
|
|
3451
|
+
return value;
|
|
3452
|
+
}
|
|
3453
|
+
async function readOptionalText(path) {
|
|
3454
|
+
try {
|
|
3455
|
+
return await promises.readFile(path, "utf8");
|
|
3456
|
+
} catch {
|
|
3457
|
+
return null;
|
|
3458
|
+
}
|
|
3459
|
+
}
|
|
3460
|
+
async function unwireAgent(input) {
|
|
3461
|
+
const homeDir = input.homeDir ?? os.homedir();
|
|
3462
|
+
const [identity, sidecar] = await Promise.all([identityAt(input.directory), readRuntimeSidecar(input.directory)]);
|
|
3463
|
+
const agentId = identity?.agent_id ?? "unknown";
|
|
3173
3464
|
const slug = input.slug ?? sidecar?.server_name;
|
|
3174
3465
|
const names = serverNamesFor(slug);
|
|
3175
3466
|
const runtimes = [];
|
|
@@ -3359,2300 +3650,2022 @@ var init_unwire = __esm({
|
|
|
3359
3650
|
DESTROY_FLAG = "--destroy-key-material";
|
|
3360
3651
|
}
|
|
3361
3652
|
});
|
|
3362
|
-
|
|
3363
|
-
|
|
3364
|
-
|
|
3365
|
-
|
|
3366
|
-
"src/rekey-messages.ts"() {
|
|
3367
|
-
REKEY_FINISH_NEEDS_API_KEY = "--rekey-finish needs --api-key <key> \u2014 the one the Haven agent page showed once.";
|
|
3653
|
+
function failureOutcomeFor(runtimeHint, error) {
|
|
3654
|
+
if (error !== null && typeof error === "object") {
|
|
3655
|
+
const recorded = failureOutcomesByError.get(error);
|
|
3656
|
+
if (recorded) return recorded;
|
|
3368
3657
|
}
|
|
3369
|
-
|
|
3370
|
-
|
|
3371
|
-
// src/prune-runtimes.ts
|
|
3372
|
-
var prune_runtimes_exports = {};
|
|
3373
|
-
__export(prune_runtimes_exports, {
|
|
3374
|
-
normalizeRuntimePath: () => normalizeRuntimePath,
|
|
3375
|
-
pruneSignerRuntimes: () => pruneSignerRuntimes,
|
|
3376
|
-
referencedRuntimeDirectories: () => referencedRuntimeDirectories,
|
|
3377
|
-
rollUpPruneLevel: () => rollUpPruneLevel,
|
|
3378
|
-
signerRuntimeRoot: () => signerRuntimeRoot
|
|
3379
|
-
});
|
|
3380
|
-
function signerRuntimeRoot(homeDir) {
|
|
3381
|
-
return path.join(homeDir, ".haven", "signer-runtime");
|
|
3382
|
-
}
|
|
3383
|
-
function classifyKey(key) {
|
|
3384
|
-
if (key.startsWith("override-")) return "override";
|
|
3385
|
-
if (key === exports.MCP_RUNTIME_MANIFEST.signerVersion || /^\d+\.\d+\.\d+/.test(key)) return "version";
|
|
3386
|
-
return "unknown";
|
|
3658
|
+
return failedConnectOutcome(runtimeHint, error);
|
|
3387
3659
|
}
|
|
3388
|
-
async function
|
|
3389
|
-
|
|
3390
|
-
|
|
3391
|
-
|
|
3392
|
-
|
|
3393
|
-
|
|
3394
|
-
|
|
3395
|
-
|
|
3396
|
-
|
|
3397
|
-
|
|
3398
|
-
const path$1 = path.join(dir, entry.name);
|
|
3399
|
-
if (entry.isDirectory()) await walk(path$1);
|
|
3400
|
-
else if (entry.isFile()) {
|
|
3401
|
-
try {
|
|
3402
|
-
total += (await promises.stat(path$1)).size;
|
|
3403
|
-
} catch {
|
|
3404
|
-
}
|
|
3405
|
-
}
|
|
3406
|
-
}
|
|
3407
|
-
};
|
|
3408
|
-
await walk(directory);
|
|
3409
|
-
return total;
|
|
3660
|
+
async function runConnect(options, deps = {}) {
|
|
3661
|
+
const trace = {};
|
|
3662
|
+
try {
|
|
3663
|
+
return await executeConnect(options, deps, trace);
|
|
3664
|
+
} catch (err) {
|
|
3665
|
+
const outcome = failedConnectOutcome(trace.runtime ?? options.runtime, err);
|
|
3666
|
+
if (err !== null && typeof err === "object") failureOutcomesByError.set(err, outcome);
|
|
3667
|
+
if (trace.directory) await recordConnectOutcome(deps, trace.directory, outcome);
|
|
3668
|
+
throw err;
|
|
3669
|
+
}
|
|
3410
3670
|
}
|
|
3411
|
-
async function
|
|
3412
|
-
const resolved = path.resolve(path$1).replace(/[\\/]+$/, "");
|
|
3671
|
+
async function recordConnectOutcome(deps, directory, outcome) {
|
|
3413
3672
|
try {
|
|
3414
|
-
return await
|
|
3673
|
+
return await (deps.writeOutcomeRecord ?? writeConnectOutcomeRecord)(directory, outcome);
|
|
3415
3674
|
} catch {
|
|
3416
|
-
return
|
|
3675
|
+
return void 0;
|
|
3417
3676
|
}
|
|
3418
3677
|
}
|
|
3419
|
-
function
|
|
3420
|
-
|
|
3421
|
-
|
|
3422
|
-
|
|
3423
|
-
const
|
|
3424
|
-
|
|
3425
|
-
|
|
3426
|
-
|
|
3427
|
-
|
|
3428
|
-
const
|
|
3429
|
-
const
|
|
3430
|
-
|
|
3431
|
-
|
|
3432
|
-
|
|
3433
|
-
|
|
3434
|
-
|
|
3435
|
-
|
|
3436
|
-
|
|
3437
|
-
|
|
3438
|
-
|
|
3439
|
-
|
|
3440
|
-
|
|
3441
|
-
|
|
3442
|
-
|
|
3443
|
-
|
|
3444
|
-
|
|
3445
|
-
|
|
3446
|
-
|
|
3447
|
-
|
|
3448
|
-
|
|
3449
|
-
|
|
3450
|
-
|
|
3451
|
-
|
|
3452
|
-
|
|
3453
|
-
|
|
3454
|
-
|
|
3455
|
-
}
|
|
3678
|
+
async function executeConnect(options, deps, trace) {
|
|
3679
|
+
assertSupportedNodeVersion(deps.nodeVersion, exports.MCP_RUNTIME_MANIFEST.minimumNodeVersion);
|
|
3680
|
+
const connectorVersion = options.connectorVersion ?? exports.CONNECTOR_VERSION;
|
|
3681
|
+
const api = deps.api ?? createConnectApiClient(options.apiBaseUrl, void 0, CONNECTOR_CLIENT_IDENTITY);
|
|
3682
|
+
const log = secureLogger(
|
|
3683
|
+
deps.log ?? ((message) => process.stdout.write(`${message}
|
|
3684
|
+
`)),
|
|
3685
|
+
deps.redactPaths === true
|
|
3686
|
+
);
|
|
3687
|
+
const writeCredentials = deps.writeCredentials ?? writeCredentialFiles;
|
|
3688
|
+
const preflightStorage = deps.preflightStorage ?? preflightCredentialStorage;
|
|
3689
|
+
const runRuntimeInstall = deps.installRuntime ?? installRuntime;
|
|
3690
|
+
const generateKey = deps.generateKey ?? generateDelegateKey;
|
|
3691
|
+
const generateLocalApiKey = deps.generateApiKey ?? generateAgentApiKey;
|
|
3692
|
+
const selection = await resolveRuntimeSelection(options.runtime, options.runtimeForce, {
|
|
3693
|
+
env: deps.env ?? process.env,
|
|
3694
|
+
selfReported: options.runtimeSelfReport,
|
|
3695
|
+
promptForRuntime: runtimeSelectionPrompt(options, deps)
|
|
3696
|
+
});
|
|
3697
|
+
if (!selection.runtime) {
|
|
3698
|
+
const hint = await installedClientHintFor(deps);
|
|
3699
|
+
throw new exports.ConnectError(
|
|
3700
|
+
"runtime_undetermined",
|
|
3701
|
+
`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: ${exports.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. ` + installedClientProse(hint) + "Nothing was written and the Haven setup token is still unused.",
|
|
3702
|
+
"rerun_connect_with_explicit_runtime",
|
|
3703
|
+
// #2091: the values must ride structurally too. The backend's setup
|
|
3704
|
+
// prompt permits a retry only with "one of the values that refusal
|
|
3705
|
+
// lists" — and --json discards prose, so a prose-only list deadlocked
|
|
3706
|
+
// every automation run in an undetected runtime (Codex in the field:
|
|
3707
|
+
// npx needs network, Codex runs network commands unsandboxed, and the
|
|
3708
|
+
// unsandboxed path carries none of the CODEX_* detection vars).
|
|
3709
|
+
//
|
|
3710
|
+
// #2174: the list alone still leaves the retry a nine-value guess. The
|
|
3711
|
+
// scan below narrows it to what is actually on this machine — as a
|
|
3712
|
+
// HINT. It does not select, and this stays a refusal: see
|
|
3713
|
+
// `installedClientHint`.
|
|
3714
|
+
{ allowedRuntimes: RUNTIME_FLAG_VALUE_LIST, ...hint }
|
|
3715
|
+
);
|
|
3716
|
+
}
|
|
3717
|
+
const runtime = selection.runtime;
|
|
3718
|
+
trace.runtime = runtime;
|
|
3719
|
+
const installCapabilities = runtimeInstallCapabilities(runtime);
|
|
3720
|
+
if (options.localMcp) {
|
|
3721
|
+
if (!supportsLocalMcp(runtime)) {
|
|
3722
|
+
throw new Error(
|
|
3723
|
+
`--local (fully-local Haven MCP) is only available for Claude Code and Codex. The detected runtime is ${runtimeProfile(runtime).label}. Re-run without --local to use the default hosted MCP + local signer setup.`
|
|
3724
|
+
);
|
|
3456
3725
|
}
|
|
3457
3726
|
}
|
|
3458
|
-
|
|
3459
|
-
}
|
|
3460
|
-
function rollUpPruneLevel(entries) {
|
|
3461
|
-
if (entries.some((e) => e.level === "failed")) return "failed";
|
|
3462
|
-
if (entries.some((e) => e.level === "advisory")) return "advisory";
|
|
3463
|
-
return "ok";
|
|
3464
|
-
}
|
|
3465
|
-
async function pruneSignerRuntimes(input, deps = {}) {
|
|
3466
|
-
const homeDir = deps.homeDir ?? os.homedir();
|
|
3467
|
-
const root = signerRuntimeRoot(homeDir);
|
|
3468
|
-
const measure = input.measure ?? true;
|
|
3469
|
-
const referenced = await referencedRuntimeDirectories(homeDir, deps.credentialsDir);
|
|
3470
|
-
const pin = await normalizeRuntimePath(path.join(root, exports.MCP_RUNTIME_MANIFEST.signerVersion));
|
|
3471
|
-
const remove = deps.rm ?? (async (directory) => promises.rm(directory, { recursive: true, force: false }));
|
|
3472
|
-
const entries = [];
|
|
3473
|
-
let keys = [];
|
|
3474
|
-
try {
|
|
3475
|
-
keys = (await promises.readdir(root, { withFileTypes: true })).filter((d) => d.isDirectory()).map((d) => d.name).sort();
|
|
3476
|
-
} catch {
|
|
3477
|
-
return { version: 1, root, dryRun: input.dryRun, entries, removed: 0, reclaimedBytes: 0, level: "ok" };
|
|
3727
|
+
if (selection.overrodeHint) {
|
|
3728
|
+
log(`runtime: ${runtime} (detected; ignoring the ${selection.overrodeHint} hint \u2014 pass --runtime-force ${selection.overrodeHint} to override)`);
|
|
3478
3729
|
}
|
|
3479
|
-
|
|
3480
|
-
|
|
3481
|
-
for (const key of keys) {
|
|
3482
|
-
const directory = path.join(root, key);
|
|
3483
|
-
const normalized = await normalizeRuntimePath(directory);
|
|
3484
|
-
const referencedBy = referenced.get(normalized) ?? [];
|
|
3485
|
-
const kind = classifyKey(key);
|
|
3486
|
-
if (referencedBy.length > 0 || normalized === pin) {
|
|
3487
|
-
entries.push({
|
|
3488
|
-
directory,
|
|
3489
|
-
key,
|
|
3490
|
-
kind,
|
|
3491
|
-
bytes: 0,
|
|
3492
|
-
referencedBy,
|
|
3493
|
-
action: "kept",
|
|
3494
|
-
level: "ok",
|
|
3495
|
-
detail: referencedBy.length > 0 ? `kept \u2014 named by ${referencedBy.length} credential director${referencedBy.length === 1 ? "y" : "ies"} (sidecar or wrapper)` : "kept \u2014 the connector's current pinned version (what --repair installs)"
|
|
3496
|
-
});
|
|
3497
|
-
continue;
|
|
3498
|
-
}
|
|
3499
|
-
const bytes = measure ? await directoryBytes(directory) : 0;
|
|
3500
|
-
if (input.dryRun) {
|
|
3501
|
-
entries.push({
|
|
3502
|
-
directory,
|
|
3503
|
-
key,
|
|
3504
|
-
kind,
|
|
3505
|
-
bytes,
|
|
3506
|
-
referencedBy,
|
|
3507
|
-
action: "would_remove",
|
|
3508
|
-
level: "advisory",
|
|
3509
|
-
detail: `would remove \u2014 no credential directory names it (${kind}-keyed)`
|
|
3510
|
-
});
|
|
3511
|
-
continue;
|
|
3512
|
-
}
|
|
3513
|
-
try {
|
|
3514
|
-
await remove(directory);
|
|
3515
|
-
removed += 1;
|
|
3516
|
-
reclaimedBytes += bytes;
|
|
3517
|
-
entries.push({ directory, key, kind, bytes, referencedBy, action: "removed", level: "ok", detail: `removed \u2014 no credential directory named it (${kind}-keyed)` });
|
|
3518
|
-
} catch (err) {
|
|
3519
|
-
entries.push({
|
|
3520
|
-
directory,
|
|
3521
|
-
key,
|
|
3522
|
-
kind,
|
|
3523
|
-
bytes,
|
|
3524
|
-
referencedBy,
|
|
3525
|
-
action: "failed",
|
|
3526
|
-
level: "failed",
|
|
3527
|
-
detail: `removal failed: ${err instanceof Error ? err.message : String(err)} \u2014 a signer process may still hold it open; stop it and re-run`
|
|
3528
|
-
});
|
|
3529
|
-
}
|
|
3730
|
+
if (selection.discardedHint) {
|
|
3731
|
+
log(`runtime: ${runtime} (detected; "${selection.discardedHint}" is not a runtime Haven knows \u2014 valid values: ${exports.RUNTIME_FLAG_VALUES})`);
|
|
3530
3732
|
}
|
|
3531
|
-
|
|
3532
|
-
}
|
|
3533
|
-
var init_prune_runtimes = __esm({
|
|
3534
|
-
"src/prune-runtimes.ts"() {
|
|
3535
|
-
init_runtime_manifest();
|
|
3733
|
+
if (selection.source === "prompted") {
|
|
3734
|
+
log(`runtime: ${runtime} (chosen at the prompt \u2014 nothing was detected in this environment)`);
|
|
3536
3735
|
}
|
|
3537
|
-
|
|
3538
|
-
|
|
3539
|
-
|
|
3540
|
-
|
|
3541
|
-
|
|
3542
|
-
|
|
3543
|
-
|
|
3544
|
-
});
|
|
3545
|
-
|
|
3546
|
-
|
|
3547
|
-
const stored = await readStoredCredentials(
|
|
3548
|
-
options.serverName,
|
|
3549
|
-
options.agentId,
|
|
3550
|
-
options.credentialsDir
|
|
3551
|
-
);
|
|
3552
|
-
const api = (deps.createApi ?? ((url) => createConnectApiClient(url)))(stored.apiUrl);
|
|
3553
|
-
const identity = await probeIdentity(api, stored.apiKey, "current");
|
|
3554
|
-
assertRekeyable(identity, stored);
|
|
3555
|
-
const key = (deps.generateKey ?? generateDelegateKey)();
|
|
3556
|
-
const startedAt = new Date(now()).toISOString();
|
|
3557
|
-
const expiresAt = new Date(now() + REKEY_PENDING_TTL_MS).toISOString();
|
|
3558
|
-
await writeRekeyPending(stored.directory, {
|
|
3559
|
-
agent_id: stored.agentId,
|
|
3560
|
-
new_delegate_address: key.address,
|
|
3561
|
-
new_delegate_key: key.privateKey,
|
|
3562
|
-
started_at: startedAt,
|
|
3563
|
-
expires_at: expiresAt
|
|
3564
|
-
});
|
|
3565
|
-
const finishCommand = [
|
|
3566
|
-
sdk.connectorRerunCommand("--rekey-finish"),
|
|
3567
|
-
options.serverName ? `--name ${options.serverName}` : void 0,
|
|
3568
|
-
"--api-key <the key the dashboard showed you>",
|
|
3569
|
-
options.runtime ? `--runtime ${options.runtime}` : "--runtime <your runtime>"
|
|
3570
|
-
].filter(Boolean).join(" ");
|
|
3571
|
-
return {
|
|
3572
|
-
started: true,
|
|
3573
|
-
agentId: stored.agentId,
|
|
3574
|
-
directory: stored.directory,
|
|
3575
|
-
newDelegateAddress: key.address,
|
|
3576
|
-
expiresAt,
|
|
3577
|
-
messages: [
|
|
3578
|
-
`New signing key generated on this machine for agent ${identity.name || stored.agentId}.`,
|
|
3579
|
-
"",
|
|
3580
|
-
` New signing address: ${key.address}`,
|
|
3581
|
-
"",
|
|
3582
|
-
"The private half stays here \u2014 Haven never receives it, and there is no way to move it",
|
|
3583
|
-
"between machines. That is what keeps the account non-custodial.",
|
|
3584
|
-
"",
|
|
3585
|
-
'Next, on the Haven agent page: choose "Replace signing key" and paste that address.',
|
|
3586
|
-
"When it finishes it shows a new API key ONCE. Come back here and run:",
|
|
3587
|
-
"",
|
|
3588
|
-
` ${finishCommand}`,
|
|
3589
|
-
"",
|
|
3590
|
-
`Nothing has changed yet \u2014 the agent keeps working on its old key until you finish.`,
|
|
3591
|
-
`This pending re-key expires ${expiresAt}.`
|
|
3592
|
-
]
|
|
3593
|
-
};
|
|
3594
|
-
}
|
|
3595
|
-
async function finishRekey(options, deps = {}) {
|
|
3596
|
-
const now = deps.now ?? (() => Date.now());
|
|
3597
|
-
if (!options.newApiKey) {
|
|
3598
|
-
throw new Error(REKEY_FINISH_NEEDS_API_KEY);
|
|
3736
|
+
log("Warming up your connection to Haven\u2026");
|
|
3737
|
+
let setup;
|
|
3738
|
+
try {
|
|
3739
|
+
setup = await api.resolveSetup({
|
|
3740
|
+
setupToken: options.setupToken,
|
|
3741
|
+
connectorVersion,
|
|
3742
|
+
runtime
|
|
3743
|
+
});
|
|
3744
|
+
} catch (err) {
|
|
3745
|
+
throw deadSetupTokenError(err) ?? err;
|
|
3599
3746
|
}
|
|
3600
|
-
|
|
3601
|
-
|
|
3602
|
-
|
|
3603
|
-
|
|
3604
|
-
|
|
3605
|
-
|
|
3606
|
-
if (pending.agent_id !== stored.agentId) {
|
|
3607
|
-
throw new Error(
|
|
3608
|
-
`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.`
|
|
3609
|
-
);
|
|
3747
|
+
assertSetupChallengeIsUsable(setup.challenge.expires_at);
|
|
3748
|
+
printSetupSummary(setup, log);
|
|
3749
|
+
await preflightStorage({ baseDir: options.credentialsDir, warn: log });
|
|
3750
|
+
if (options.serverName) {
|
|
3751
|
+
assertValidServerSlug(options.serverName);
|
|
3752
|
+
await assertServerSlugAvailable(options.serverName, options.credentialsDir);
|
|
3610
3753
|
}
|
|
3611
|
-
|
|
3612
|
-
|
|
3613
|
-
|
|
3614
|
-
|
|
3615
|
-
|
|
3754
|
+
log("Checked local credential storage \u2014 all clear.");
|
|
3755
|
+
let serverName = options.serverName;
|
|
3756
|
+
let replacing;
|
|
3757
|
+
if (!serverName) {
|
|
3758
|
+
const collision = await detectWiringCollision({
|
|
3759
|
+
credentialsDir: options.credentialsDir,
|
|
3760
|
+
agentName: setup.agent.name
|
|
3761
|
+
});
|
|
3762
|
+
if (collision) {
|
|
3763
|
+
const resolution = await resolveWiringCollision(collision, setup.agent.name, options, deps);
|
|
3764
|
+
if (resolution.action === "replace") {
|
|
3765
|
+
replacing = collision;
|
|
3766
|
+
log(
|
|
3767
|
+
`Replacing the existing haven / haven-signer wiring (previous agent(s): ${supersededIds(collision)}). The previous directory is retired locally once the new wiring is written; nothing is revoked.`
|
|
3768
|
+
);
|
|
3769
|
+
} else {
|
|
3770
|
+
serverName = resolution.serverName;
|
|
3771
|
+
assertValidServerSlug(serverName);
|
|
3772
|
+
await assertServerSlugAvailable(serverName, options.credentialsDir);
|
|
3773
|
+
log(`Installing alongside the existing wiring as a named agent: ${serverNamesFor(serverName).hosted} / ${serverNamesFor(serverName).signer}.`);
|
|
3774
|
+
}
|
|
3775
|
+
}
|
|
3776
|
+
}
|
|
3777
|
+
const existingAgents = await listExistingKeyedAgents(options.credentialsDir);
|
|
3778
|
+
if (existingAgents.length > 0) {
|
|
3779
|
+
log("");
|
|
3780
|
+
log(
|
|
3781
|
+
`Heads-up (before anything is written to this machine): it already carries ${existingAgents.length} agent director${existingAgents.length === 1 ? "y" : "ies"} with stored keys \u2014 ` + existingAgents.map((a) => `${a.agentId}${a.accountAddress ? ` (spends from ${shortAddress(a.accountAddress)})` : ""}`).join(", ") + ". This setup creates a NEW agent alongside them and revokes nothing."
|
|
3616
3782
|
);
|
|
3617
3783
|
}
|
|
3618
|
-
const
|
|
3619
|
-
|
|
3620
|
-
|
|
3621
|
-
|
|
3622
|
-
|
|
3784
|
+
const hostedNameForRun = serverNamesFor(serverName).hosted;
|
|
3785
|
+
let reboundFrom;
|
|
3786
|
+
const holders = (await listMcpServerBindings(options.credentialsDir)).filter(({ binding }) => binding.server_name === hostedNameForRun).sort((a, b) => a.binding.bound_at < b.binding.bound_at ? 1 : a.binding.bound_at > b.binding.bound_at ? -1 : 0);
|
|
3787
|
+
const newest = holders[0];
|
|
3788
|
+
if (newest) {
|
|
3789
|
+
const { binding, directory } = newest;
|
|
3790
|
+
const backendChanged = withoutUserinfo(binding.api_url) !== withoutUserinfo(options.apiBaseUrl);
|
|
3791
|
+
const previousApiUrl = withoutUserinfo(binding.api_url);
|
|
3792
|
+
reboundFrom = { server_name: binding.server_name, agent_id: binding.agent_id, api_url: previousApiUrl, bound_at: binding.bound_at, backend_changed: backendChanged };
|
|
3793
|
+
const beingReplaced = replacing?.superseded.some((entry) => entry.directory === directory) ?? false;
|
|
3794
|
+
log(
|
|
3795
|
+
`Heads-up: the MCP server name '${binding.server_name}' was bound to agent ${binding.agent_id} on ${previousApiUrl} at ${binding.bound_at} (locally recorded${holders.length > 1 ? `; ${holders.length - 1} older record${holders.length > 2 ? "s" : ""} also claim${holders.length > 2 ? "" : "s"} it` : ""}). ` + (beingReplaced ? `This run replaces that wiring, as you chose, with a new agent on ${withoutUserinfo(options.apiBaseUrl)}` : `This run rebinds it to a new agent on ${withoutUserinfo(options.apiBaseUrl)}`) + (backendChanged ? " \u2014 a DIFFERENT backend: any saved session, script or document naming this MCP server now resolves to a different backend and agent." : ".")
|
|
3623
3796
|
);
|
|
3624
3797
|
}
|
|
3625
|
-
|
|
3798
|
+
const localKey = generateKey();
|
|
3799
|
+
const localApiKey = generateLocalApiKey();
|
|
3800
|
+
log("Minting a fresh signing key and API key \u2014 both stay on this machine.");
|
|
3801
|
+
const proofSignature = await localKey.signChallenge(setup.challenge.message);
|
|
3802
|
+
log("Introducing your agent to Haven\u2026");
|
|
3803
|
+
let registration;
|
|
3804
|
+
try {
|
|
3805
|
+
registration = await api.registerSetup({
|
|
3806
|
+
setupToken: options.setupToken,
|
|
3807
|
+
connectorVersion,
|
|
3808
|
+
runtime,
|
|
3809
|
+
challengeId: setup.challenge.id,
|
|
3810
|
+
delegateAddress: localKey.address,
|
|
3811
|
+
proofSignature,
|
|
3812
|
+
apiKeyHash: hashAgentApiKey(localApiKey),
|
|
3813
|
+
apiKeyPrefix: agentApiKeyPrefix(localApiKey),
|
|
3814
|
+
// #1878: report the pair we are ACTUALLY wiring, bare pair included, so
|
|
3815
|
+
// the dashboard can name it. Derived here rather than sent as the raw
|
|
3816
|
+
// slug — `serverNamesFor` is the one place the naming rule lives, and
|
|
3817
|
+
// the hosted name is what a user pastes into an MCP config.
|
|
3818
|
+
mcpServerName: serverNamesFor(serverName).hosted,
|
|
3819
|
+
// #2528: 'prose' is the default because it is what a caller who says
|
|
3820
|
+
// nothing is doing — the library entry point is not a --json run.
|
|
3821
|
+
runMode: options.runMode ?? "prose",
|
|
3822
|
+
connectorContext: {
|
|
3823
|
+
environment_label: options.environmentLabel ?? "Local workspace",
|
|
3824
|
+
config_target: installCapabilities.canWriteRuntimeConfig ? "agent runtime MCP config" : "local credential files"
|
|
3825
|
+
},
|
|
3826
|
+
installCapabilities
|
|
3827
|
+
});
|
|
3828
|
+
} catch (err) {
|
|
3829
|
+
const dead = deadSetupTokenError(err);
|
|
3830
|
+
if (dead) throw dead;
|
|
3831
|
+
if (isExpiredSetupChallenge(err)) {
|
|
3832
|
+
throw new Error(
|
|
3833
|
+
"The Haven setup challenge expired while connecting. Return to Haven, start a fresh connection, and run its new connector command. Do not reuse or paste credentials."
|
|
3834
|
+
);
|
|
3835
|
+
}
|
|
3836
|
+
throw err;
|
|
3837
|
+
}
|
|
3838
|
+
log(`Registered signing address with Haven: ${shortAddress(registration.delegate_address)}.`);
|
|
3839
|
+
log("Tucking your credentials away safely on disk\u2026");
|
|
3840
|
+
const credentialPaths = await writeCredentials({
|
|
3626
3841
|
baseDir: options.credentialsDir,
|
|
3627
|
-
agentId:
|
|
3628
|
-
serverName
|
|
3629
|
-
apiKey:
|
|
3630
|
-
delegateKey:
|
|
3631
|
-
delegateAddress:
|
|
3632
|
-
|
|
3633
|
-
|
|
3634
|
-
|
|
3635
|
-
|
|
3636
|
-
|
|
3637
|
-
|
|
3638
|
-
|
|
3639
|
-
|
|
3640
|
-
|
|
3641
|
-
|
|
3642
|
-
|
|
3842
|
+
agentId: registration.agent_id,
|
|
3843
|
+
serverName,
|
|
3844
|
+
apiKey: localApiKey,
|
|
3845
|
+
delegateKey: localKey.privateKey,
|
|
3846
|
+
delegateAddress: localKey.address,
|
|
3847
|
+
accountAddress: setup.haven_wallet.address,
|
|
3848
|
+
chainId: setup.haven_wallet.chain_id,
|
|
3849
|
+
network: setup.haven_wallet.network,
|
|
3850
|
+
agentBudget: setup.agent_budget.map((budget) => ({
|
|
3851
|
+
token_symbol: budget.token_symbol,
|
|
3852
|
+
allowance_amount: budget.allowance_amount,
|
|
3853
|
+
reset_period_min: budget.reset_period_min
|
|
3854
|
+
})),
|
|
3855
|
+
apiUrl: options.apiBaseUrl,
|
|
3856
|
+
hostedMcpUrl: registration.hosted_mcp_url,
|
|
3857
|
+
x402BindingSigner: setup.x402_binding_signer ?? void 0,
|
|
3858
|
+
warn: log
|
|
3643
3859
|
});
|
|
3644
|
-
|
|
3645
|
-
|
|
3646
|
-
|
|
3647
|
-
|
|
3648
|
-
|
|
3649
|
-
|
|
3650
|
-
|
|
3651
|
-
|
|
3652
|
-
|
|
3653
|
-
|
|
3654
|
-
|
|
3655
|
-
|
|
3656
|
-
|
|
3657
|
-
|
|
3658
|
-
|
|
3659
|
-
|
|
3660
|
-
|
|
3661
|
-
|
|
3662
|
-
|
|
3663
|
-
|
|
3664
|
-
|
|
3665
|
-
|
|
3666
|
-
|
|
3667
|
-
|
|
3668
|
-
identityPath: `${stored.directory}/identity.json`,
|
|
3669
|
-
signerPath: `${stored.directory}/signer.json`,
|
|
3670
|
-
credentialDirectory: stored.directory,
|
|
3671
|
-
serverName: options.serverName
|
|
3672
|
-
},
|
|
3673
|
-
{ command: prepared.command, args: prepared.args }
|
|
3860
|
+
trace.directory = credentialPaths.directory;
|
|
3861
|
+
try {
|
|
3862
|
+
const bindingRecord = {
|
|
3863
|
+
version: 1,
|
|
3864
|
+
server_name: hostedNameForRun,
|
|
3865
|
+
signer_name: serverNamesFor(serverName).signer,
|
|
3866
|
+
agent_id: registration.agent_id,
|
|
3867
|
+
api_url: withoutUserinfo(options.apiBaseUrl),
|
|
3868
|
+
// never persist `user:pass@` (#3154 doc review r2)
|
|
3869
|
+
...registration.hosted_mcp_url ? { hosted_mcp_url: registration.hosted_mcp_url } : {},
|
|
3870
|
+
bound_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
3871
|
+
};
|
|
3872
|
+
await writeMcpServerBinding(credentialPaths.directory, bindingRecord);
|
|
3873
|
+
} catch {
|
|
3874
|
+
log("Could not record the MCP server-name binding locally (non-fatal; the next setup cannot see this binding).");
|
|
3875
|
+
}
|
|
3876
|
+
log(`Stored Haven identity credential locally: ${credentialPaths.identityPath}`);
|
|
3877
|
+
log(`Stored local signer credential locally: ${credentialPaths.signerPath}`);
|
|
3878
|
+
log(`Stored non-secret agent orientation locally: ${credentialPaths.agentPath}`);
|
|
3879
|
+
if (setup.x402_binding_signer) {
|
|
3880
|
+
log("Configured x402 binding signer for the local signer.");
|
|
3881
|
+
} else {
|
|
3882
|
+
log(
|
|
3883
|
+
"Warning: Haven did not provide an x402 binding signer, so x402 payments will not sign until HAVEN_X402_BINDING_SIGNER is set for the signer. Non-x402 payments are unaffected."
|
|
3674
3884
|
);
|
|
3675
|
-
|
|
3676
|
-
|
|
3677
|
-
|
|
3678
|
-
|
|
3679
|
-
|
|
3885
|
+
}
|
|
3886
|
+
const runtimeInstall = await runRuntimeInstall({
|
|
3887
|
+
runtime,
|
|
3888
|
+
hostedMcpUrl: registration.hosted_mcp_url,
|
|
3889
|
+
apiKey: localApiKey,
|
|
3890
|
+
signerPath: credentialPaths.signerPath,
|
|
3891
|
+
identityPath: credentialPaths.identityPath,
|
|
3892
|
+
credentialDirectory: credentialPaths.directory,
|
|
3893
|
+
environmentLabel: options.environmentLabel ?? "Local workspace",
|
|
3894
|
+
ackSigner: options.ackSigner,
|
|
3895
|
+
ackLocalTools: options.ackLocalTools,
|
|
3896
|
+
localMcp: options.localMcp,
|
|
3897
|
+
serverName
|
|
3898
|
+
}, {
|
|
3899
|
+
onProgress: log,
|
|
3900
|
+
// #1543: report "runtime configured" the moment the config write settles,
|
|
3901
|
+
// so the dashboard can expose its budget-approval controls without
|
|
3902
|
+
// waiting on the probes and skill install — a tail that approval does not
|
|
3903
|
+
// depend on. Silent and best-effort: the complete report below remains
|
|
3904
|
+
// authoritative (it overwrites these keys, adding the probe verdicts and
|
|
3905
|
+
// skill state), so an early failure costs nothing but the head start.
|
|
3906
|
+
onRuntimeConfigured: async (early) => {
|
|
3907
|
+
try {
|
|
3908
|
+
await api.updateInstallStatus(registration.setup_id, localApiKey, {
|
|
3909
|
+
runtime: early.runtime,
|
|
3910
|
+
connectorVersion,
|
|
3911
|
+
runtimeMcpMode: early.runtimeMcpMode,
|
|
3912
|
+
hostedMcpConfigured: early.hostedMcpConfigured,
|
|
3913
|
+
localSignerConfigured: early.localSignerConfigured,
|
|
3914
|
+
localMcpConfigured: early.localMcpConfigured,
|
|
3915
|
+
credentialFilesWritten: true,
|
|
3916
|
+
signerAcknowledged: early.signerAcknowledged,
|
|
3917
|
+
localMcpAcknowledged: early.localMcpAcknowledged,
|
|
3918
|
+
restartRequired: early.restartRequired,
|
|
3919
|
+
nextUserAction: early.nextUserAction,
|
|
3920
|
+
errorCode: early.errorCode ?? null,
|
|
3921
|
+
environmentLabel: options.environmentLabel ?? "Local workspace"
|
|
3922
|
+
});
|
|
3923
|
+
if (!early.errorCode || early.errorCode === "manual_runtime_setup_required") {
|
|
3924
|
+
log(approveBudgetCta(setup, registration.approval_url));
|
|
3925
|
+
}
|
|
3926
|
+
} catch {
|
|
3927
|
+
}
|
|
3680
3928
|
}
|
|
3681
|
-
|
|
3682
|
-
|
|
3683
|
-
|
|
3684
|
-
|
|
3685
|
-
|
|
3686
|
-
|
|
3687
|
-
|
|
3688
|
-
|
|
3929
|
+
});
|
|
3930
|
+
printRuntimeInstall(runtimeInstall, log);
|
|
3931
|
+
if (runtimeInstall.errorCode) {
|
|
3932
|
+
log("Haven setup needs a couple more steps on this machine \u2014 see the notes above.");
|
|
3933
|
+
} else {
|
|
3934
|
+
log("Haven setup on this machine is complete.");
|
|
3935
|
+
}
|
|
3936
|
+
let supersededAgentsRetiredLocally;
|
|
3937
|
+
const retiredAgentIds = [];
|
|
3938
|
+
const retirementMirrorErrors = {};
|
|
3939
|
+
if (replacing) {
|
|
3940
|
+
if (runtimeInstall.errorCode) {
|
|
3941
|
+
supersededAgentsRetiredLocally = false;
|
|
3942
|
+
log(
|
|
3943
|
+
`Previous agent(s) ${supersededIds(replacing)} were NOT retired: the runtime install did not complete, so their wiring may still be the only working one. Resolve the install, then retire them with ${RERUN_HINT} --unwire <dir>.`
|
|
3689
3944
|
);
|
|
3945
|
+
} else {
|
|
3946
|
+
supersededAgentsRetiredLocally = true;
|
|
3947
|
+
for (const entry of replacing.superseded) {
|
|
3948
|
+
try {
|
|
3949
|
+
const { mirrorError } = await tombstoneDirectoryIfAbsent({
|
|
3950
|
+
directory: entry.directory,
|
|
3951
|
+
agentId: entry.agentId,
|
|
3952
|
+
reason: "replaced by a new setup (--replace)",
|
|
3953
|
+
replacedBy: registration.agent_id,
|
|
3954
|
+
// #3251: the ledger follows this run's credential root (default
|
|
3955
|
+
// root → ~/.haven/tombstones, as before; any other → <root>/.tombstones).
|
|
3956
|
+
tombstonesDir: tombstonesDirForCredentialRoot(options.credentialsDir)
|
|
3957
|
+
});
|
|
3958
|
+
if (mirrorError !== void 0) {
|
|
3959
|
+
retirementMirrorErrors[entry.agentId] = mirrorError;
|
|
3960
|
+
log(
|
|
3961
|
+
`Warning: the surviving tombstone record for ${entry.agentId} could not be written to ${tombstonesDirForCredentialRoot(options.credentialsDir)} (${mirrorError}). The in-place TOMBSTONE.json stands; --doctor will not list this retirement once the directory is deleted.`
|
|
3962
|
+
);
|
|
3963
|
+
}
|
|
3964
|
+
await teardownLocalKeyMaterial(entry.directory, await readIdentityFile(entry.directory));
|
|
3965
|
+
await clearMcpServerBinding(entry.directory);
|
|
3966
|
+
retiredAgentIds.push(entry.agentId);
|
|
3967
|
+
log(`Retired previous agent ${entry.agentId} locally: tombstoned, local key files removed.`);
|
|
3968
|
+
} catch (err) {
|
|
3969
|
+
supersededAgentsRetiredLocally = false;
|
|
3970
|
+
log(`Could not retire previous agent ${entry.agentId} locally: ${err instanceof Error ? err.message : String(err)}`);
|
|
3971
|
+
}
|
|
3972
|
+
}
|
|
3690
3973
|
}
|
|
3691
|
-
} else {
|
|
3692
|
-
messages.push(
|
|
3693
|
-
"",
|
|
3694
|
-
"NOTE: no --runtime was given, so the MCP config still carries the OLD API key and every",
|
|
3695
|
-
"wired host will fail with 401. Re-run with --runtime <name> to rewrite it."
|
|
3696
|
-
);
|
|
3697
3974
|
}
|
|
3698
|
-
|
|
3699
|
-
|
|
3700
|
-
agentId: stored.agentId,
|
|
3701
|
-
directory: stored.directory,
|
|
3702
|
-
newDelegateAddress: pending.new_delegate_address,
|
|
3703
|
-
serverNames: { hosted: names.hosted, signer: names.signer },
|
|
3704
|
-
configRewritten,
|
|
3705
|
-
messages
|
|
3706
|
-
};
|
|
3707
|
-
}
|
|
3708
|
-
async function probeIdentity(api, apiKey, which) {
|
|
3975
|
+
let supersededScan = null;
|
|
3976
|
+
let supersededAgentIds = [];
|
|
3709
3977
|
try {
|
|
3710
|
-
|
|
3711
|
-
|
|
3712
|
-
|
|
3713
|
-
|
|
3714
|
-
|
|
3715
|
-
|
|
3978
|
+
supersededScan = await listOtherAgentIds(options.credentialsDir, credentialPaths.directory);
|
|
3979
|
+
supersededAgentIds = supersededScan ?? [];
|
|
3980
|
+
if (supersededAgentsRetiredLocally === true) {
|
|
3981
|
+
log("");
|
|
3982
|
+
log(
|
|
3983
|
+
`Replaced: previous agent(s) ${supersededIds(replacing)} are retired on this machine but NOT revoked \u2014 revoke them on the Haven agent page, then restart EVERY long-lived host (gateways, TUI workers, editors): each holds the MCP wiring snapshot from its own start time, and the tombstone speaks only when a stale host next probes the old path.`
|
|
3984
|
+
);
|
|
3985
|
+
} else if (supersededAgentIds.length > 0) {
|
|
3986
|
+
log("");
|
|
3987
|
+
log(
|
|
3988
|
+
`Heads-up: this setup created a NEW agent. Your previous agent(s) \u2014 ${supersededAgentIds.join(", ")} \u2014 still exist with their own keys, and any host that was already running keeps acting as them.`
|
|
3989
|
+
);
|
|
3990
|
+
log(
|
|
3991
|
+
`If you meant to replace them: revoke them on the Haven agent page, then restart EVERY long-lived host (gateways, TUI workers, editors) \u2014 each holds the MCP wiring snapshot from its own start time, so after repeated setups each can be stuck on a DIFFERENT old agent. Then remove their directories under ~/.haven/agents (or ${RERUN_HINT} --tombstone <dir> to leave a diagnostic in their place). Run ${RERUN_HINT} --doctor to check whether their keys are still live.`
|
|
3716
3992
|
);
|
|
3717
3993
|
}
|
|
3718
|
-
|
|
3719
|
-
`Could not reach Haven to check this agent (${redactSecrets(
|
|
3720
|
-
err instanceof Error ? err.message : String(err)
|
|
3721
|
-
)}). Nothing was changed.`
|
|
3722
|
-
);
|
|
3994
|
+
} catch {
|
|
3723
3995
|
}
|
|
3724
|
-
|
|
3725
|
-
|
|
3726
|
-
|
|
3727
|
-
|
|
3728
|
-
|
|
3729
|
-
|
|
3996
|
+
try {
|
|
3997
|
+
await api.updateInstallStatus(registration.setup_id, localApiKey, {
|
|
3998
|
+
runtime: runtimeInstall.runtime,
|
|
3999
|
+
connectorVersion,
|
|
4000
|
+
runtimeMcpMode: runtimeInstall.runtimeMcpMode,
|
|
4001
|
+
hostedMcpConfigured: runtimeInstall.hostedMcpConfigured,
|
|
4002
|
+
localSignerConfigured: runtimeInstall.localSignerConfigured,
|
|
4003
|
+
localMcpConfigured: runtimeInstall.localMcpConfigured,
|
|
4004
|
+
credentialFilesWritten: true,
|
|
4005
|
+
signerAcknowledged: runtimeInstall.signerAcknowledged,
|
|
4006
|
+
localMcpAcknowledged: runtimeInstall.localMcpAcknowledged,
|
|
4007
|
+
activationCommandAvailable: Boolean(runtimeInstall.activationCommand),
|
|
4008
|
+
skillInstalled: runtimeInstall.skillInstalled,
|
|
4009
|
+
probeResult: runtimeInstall.probeResult,
|
|
4010
|
+
restartRequired: runtimeInstall.restartRequired,
|
|
4011
|
+
nextUserAction: runtimeInstall.nextUserAction,
|
|
4012
|
+
errorCode: runtimeInstall.errorCode,
|
|
4013
|
+
environmentLabel: options.environmentLabel ?? "Local workspace",
|
|
4014
|
+
// The raw scan result, `null` and all — NOT the flattened
|
|
4015
|
+
// `supersededAgentIds` the outcome carries. Flattening here would hand
|
|
4016
|
+
// the dashboard the same ambiguity this field exists to remove (#2561).
|
|
4017
|
+
supersededAgentIds: supersededScan
|
|
4018
|
+
});
|
|
4019
|
+
} catch (err) {
|
|
4020
|
+
log(`Could not report install status to Haven: ${err instanceof Error ? err.message : String(err)}`);
|
|
3730
4021
|
}
|
|
3731
|
-
|
|
3732
|
-
|
|
3733
|
-
|
|
3734
|
-
);
|
|
4022
|
+
let approval;
|
|
4023
|
+
const narrateApprovalWait = options.waitForApproval === true || options.waitForApproval === void 0 && (deps.isStdoutTty ?? Boolean(process.stdout.isTTY));
|
|
4024
|
+
if (narrateApprovalWait && !runtimeInstall.errorCode) {
|
|
4025
|
+
approval = await waitForBudgetApproval(api, registration.setup_id, localApiKey, log, options.approvalWait);
|
|
3735
4026
|
}
|
|
3736
|
-
|
|
3737
|
-
|
|
3738
|
-
|
|
3739
|
-
|
|
4027
|
+
printNextSteps(runtimeInstall, log, approval, registration.approval_url);
|
|
4028
|
+
const outcome = completionOutcome({
|
|
4029
|
+
runtimeInstall,
|
|
4030
|
+
delegateAddress: registration.delegate_address,
|
|
4031
|
+
hostedMcpUrl: registration.hosted_mcp_url,
|
|
4032
|
+
supersededAgentIds,
|
|
4033
|
+
supersededAgentsRetiredLocally,
|
|
4034
|
+
...replacing ? { retiredAgentIds } : {},
|
|
4035
|
+
...Object.keys(retirementMirrorErrors).length > 0 ? { retirementMirrorErrors } : {},
|
|
4036
|
+
existingAgentsBeforeWrite: existingAgents.map((a) => ({ agent_id: a.agentId, account_address: a.accountAddress })),
|
|
4037
|
+
...reboundFrom ? { serverNameReboundFrom: reboundFrom } : {},
|
|
4038
|
+
setupChallengeExpiresAt: setup.challenge.expires_at,
|
|
4039
|
+
approvalRequired: registration.agent_status === "pending_approval",
|
|
4040
|
+
approvalUrl: registration.approval_url
|
|
4041
|
+
});
|
|
4042
|
+
if (await recordConnectOutcome(deps, credentialPaths.directory, outcome)) {
|
|
4043
|
+
log(`Saved this run's outcome to ${exports.CONNECT_OUTCOME_FILENAME} in the agent's credential directory.`);
|
|
3740
4044
|
}
|
|
4045
|
+
return {
|
|
4046
|
+
setupId: registration.setup_id,
|
|
4047
|
+
agentId: registration.agent_id,
|
|
4048
|
+
delegateAddress: registration.delegate_address,
|
|
4049
|
+
credentialPaths,
|
|
4050
|
+
outcome
|
|
4051
|
+
};
|
|
3741
4052
|
}
|
|
3742
|
-
|
|
3743
|
-
|
|
3744
|
-
|
|
3745
|
-
|
|
3746
|
-
|
|
3747
|
-
|
|
3748
|
-
|
|
3749
|
-
|
|
3750
|
-
|
|
3751
|
-
|
|
3752
|
-
|
|
3753
|
-
|
|
3754
|
-
|
|
3755
|
-
|
|
3756
|
-
|
|
3757
|
-
|
|
3758
|
-
|
|
3759
|
-
|
|
3760
|
-
}
|
|
3761
|
-
|
|
3762
|
-
|
|
3763
|
-
|
|
3764
|
-
|
|
3765
|
-
|
|
3766
|
-
|
|
3767
|
-
|
|
3768
|
-
|
|
3769
|
-
|
|
3770
|
-
|
|
3771
|
-
|
|
3772
|
-
|
|
3773
|
-
|
|
3774
|
-
|
|
3775
|
-
|
|
4053
|
+
function completionOutcome(input) {
|
|
4054
|
+
const { runtimeInstall } = input;
|
|
4055
|
+
const manualSetup = runtimeInstall.errorCode === "manual_runtime_setup_required";
|
|
4056
|
+
const nextAction2 = runtimeInstall.nextUserAction;
|
|
4057
|
+
const outcome = {
|
|
4058
|
+
schema_version: exports.CONNECT_OUTCOME_SCHEMA_VERSION,
|
|
4059
|
+
outcome: runtimeInstall.errorCode ? "action_required" : "complete",
|
|
4060
|
+
runtime: runtimeInstall.runtime,
|
|
4061
|
+
topology: runtimeInstall.runtimeMcpMode,
|
|
4062
|
+
configuration: {
|
|
4063
|
+
hosted_mcp: runtimeInstall.hostedMcpConfigured,
|
|
4064
|
+
local_signer: runtimeInstall.localSignerConfigured,
|
|
4065
|
+
local_mcp: runtimeInstall.localMcpConfigured
|
|
4066
|
+
},
|
|
4067
|
+
probe: { result: runtimeInstall.probeResult },
|
|
4068
|
+
activation: {
|
|
4069
|
+
restart_required: runtimeInstall.restartRequired,
|
|
4070
|
+
instruction: manualSetup ? "Finish the manual MCP setup using the secret-free references shown in normal Connect output, then start a fresh session." : runtimeProfile(runtimeInstall.runtime).activationInstruction
|
|
4071
|
+
},
|
|
4072
|
+
next_action: nextAction2,
|
|
4073
|
+
approval: {
|
|
4074
|
+
required: input.approvalRequired,
|
|
4075
|
+
expires_at: null,
|
|
4076
|
+
// Only when there is something to approve AND the backend supplied a
|
|
4077
|
+
// link. Never synthesised here: the connector does not know the
|
|
4078
|
+
// dashboard's origin, and a guessed URL is worse than none — it is the
|
|
4079
|
+
// "do not invent one" rule the agent runbook states, applied to the
|
|
4080
|
+
// tool rather than the agent.
|
|
4081
|
+
...input.approvalRequired && input.approvalUrl ? { url: input.approvalUrl } : {}
|
|
4082
|
+
},
|
|
4083
|
+
verification: {
|
|
4084
|
+
tools: ["haven_get_agent", "haven_get_allowances"],
|
|
4085
|
+
instruction: runtimeVerificationInstruction(runtimeInstall.runtime)
|
|
4086
|
+
},
|
|
4087
|
+
// The backend contract supplies a 20-byte address. If an unexpected
|
|
4088
|
+
// malformed value arrives, do not echo it into an automation-facing
|
|
4089
|
+
// record; the human log has already been redacted separately.
|
|
4090
|
+
delegate_address: /^0x[0-9a-fA-F]{40}$/.test(input.delegateAddress) ? shortAddress(input.delegateAddress) : "[delegate-address-redacted]",
|
|
4091
|
+
// The endpoint Connect wrote into the runtime's MCP config, verbatim — the
|
|
4092
|
+
// same string that already sits in the user's own config file. Passed
|
|
4093
|
+
// through the secret filter anyway: this is the automation contract, the
|
|
4094
|
+
// value is server-supplied, and belts are cheap (the #1589 stance).
|
|
4095
|
+
...input.hostedMcpUrl ? { hosted_mcp_url: redactSecrets(input.hostedMcpUrl) } : {},
|
|
4096
|
+
// Always emitted on a completed run, empty list included: "no superseded
|
|
4097
|
+
// agents" is a fact a caller needs, and an omitted key would be
|
|
4098
|
+
// indistinguishable from an older connector that never reported it.
|
|
4099
|
+
superseded_agent_ids: input.supersededAgentIds ?? [],
|
|
4100
|
+
...input.supersededAgentsRetiredLocally !== void 0 ? { superseded_agents_retired_locally: input.supersededAgentsRetiredLocally } : {},
|
|
4101
|
+
...input.retiredAgentIds ? { retired_agent_ids: input.retiredAgentIds } : {},
|
|
4102
|
+
...input.retirementMirrorErrors ? { retirement_mirror_errors: input.retirementMirrorErrors } : {},
|
|
4103
|
+
// #3122: always emitted on a completed run (empty list included), for the
|
|
4104
|
+
// same reason as superseded_agent_ids above.
|
|
4105
|
+
existing_agents_before_write: input.existingAgentsBeforeWrite ?? [],
|
|
4106
|
+
...input.serverNameReboundFrom ? { server_name_rebound_from: input.serverNameReboundFrom } : {},
|
|
4107
|
+
...input.setupChallengeExpiresAt ? { setup_challenge_expires_at: input.setupChallengeExpiresAt } : {},
|
|
4108
|
+
...runtimeInstall.errorCode ? { error: { code: runtimeInstall.errorCode, next_action: nextAction2 } } : {}
|
|
4109
|
+
};
|
|
4110
|
+
return outcome;
|
|
3776
4111
|
}
|
|
3777
|
-
|
|
3778
|
-
|
|
3779
|
-
|
|
3780
|
-
|
|
3781
|
-
|
|
3782
|
-
|
|
3783
|
-
|
|
3784
|
-
how: "Exit this Claude Code session and start a new one:"
|
|
3785
|
-
},
|
|
3786
|
-
"codex-cli": {
|
|
3787
|
-
commands: ["codex resume --last"],
|
|
3788
|
-
how: "Start a fresh Codex CLI session:"
|
|
3789
|
-
},
|
|
3790
|
-
"codex-desktop": {
|
|
3791
|
-
commands: [],
|
|
3792
|
-
how: "Quit Codex Desktop completely (not just the window) and reopen it."
|
|
3793
|
-
},
|
|
3794
|
-
"claude-desktop": {
|
|
3795
|
-
commands: [],
|
|
3796
|
-
how: "Quit Claude Desktop completely (not just the window) and reopen it."
|
|
3797
|
-
},
|
|
3798
|
-
hermes: {
|
|
3799
|
-
commands: ["systemctl --user restart hermes-gateway", "/restart"],
|
|
3800
|
-
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:"
|
|
3801
|
-
},
|
|
3802
|
-
cursor: {
|
|
3803
|
-
commands: [],
|
|
3804
|
-
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").'
|
|
3805
|
-
},
|
|
3806
|
-
vscode: {
|
|
3807
|
-
commands: [],
|
|
3808
|
-
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").'
|
|
3809
|
-
},
|
|
3810
|
-
"vscode-insiders": {
|
|
3811
|
-
commands: [],
|
|
3812
|
-
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").'
|
|
3813
|
-
}
|
|
3814
|
-
};
|
|
4112
|
+
async function installedClientHintFor(deps) {
|
|
4113
|
+
try {
|
|
4114
|
+
const candidates = await (deps.scanInstalledClients ?? scanInstalledClients)({ env: deps.env });
|
|
4115
|
+
const hint = installedClientHint(candidates);
|
|
4116
|
+
return hint.installedClients.length > 0 ? hint : {};
|
|
4117
|
+
} catch {
|
|
4118
|
+
return {};
|
|
3815
4119
|
}
|
|
3816
|
-
});
|
|
3817
|
-
|
|
3818
|
-
// src/doctor.ts
|
|
3819
|
-
var doctor_exports = {};
|
|
3820
|
-
__export(doctor_exports, {
|
|
3821
|
-
describeAccountAddressKey: () => describeAccountAddressKey,
|
|
3822
|
-
rollUpLevel: () => rollUpLevel,
|
|
3823
|
-
runDoctor: () => runDoctor,
|
|
3824
|
-
runRepair: () => runRepair
|
|
3825
|
-
});
|
|
3826
|
-
function finalizeCheck(check) {
|
|
3827
|
-
return { ...check, ok: check.level !== "failed" };
|
|
3828
4120
|
}
|
|
3829
|
-
function
|
|
3830
|
-
|
|
3831
|
-
if (
|
|
3832
|
-
|
|
4121
|
+
function installedClientProse(hint) {
|
|
4122
|
+
const found = hint.installedClients ?? [];
|
|
4123
|
+
if (found.length === 0) return "";
|
|
4124
|
+
const suggestion = hint.suggestedRuntime ? ` The likeliest is ${hint.suggestedRuntime}, but Haven will not choose for you \u2014 pass it yourself if it is right.` : " Haven will not choose between them for you.";
|
|
4125
|
+
return `Haven can see these agent clients installed here, likeliest first: ${found.join(", ")}.${suggestion} `;
|
|
3833
4126
|
}
|
|
3834
|
-
function
|
|
3835
|
-
|
|
4127
|
+
function runtimeSelectionPrompt(options, deps) {
|
|
4128
|
+
if (!interactivePromptAllowed(options, deps)) return void 0;
|
|
4129
|
+
return deps.promptRuntime ?? (() => resolveRuntimeByInstalledClientPrompt());
|
|
3836
4130
|
}
|
|
3837
|
-
function
|
|
3838
|
-
if (
|
|
3839
|
-
return
|
|
4131
|
+
function interactivePromptAllowed(options, deps) {
|
|
4132
|
+
if (options.interactive !== true) return false;
|
|
4133
|
+
return deps.isTty ?? Boolean(process.stdin.isTTY);
|
|
3840
4134
|
}
|
|
3841
|
-
|
|
3842
|
-
|
|
3843
|
-
if (explicit) return { runtime: explicit, origin: "flag" };
|
|
3844
|
-
if (directory) {
|
|
3845
|
-
const recorded = await readConnectOutcomeRuntime(directory);
|
|
3846
|
-
if (recorded !== null && normalizeRuntimeName(recorded)) {
|
|
3847
|
-
return { runtime: recorded, origin: "record" };
|
|
3848
|
-
}
|
|
3849
|
-
}
|
|
3850
|
-
return { runtime: "", origin: "unknown" };
|
|
4135
|
+
function supersededIds(collision) {
|
|
4136
|
+
return collision.superseded.map((entry) => entry.agentId).join(", ");
|
|
3851
4137
|
}
|
|
3852
|
-
async function
|
|
3853
|
-
|
|
3854
|
-
|
|
3855
|
-
|
|
3856
|
-
|
|
3857
|
-
|
|
3858
|
-
|
|
3859
|
-
|
|
3860
|
-
|
|
3861
|
-
|
|
3862
|
-
|
|
3863
|
-
|
|
3864
|
-
const directory = path.join(root, entry);
|
|
3865
|
-
try {
|
|
3866
|
-
const s = await promises.stat(path.join(directory, "identity.json"));
|
|
3867
|
-
candidates.push({ directory, mtimeMs: s.mtimeMs });
|
|
3868
|
-
} catch {
|
|
3869
|
-
try {
|
|
3870
|
-
await promises.stat(path.join(directory, TOMBSTONE_FILENAME));
|
|
3871
|
-
tombstonedOnly.push(directory);
|
|
3872
|
-
} catch {
|
|
3873
|
-
try {
|
|
3874
|
-
await promises.stat(path.join(directory, REKEY_PENDING_FILENAME));
|
|
3875
|
-
parkedOnly.push(directory);
|
|
3876
|
-
} catch {
|
|
3877
|
-
}
|
|
3878
|
-
}
|
|
4138
|
+
async function resolveWiringCollision(collision, agentName, options, deps) {
|
|
4139
|
+
if (options.replaceExistingWiring) return { action: "replace" };
|
|
4140
|
+
if (interactivePromptAllowed(options, deps)) {
|
|
4141
|
+
const prompt = deps.promptWiringCollision ?? ((c, name) => promptWiringCollisionResolution(c, name, defaultPromptIo()));
|
|
4142
|
+
const resolution = await prompt(collision, agentName);
|
|
4143
|
+
if (resolution.action === "abort") {
|
|
4144
|
+
throw new exports.ConnectError(
|
|
4145
|
+
"wiring_collision_declined",
|
|
4146
|
+
`Setup stopped at your request: this machine is already wired to ${supersededIds(collision)} and you chose neither to replace that wiring nor to install alongside it. Nothing was written: no agent was created, no credentials were stored, and the Haven setup token is still unused. Run the connector command again with --replace to re-point haven / haven-signer at the new agent, or with --name <slug> (e.g. --name ${collision.suggestedServerName}) to install alongside.`,
|
|
4147
|
+
"rerun_connect_with_replace_or_name",
|
|
4148
|
+
{ supersededAgentIds: collision.superseded.map((e) => e.agentId), suggestedServerName: collision.suggestedServerName }
|
|
4149
|
+
);
|
|
3879
4150
|
}
|
|
4151
|
+
return resolution;
|
|
3880
4152
|
}
|
|
3881
|
-
|
|
3882
|
-
|
|
3883
|
-
|
|
3884
|
-
|
|
3885
|
-
|
|
3886
|
-
|
|
3887
|
-
|
|
3888
|
-
|
|
3889
|
-
|
|
3890
|
-
|
|
3891
|
-
|
|
3892
|
-
|
|
4153
|
+
throw new exports.ConnectError(
|
|
4154
|
+
"wiring_collision",
|
|
4155
|
+
`This machine is already wired to a Haven agent with a live key (${supersededIds(collision)}), and setting up "${agentName}" on the bare haven / haven-signer pair would replace that wiring. Nothing was written and the Haven setup token is still unused. If you are an AI agent running this command: do NOT add a flag yourself \u2014 relay this to your user and stop. Your user decides: REPLACE the existing wiring (re-run the same command with --replace added, which re-points the pair at the new agent and retires the previous directory locally \u2014 they still revoke the old agent on the Haven agent page), or install ALONGSIDE it (re-run with --name <slug> added, e.g. --name ${collision.suggestedServerName}, which gives the new agent its own haven-<slug> / haven-signer-<slug> pair). Re-run only with the flag your user chooses.`,
|
|
4156
|
+
"relay_wiring_collision_to_user",
|
|
4157
|
+
{ supersededAgentIds: collision.superseded.map((e) => e.agentId), suggestedServerName: collision.suggestedServerName }
|
|
4158
|
+
);
|
|
4159
|
+
}
|
|
4160
|
+
function failedConnectOutcome(runtimeHint, error) {
|
|
4161
|
+
const message = error instanceof Error ? error.message : "";
|
|
4162
|
+
const code = error instanceof exports.ConnectError ? error.code : /Node\.js >=/i.test(message) ? "unsupported_node_version" : /setup challenge.*expired|expired or invalid/i.test(message) ? "setup_challenge_expired_or_invalid" : /only available for Claude Code and Codex/i.test(message) ? "local_mcp_unsupported_runtime" : "connect_failed";
|
|
4163
|
+
const runtime = normalizeRuntime(runtimeHint);
|
|
4164
|
+
const nextAction2 = error instanceof exports.ConnectError ? error.nextAction : code === "setup_challenge_expired_or_invalid" ? "return_to_haven_for_fresh_setup" : code === "unsupported_node_version" ? "install_supported_node_and_rerun_connect" : code === "local_mcp_unsupported_runtime" ? "rerun_without_local_mcp" : "review_the_safe_error_output_and_start_a_fresh_haven_setup_if_needed";
|
|
3893
4165
|
return {
|
|
3894
|
-
|
|
3895
|
-
|
|
3896
|
-
|
|
4166
|
+
schema_version: exports.CONNECT_OUTCOME_SCHEMA_VERSION,
|
|
4167
|
+
outcome: "failed",
|
|
4168
|
+
runtime,
|
|
4169
|
+
topology: "unknown",
|
|
4170
|
+
configuration: { hosted_mcp: false, local_signer: false, local_mcp: false },
|
|
4171
|
+
probe: { result: "not_run" },
|
|
4172
|
+
activation: { restart_required: false, instruction: "Resolve the reported problem before activating Haven tools." },
|
|
4173
|
+
next_action: nextAction2,
|
|
4174
|
+
approval: { required: false, expires_at: null },
|
|
4175
|
+
verification: {
|
|
4176
|
+
tools: ["haven_get_agent", "haven_get_allowances"],
|
|
4177
|
+
instruction: "After a successful setup and activation, verify only with haven_get_agent and haven_get_allowances."
|
|
4178
|
+
},
|
|
4179
|
+
error: {
|
|
4180
|
+
code,
|
|
4181
|
+
next_action: nextAction2,
|
|
4182
|
+
// Only a ConnectError's message enters the JSON record: the vocabulary's
|
|
4183
|
+
// prose is connector-authored and safe to serialize, while a plain
|
|
4184
|
+
// Error can carry arbitrary server or filesystem detail (that stance is
|
|
4185
|
+
// pinned by test). Redaction stays on as belt-and-braces; plain-Error
|
|
4186
|
+
// runs still get their redacted message on stderr via the CLI mirror.
|
|
4187
|
+
...error instanceof exports.ConnectError && message ? { message: redactForAutomation(message) } : {},
|
|
4188
|
+
...error instanceof exports.ConnectError && error.details.allowedRuntimes ? { allowed_runtimes: error.details.allowedRuntimes } : {},
|
|
4189
|
+
...error instanceof exports.ConnectError && error.details.installedClients?.length ? { installed_clients: error.details.installedClients } : {},
|
|
4190
|
+
...error instanceof exports.ConnectError && error.details.suggestedRuntime ? { suggested_runtime: error.details.suggestedRuntime } : {},
|
|
4191
|
+
...error instanceof exports.ConnectError && error.details.supersededAgentIds ? { superseded_agent_ids: error.details.supersededAgentIds } : {},
|
|
4192
|
+
...error instanceof exports.ConnectError && error.details.suggestedServerName ? { suggested_name: error.details.suggestedServerName } : {}
|
|
4193
|
+
}
|
|
3897
4194
|
};
|
|
3898
4195
|
}
|
|
3899
|
-
function
|
|
3900
|
-
|
|
3901
|
-
|
|
3902
|
-
|
|
3903
|
-
|
|
4196
|
+
function printSetupSummary(setup, log) {
|
|
4197
|
+
log(`Fetched Haven setup for ${setup.agent.name}.`);
|
|
4198
|
+
log(`Haven wallet: ${setup.haven_wallet.name} on ${setup.haven_wallet.network}.`);
|
|
4199
|
+
if (setup.agent_budget.length > 0) {
|
|
4200
|
+
for (const budget of setup.agent_budget) {
|
|
4201
|
+
log(
|
|
4202
|
+
`Agent budget: ${budget.allowance_amount} atomic ${budget.token_symbol} / ${budget.reset_period_min} minute reset.`
|
|
4203
|
+
);
|
|
3904
4204
|
}
|
|
3905
|
-
return false;
|
|
3906
4205
|
}
|
|
3907
|
-
|
|
3908
|
-
if (bareOwnerExists) return false;
|
|
3909
|
-
return isPrimary && Boolean(identity?.hosted_mcp_url && configText.includes(identity.hosted_mcp_url));
|
|
3910
|
-
}
|
|
3911
|
-
function rekeyPendingCheck(status, hostedDelegateAddress, runtime, slug) {
|
|
3912
|
-
return finalizeCheck(rekeyPendingVerdict(status, hostedDelegateAddress, runtime, slug));
|
|
4206
|
+
log(`Setup challenge expires at ${setup.challenge.expires_at}. If it expires, return to Haven for a fresh setup and rerun Connect \u2014 do not reuse or paste credentials.`);
|
|
3913
4207
|
}
|
|
3914
|
-
function
|
|
3915
|
-
const
|
|
3916
|
-
const
|
|
3917
|
-
if (
|
|
3918
|
-
return {
|
|
3919
|
-
id: "rekey_pending",
|
|
3920
|
-
label,
|
|
3921
|
-
level: "failed",
|
|
3922
|
-
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.`,
|
|
3923
|
-
repair: `Delete ${status.path}, then start again: ${RERUN} --rekey${nameFlag}`
|
|
3924
|
-
};
|
|
3925
|
-
}
|
|
3926
|
-
const started = status.startedAt ?? "an unknown time";
|
|
3927
|
-
const address = status.newDelegateAddress ?? "unknown";
|
|
3928
|
-
const completedOnHaven = hostedDelegateAddress !== void 0 && status.newDelegateAddress !== void 0 && hostedDelegateAddress.toLowerCase() === status.newDelegateAddress.toLowerCase();
|
|
3929
|
-
if (completedOnHaven) {
|
|
3930
|
-
return {
|
|
3931
|
-
id: "rekey_pending",
|
|
3932
|
-
label,
|
|
3933
|
-
level: "failed",
|
|
3934
|
-
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." : ""),
|
|
3935
|
-
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>${runtimeFlagFor(runtime)}`
|
|
3936
|
-
};
|
|
3937
|
-
}
|
|
3938
|
-
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.";
|
|
3939
|
-
if (status.state === "expired") {
|
|
3940
|
-
return {
|
|
3941
|
-
id: "rekey_pending",
|
|
3942
|
-
label,
|
|
3943
|
-
level: "failed",
|
|
3944
|
-
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,
|
|
3945
|
-
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.`
|
|
3946
|
-
};
|
|
4208
|
+
function approveBudgetCta(setup, approvalUrl) {
|
|
4209
|
+
const where = approvalUrl ? `at ${approvalUrl}` : "in the Haven dashboard";
|
|
4210
|
+
const budgetPhrase = setup.agent_budget.length > 0 ? setup.agent_budget.map((budget) => `up to ${describeSetupBudget(budget)}`).join(", ") : void 0;
|
|
4211
|
+
if (budgetPhrase) {
|
|
4212
|
+
return `\u2192 Action needed: approve this agent's budget \u2014 ${budgetPhrase} from ${setup.haven_wallet.name} on ${setup.haven_wallet.network} \u2014 ${where}. The approval button is live now; setup continues here in the meantime.`;
|
|
3947
4213
|
}
|
|
3948
|
-
return {
|
|
3949
|
-
id: "rekey_pending",
|
|
3950
|
-
label,
|
|
3951
|
-
level: "ok",
|
|
3952
|
-
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
|
|
3953
|
-
};
|
|
4214
|
+
return `\u2192 Action needed: approve this agent's budget ${where} \u2014 the approval button is live now. Setup continues here in the meantime.`;
|
|
3954
4215
|
}
|
|
3955
|
-
|
|
3956
|
-
|
|
3957
|
-
|
|
3958
|
-
|
|
3959
|
-
|
|
3960
|
-
|
|
3961
|
-
);
|
|
3962
|
-
}
|
|
3963
|
-
const mcpInstalled = await readMcpSidecarOverride(directory);
|
|
3964
|
-
if (mcpInstalled) {
|
|
3965
|
-
facts.push(
|
|
3966
|
-
`local MCP runtime installed under ${describeRuntimeSpecOverride(mcpInstalled.specs)} (resolved: ${mcpInstalled.resolved_specs.join(" ")}; directory key ${mcpInstalled.directory_key})`
|
|
3967
|
-
);
|
|
3968
|
-
}
|
|
3969
|
-
let shell;
|
|
3970
|
-
try {
|
|
3971
|
-
const active = resolveRuntimeSpecOverride(env);
|
|
3972
|
-
if (active) shell = `set in this shell: ${describeRuntimeSpecOverride(active)} \u2014 a --repair from here installs these, not the pin`;
|
|
3973
|
-
} catch (err) {
|
|
3974
|
-
shell = err instanceof RuntimeSpecOverrideError ? `set in this shell but REFUSED: ${err.message}` : `set in this shell but unreadable: ${err instanceof Error ? err.message : String(err)}`;
|
|
3975
|
-
}
|
|
3976
|
-
if (shell) facts.push(shell);
|
|
3977
|
-
if (facts.length === 0) return void 0;
|
|
3978
|
-
const variables = Object.values(RUNTIME_SPEC_ENV).join(" / ");
|
|
3979
|
-
return finalizeCheck({
|
|
3980
|
-
id: "runtime_spec_override",
|
|
3981
|
-
label: "Runtime spec override",
|
|
3982
|
-
level: "failed",
|
|
3983
|
-
detail: `runtime spec overridden \u2014 not the pinned manifest (${exports.MCP_RUNTIME_MANIFEST.signerPackage}@${exports.MCP_RUNTIME_MANIFEST.signerVersion}, ${exports.MCP_RUNTIME_MANIFEST.sdkPackage}@${exports.MCP_RUNTIME_MANIFEST.sdkVersion}). ${facts.join(". ")}.`,
|
|
3984
|
-
repair: `Developer override (#2424). To return to the pinned manifest: unset ${variables}, then run ${RERUN} --doctor --repair --runtime <runtime>. If the override is intentional, this finding is the record of it.`
|
|
4216
|
+
function describeSetupBudget(budget) {
|
|
4217
|
+
return describeApprovedBudget({
|
|
4218
|
+
token_symbol: budget.token_symbol,
|
|
4219
|
+
token_address: budget.token_address,
|
|
4220
|
+
amount: budget.allowance_amount,
|
|
4221
|
+
reset_period_min: budget.reset_period_min
|
|
3985
4222
|
});
|
|
3986
4223
|
}
|
|
3987
|
-
|
|
3988
|
-
|
|
3989
|
-
|
|
3990
|
-
|
|
3991
|
-
|
|
3992
|
-
|
|
3993
|
-
}
|
|
4224
|
+
function assertSetupChallengeIsUsable(expiresAt) {
|
|
4225
|
+
const expiresAtMs = Date.parse(expiresAt);
|
|
4226
|
+
if (!Number.isNaN(expiresAtMs) && expiresAtMs > Date.now()) return;
|
|
4227
|
+
throw new Error(
|
|
4228
|
+
"This Haven setup challenge is expired or invalid. Return to Haven, start a fresh connection, and rerun Connect. No local credentials were written."
|
|
4229
|
+
);
|
|
3994
4230
|
}
|
|
3995
|
-
|
|
3996
|
-
|
|
3997
|
-
|
|
3998
|
-
|
|
3999
|
-
|
|
4000
|
-
|
|
4231
|
+
function deadSetupTokenError(err) {
|
|
4232
|
+
if (!(err instanceof ConnectRequestError) || err.status !== 410 && err.status !== 401) return null;
|
|
4233
|
+
return new exports.ConnectError(
|
|
4234
|
+
"setup_challenge_expired_or_invalid",
|
|
4235
|
+
"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 connector command. No local credentials were written.",
|
|
4236
|
+
"return_to_haven_for_fresh_setup"
|
|
4237
|
+
);
|
|
4001
4238
|
}
|
|
4002
|
-
function
|
|
4003
|
-
|
|
4004
|
-
const has = (key) => files.some((f) => typeof f?.[key] === "string" && f[key].trim() !== "");
|
|
4005
|
-
if (has("account_address")) return "account address stored as account_address";
|
|
4006
|
-
if (has("safe_address")) {
|
|
4007
|
-
return "account address stored under the pre-#2908 name safe_address \u2014 still read; the next --rekey or setup rewrites it as account_address";
|
|
4008
|
-
}
|
|
4009
|
-
return "no account address stored";
|
|
4239
|
+
function isExpiredSetupChallenge(err) {
|
|
4240
|
+
return err instanceof Error && /(?:setup )?challenge.*expir|expir.*(?:setup )?challenge/i.test(err.message);
|
|
4010
4241
|
}
|
|
4011
|
-
|
|
4012
|
-
|
|
4013
|
-
|
|
4014
|
-
checks: verdicts.checks.map(finalizeCheck),
|
|
4015
|
-
...verdicts.signerCapabilities ? { signerCapabilities: verdicts.signerCapabilities } : {}
|
|
4242
|
+
function secureLogger(log, redactPaths = false) {
|
|
4243
|
+
return (message) => {
|
|
4244
|
+
log(redactPaths ? redactForAutomation(message) : redactSecrets(message));
|
|
4016
4245
|
};
|
|
4017
4246
|
}
|
|
4018
|
-
|
|
4019
|
-
const
|
|
4020
|
-
|
|
4021
|
-
|
|
4022
|
-
|
|
4023
|
-
|
|
4024
|
-
|
|
4025
|
-
|
|
4026
|
-
} catch {
|
|
4027
|
-
signerFile = void 0;
|
|
4247
|
+
function printRuntimeInstall(result, log) {
|
|
4248
|
+
for (const message of result.messages) log(message);
|
|
4249
|
+
if (result.localMcpConfigured) {
|
|
4250
|
+
log("Configured local Haven MCP tools.");
|
|
4251
|
+
} else if (result.hostedMcpConfigured) {
|
|
4252
|
+
log("Configured hosted Haven MCP identity.");
|
|
4253
|
+
} else {
|
|
4254
|
+
log("Haven MCP tools still need runtime setup.");
|
|
4028
4255
|
}
|
|
4029
|
-
|
|
4030
|
-
|
|
4031
|
-
id: "credentials",
|
|
4032
|
-
label: "Agent credentials",
|
|
4033
|
-
level: credentialsOk ? "ok" : "failed",
|
|
4034
|
-
detail: credentialsOk ? `identity.json and signer.json parse (agent ${identity?.agent_id ?? "unknown"}; ${describeAccountAddressKey(identity, signerFile)})` : "identity.json or signer.json is missing or unparseable.",
|
|
4035
|
-
...credentialsOk ? {} : { repair: `Re-run the full setup with a fresh token: ${RERUN} --setup <token>.` }
|
|
4036
|
-
});
|
|
4037
|
-
if (!sidecar) {
|
|
4038
|
-
checks.push({
|
|
4039
|
-
id: "signer_runtime",
|
|
4040
|
-
label: "Signer runtime (preinstalled wrapper)",
|
|
4041
|
-
level: "failed",
|
|
4042
|
-
detail: "No signer-runtime.json sidecar \u2014 the pinned signer runtime was never prepared (or a pre-#1586 npx config).",
|
|
4043
|
-
repair: repairCommandFor(input.runtime)
|
|
4044
|
-
});
|
|
4045
|
-
} else if (sidecar.runtime_spec_override) {
|
|
4046
|
-
const matches = await installedRuntimeMatchesVersions(sidecar.runtime_directory, sidecar.cli_path, {
|
|
4047
|
-
signerVersion: sidecar.signer_version,
|
|
4048
|
-
sdkVersion: sidecar.sdk_version
|
|
4049
|
-
});
|
|
4050
|
-
checks.push({
|
|
4051
|
-
id: "signer_runtime",
|
|
4052
|
-
label: "Signer runtime (preinstalled wrapper)",
|
|
4053
|
-
level: matches ? "ok" : "failed",
|
|
4054
|
-
detail: matches ? `Installed ${sidecar.signer_package}@${sidecar.signer_version} at ${sidecar.runtime_directory} (override install \u2014 see runtime_spec_override)` : `Override runtime directory is stale or empty (${sidecar.runtime_directory}) \u2014 the CLI or package versions are missing.`,
|
|
4055
|
-
...matches ? {} : { repair: repairCommandFor(input.runtime, " with the same HAVEN_*_SPEC variables set.") }
|
|
4056
|
-
});
|
|
4256
|
+
if (result.localSignerConfigured) {
|
|
4257
|
+
log("Configured local Haven signer.");
|
|
4057
4258
|
} else {
|
|
4058
|
-
|
|
4059
|
-
signerVersion: sidecar.signer_version,
|
|
4060
|
-
sdkVersion: sidecar.sdk_version
|
|
4061
|
-
});
|
|
4062
|
-
const versionOk = sidecar.signer_version === exports.MCP_RUNTIME_MANIFEST.signerVersion;
|
|
4063
|
-
const ok = intact && versionOk;
|
|
4064
|
-
checks.push({
|
|
4065
|
-
id: "signer_runtime",
|
|
4066
|
-
label: "Signer runtime (preinstalled wrapper)",
|
|
4067
|
-
level: ok ? "ok" : intact ? "advisory" : "failed",
|
|
4068
|
-
detail: ok ? `Installed ${sidecar.signer_package}@${sidecar.signer_version} at ${sidecar.runtime_directory}` : intact ? `Installed version ${sidecar.signer_version} does not match the connector's pinned ${exports.MCP_RUNTIME_MANIFEST.signerVersion} \u2014 intact, but outdated.` : `Runtime directory is stale or empty (${sidecar.runtime_directory}) \u2014 the CLI or package versions are missing.`,
|
|
4069
|
-
...ok ? {} : { repair: repairCommandFor(input.runtime) }
|
|
4070
|
-
});
|
|
4259
|
+
log("Local Haven signer still needs runtime setup.");
|
|
4071
4260
|
}
|
|
4072
|
-
|
|
4073
|
-
|
|
4074
|
-
const
|
|
4075
|
-
|
|
4076
|
-
|
|
4077
|
-
|
|
4078
|
-
|
|
4079
|
-
|
|
4080
|
-
|
|
4081
|
-
|
|
4082
|
-
|
|
4083
|
-
|
|
4084
|
-
|
|
4085
|
-
|
|
4086
|
-
|
|
4087
|
-
|
|
4088
|
-
|
|
4089
|
-
|
|
4090
|
-
|
|
4091
|
-
|
|
4092
|
-
|
|
4093
|
-
|
|
4261
|
+
}
|
|
4262
|
+
function formatAtomicAmount(atomic, decimals) {
|
|
4263
|
+
const s = atomic.toString().padStart(decimals + 1, "0");
|
|
4264
|
+
const intPart = s.slice(0, s.length - decimals) || "0";
|
|
4265
|
+
const fracPart = s.slice(s.length - decimals).replace(/0+$/, "");
|
|
4266
|
+
return fracPart ? `${intPart}.${fracPart}` : intPart;
|
|
4267
|
+
}
|
|
4268
|
+
function describeResetPeriod(resetPeriodMin) {
|
|
4269
|
+
if (resetPeriodMin === 1440) return "per day";
|
|
4270
|
+
if (resetPeriodMin === 10080) return "per week";
|
|
4271
|
+
if (resetPeriodMin === 43200) return "per month";
|
|
4272
|
+
if (resetPeriodMin === 60) return "per hour";
|
|
4273
|
+
if (resetPeriodMin === 0) return "in total";
|
|
4274
|
+
return `every ${resetPeriodMin} minutes`;
|
|
4275
|
+
}
|
|
4276
|
+
function describeApprovedBudget(budget) {
|
|
4277
|
+
const token = sdk.resolveTokenFromAddress(budget.token_address);
|
|
4278
|
+
const amount = token ? `${formatAtomicAmount(BigInt(budget.amount), token.decimals)} ${budget.token_symbol}` : `${budget.amount} ${budget.token_symbol} (atomic units)`;
|
|
4279
|
+
return `${amount} ${describeResetPeriod(budget.reset_period_min)}`;
|
|
4280
|
+
}
|
|
4281
|
+
function describeWaitBound(timeoutMs) {
|
|
4282
|
+
if (timeoutMs >= 12e4) {
|
|
4283
|
+
const minutes = Math.round(timeoutMs / 6e4);
|
|
4284
|
+
return `${minutes} minutes`;
|
|
4094
4285
|
}
|
|
4095
|
-
|
|
4096
|
-
|
|
4097
|
-
|
|
4098
|
-
|
|
4099
|
-
|
|
4100
|
-
|
|
4101
|
-
|
|
4102
|
-
|
|
4103
|
-
|
|
4104
|
-
|
|
4105
|
-
|
|
4106
|
-
|
|
4107
|
-
|
|
4108
|
-
|
|
4109
|
-
|
|
4110
|
-
|
|
4111
|
-
|
|
4112
|
-
|
|
4113
|
-
|
|
4114
|
-
|
|
4115
|
-
|
|
4116
|
-
|
|
4117
|
-
|
|
4118
|
-
|
|
4119
|
-
|
|
4120
|
-
|
|
4121
|
-
const same = probe.delegateAddress?.toLowerCase() === localDelegate.toLowerCase();
|
|
4122
|
-
checks.push({
|
|
4123
|
-
id: "identity_match",
|
|
4124
|
-
label: "Hosted identity matches the local signing key",
|
|
4125
|
-
level: same ? "ok" : "failed",
|
|
4126
|
-
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.`,
|
|
4127
|
-
...same ? {} : {
|
|
4128
|
-
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.`
|
|
4129
|
-
}
|
|
4130
|
-
});
|
|
4286
|
+
return `${Math.round(timeoutMs / 1e3)}s`;
|
|
4287
|
+
}
|
|
4288
|
+
async function waitForBudgetApproval(api, setupId, apiKey, log, options = {}) {
|
|
4289
|
+
const intervalMs = options.intervalMs ?? 5e3;
|
|
4290
|
+
const timeoutMs = options.timeoutMs ?? 18e4;
|
|
4291
|
+
const sleep = options.sleep ?? ((ms) => new Promise((resolve11) => setTimeout(resolve11, ms)));
|
|
4292
|
+
const maxPolls = Math.max(1, Math.floor(timeoutMs / intervalMs));
|
|
4293
|
+
const remindEvery = Math.max(1, Math.floor(3e4 / intervalMs));
|
|
4294
|
+
let waitingAnnounced = false;
|
|
4295
|
+
const announceWaiting = () => {
|
|
4296
|
+
if (waitingAnnounced) return;
|
|
4297
|
+
waitingAnnounced = true;
|
|
4298
|
+
log("Now waiting for you to approve the budget in the Haven dashboard \u2014 approval is what unlocks the agent's Haven tools\u2026");
|
|
4299
|
+
};
|
|
4300
|
+
for (let i = 0; i < maxPolls; i++) {
|
|
4301
|
+
if (i > 0) await sleep(intervalMs);
|
|
4302
|
+
let status;
|
|
4303
|
+
try {
|
|
4304
|
+
status = await api.getConnectorStatus(setupId, apiKey);
|
|
4305
|
+
} catch (err) {
|
|
4306
|
+
if (err instanceof ConnectRequestError && (err.status === 401 || err.status === 404)) {
|
|
4307
|
+
log("This setup ended in Haven \u2014 start a fresh connection from the dashboard when ready.");
|
|
4308
|
+
return "ended";
|
|
4309
|
+
}
|
|
4310
|
+
announceWaiting();
|
|
4311
|
+
continue;
|
|
4131
4312
|
}
|
|
4132
|
-
|
|
4133
|
-
|
|
4134
|
-
|
|
4135
|
-
|
|
4136
|
-
|
|
4137
|
-
|
|
4138
|
-
|
|
4139
|
-
|
|
4140
|
-
|
|
4141
|
-
|
|
4142
|
-
|
|
4143
|
-
|
|
4144
|
-
|
|
4145
|
-
|
|
4146
|
-
|
|
4147
|
-
} else {
|
|
4148
|
-
const probe = await (deps.probeSignerTools ?? probeLocalMcpTools)(
|
|
4149
|
-
sidecar.wrapper_path,
|
|
4150
|
-
[],
|
|
4151
|
-
exports.MCP_RUNTIME_MANIFEST.requiredSignerTools
|
|
4313
|
+
if (status.status === "active") {
|
|
4314
|
+
log(
|
|
4315
|
+
status.approved_budget ? `Budget approved \u{1F389} \u2014 I can now spend up to ${describeApprovedBudget(status.approved_budget)} from your Haven wallet.` : "Budget approved \u{1F389} \u2014 the agent can now spend within its Haven rules."
|
|
4316
|
+
);
|
|
4317
|
+
return "approved";
|
|
4318
|
+
}
|
|
4319
|
+
if (status.status === "cancelled" || status.status === "expired" || status.status === "failed") {
|
|
4320
|
+
log(`This setup ended in Haven (${status.status}) \u2014 start a fresh connection from the dashboard when ready.`);
|
|
4321
|
+
return "ended";
|
|
4322
|
+
}
|
|
4323
|
+
announceWaiting();
|
|
4324
|
+
if (i > 0 && i % remindEvery === 0) {
|
|
4325
|
+
const elapsedSeconds = Math.round(i * intervalMs / 1e3);
|
|
4326
|
+
log(
|
|
4327
|
+
`Still waiting for budget approval in Haven \u2014 ${elapsedSeconds}s elapsed, checking every ${Math.round(intervalMs / 1e3)}s. I'll stop waiting after ${describeWaitBound(timeoutMs)}; you can approve later and the tools unlock then.`
|
|
4152
4328
|
);
|
|
4153
|
-
const experimental = probe.capabilities?.experimental ?? probe.capabilities;
|
|
4154
|
-
const compat = experimental?.["haven/signer-compatibility"];
|
|
4155
|
-
signerCapabilities = compat ? { "haven/signer-compatibility": compat } : void 0;
|
|
4156
|
-
const compatDetail = compat ? ` Compat: x402 expected-context v${JSON.stringify(compat.x402_expected_context_versions ?? "?")}.` : "";
|
|
4157
|
-
checks.push({
|
|
4158
|
-
id: "signer_process",
|
|
4159
|
-
label: "Signer stdio handshake",
|
|
4160
|
-
level: probe.status === "ok" ? "ok" : "failed",
|
|
4161
|
-
detail: probe.status === "ok" ? `Signer started, listed ${probe.toolNames?.length ?? 0} tools${probe.serverInfo?.version ? ` (v${probe.serverInfo.version})` : ""}.${compatDetail}` : `Handshake failed: ${probe.status}.`,
|
|
4162
|
-
...probe.status === "ok" ? {} : { repair: repairCommandFor(input.runtime) }
|
|
4163
|
-
});
|
|
4164
4329
|
}
|
|
4165
|
-
} else {
|
|
4166
|
-
checks.push({
|
|
4167
|
-
id: "signer_process",
|
|
4168
|
-
label: "Signer stdio handshake",
|
|
4169
|
-
level: "failed",
|
|
4170
|
-
detail: "Skipped \u2014 no prepared signer runtime to probe.",
|
|
4171
|
-
repair: repairCommandFor(input.runtime)
|
|
4172
|
-
});
|
|
4173
4330
|
}
|
|
4174
|
-
|
|
4331
|
+
log(
|
|
4332
|
+
"Budget approval is still pending in Haven. Approve it in the dashboard whenever you are ready \u2014 the agent tools unlock the moment you do. Verify later with the read-only haven_get_agent tool."
|
|
4333
|
+
);
|
|
4334
|
+
return "pending";
|
|
4175
4335
|
}
|
|
4176
|
-
|
|
4177
|
-
const
|
|
4178
|
-
|
|
4179
|
-
|
|
4180
|
-
|
|
4181
|
-
|
|
4182
|
-
|
|
4183
|
-
|
|
4184
|
-
|
|
4185
|
-
|
|
4186
|
-
|
|
4187
|
-
|
|
4336
|
+
function completionHandoffLines(result, approval, approvalUrl) {
|
|
4337
|
+
const approveStep = approvalUrl ? `Approve the budget at ${approvalUrl}. Approval \u2014 not restarting \u2014 unlocks Haven tools.` : "Return to Haven and approve the budget. Approval \u2014 not restarting \u2014 unlocks Haven tools.";
|
|
4338
|
+
if (result.errorCode === "manual_runtime_setup_required") {
|
|
4339
|
+
return [
|
|
4340
|
+
"Next steps:",
|
|
4341
|
+
`1. ${approveStep}`,
|
|
4342
|
+
"2. Finish the manual MCP setup using the secret-free file references printed above, then start a fresh session in your runtime.",
|
|
4343
|
+
`3. ${runtimeVerificationInstruction(result.runtime)}`
|
|
4344
|
+
];
|
|
4345
|
+
}
|
|
4346
|
+
if (result.errorCode) {
|
|
4347
|
+
return [
|
|
4348
|
+
"Recovery: runtime setup is not complete. Resolve the reported problem, then return to Haven for a fresh connection and run its new connector command. Do not manually edit runtime config or paste credentials into prompts, logs, or config."
|
|
4349
|
+
];
|
|
4350
|
+
}
|
|
4351
|
+
if (approval === "ended") {
|
|
4352
|
+
return [
|
|
4353
|
+
"Next step: this setup ended in Haven before the budget was approved, so there is nothing left to approve on it \u2014 start a fresh connection from the dashboard when ready."
|
|
4354
|
+
];
|
|
4355
|
+
}
|
|
4356
|
+
const profile = runtimeProfile(result.runtime);
|
|
4357
|
+
const activation = activationInstructionWithWhy(profile);
|
|
4358
|
+
if (approval === "approved") {
|
|
4359
|
+
return [
|
|
4360
|
+
"Next steps \u2014 the budget is already approved, so there is nothing more to do in Haven:",
|
|
4361
|
+
`1. ${activation}`,
|
|
4362
|
+
`2. ${runtimeVerificationInstruction(result.runtime)}`
|
|
4363
|
+
];
|
|
4364
|
+
}
|
|
4365
|
+
return [
|
|
4366
|
+
"Next steps:",
|
|
4367
|
+
`1. ${approveStep}`,
|
|
4368
|
+
`2. ${activation}`,
|
|
4369
|
+
`3. ${runtimeVerificationInstruction(result.runtime)}`
|
|
4370
|
+
];
|
|
4371
|
+
}
|
|
4372
|
+
function activationInstructionWithWhy(profile) {
|
|
4373
|
+
if (profile.restartMode === "restart-session") {
|
|
4374
|
+
return `${profile.activationInstruction} (The entries are already written and verified \u2014 ${profile.label} only reads MCP config when a session starts, which is why this step is still needed.)`;
|
|
4375
|
+
}
|
|
4376
|
+
if (profile.restartMode === "restart-app") {
|
|
4377
|
+
return `${profile.activationInstruction} (The entries are already written and verified \u2014 ${profile.label} only reads MCP config at app launch, which is why this step is still needed.)`;
|
|
4378
|
+
}
|
|
4379
|
+
return profile.activationInstruction;
|
|
4380
|
+
}
|
|
4381
|
+
async function listExistingKeyedAgents(baseDir) {
|
|
4382
|
+
const root = defaultCredentialRoot(baseDir);
|
|
4383
|
+
let entries = [];
|
|
4384
|
+
try {
|
|
4385
|
+
entries = await promises.readdir(root);
|
|
4386
|
+
} catch {
|
|
4387
|
+
return [];
|
|
4388
|
+
}
|
|
4389
|
+
const out = [];
|
|
4390
|
+
for (const entry of entries) {
|
|
4391
|
+
const directory = path.join(root, entry);
|
|
4188
4392
|
try {
|
|
4189
|
-
|
|
4393
|
+
const identity = JSON.parse(await promises.readFile(path.join(directory, "identity.json"), "utf8"));
|
|
4394
|
+
if (typeof identity.api_key !== "string" || identity.api_key.length === 0) continue;
|
|
4395
|
+
let agent = {};
|
|
4396
|
+
try {
|
|
4397
|
+
agent = JSON.parse(await promises.readFile(path.join(directory, "agent.json"), "utf8"));
|
|
4398
|
+
} catch {
|
|
4399
|
+
}
|
|
4400
|
+
const { accountAddress } = readStoredAccountAddress(identity, agent);
|
|
4401
|
+
out.push({ agentId: typeof identity.agent_id === "string" ? identity.agent_id : entry, directory, accountAddress: accountAddress ?? null });
|
|
4190
4402
|
} catch {
|
|
4191
|
-
configText = null;
|
|
4192
4403
|
}
|
|
4193
4404
|
}
|
|
4194
|
-
|
|
4195
|
-
|
|
4196
|
-
|
|
4197
|
-
|
|
4198
|
-
|
|
4199
|
-
|
|
4200
|
-
|
|
4201
|
-
|
|
4405
|
+
return out;
|
|
4406
|
+
}
|
|
4407
|
+
async function listOtherAgentIds(baseDir, currentDirectory) {
|
|
4408
|
+
const root = defaultCredentialRoot(baseDir);
|
|
4409
|
+
let entries = [];
|
|
4410
|
+
try {
|
|
4411
|
+
entries = await promises.readdir(root);
|
|
4412
|
+
} catch {
|
|
4413
|
+
return null;
|
|
4202
4414
|
}
|
|
4203
|
-
const
|
|
4204
|
-
const
|
|
4205
|
-
|
|
4206
|
-
|
|
4207
|
-
|
|
4208
|
-
|
|
4209
|
-
|
|
4210
|
-
const slug = sidecar?.server_name;
|
|
4211
|
-
const names = serverNamesFor(slug);
|
|
4212
|
-
const rekeyPending = await inspectRekeyPending(dir, deps.now?.() ?? Date.now());
|
|
4213
|
-
if (!identity?.api_key) {
|
|
4214
|
-
const agentId = tombstone?.agent_id ?? rekeyPending?.agentId;
|
|
4215
|
-
inventory.push({
|
|
4216
|
-
...slug ? { slug } : {},
|
|
4217
|
-
...agentId ? { agentId } : {},
|
|
4218
|
-
directory: dir,
|
|
4219
|
-
// A tombstone is a deliberate record and outranks the discovery tell:
|
|
4220
|
-
// a retired directory that also holds a parked key stays `retired`.
|
|
4221
|
-
classification: tombstone ? "retired" : parkedOnly.has(dir) ? "parked" : "orphaned",
|
|
4222
|
-
checks: rekeyPending ? [rekeyPendingCheck(rekeyPending, void 0, input2.runtime, slug)] : [],
|
|
4223
|
-
...rekeyPending ? { rekeyPending } : {}
|
|
4224
|
-
});
|
|
4415
|
+
const ids = [];
|
|
4416
|
+
for (const entry of entries) {
|
|
4417
|
+
if (path.join(root, entry) === currentDirectory) continue;
|
|
4418
|
+
const identityPath = path.join(root, entry, "identity.json");
|
|
4419
|
+
try {
|
|
4420
|
+
await promises.stat(identityPath);
|
|
4421
|
+
} catch {
|
|
4225
4422
|
continue;
|
|
4226
4423
|
}
|
|
4227
|
-
|
|
4228
|
-
|
|
4229
|
-
|
|
4230
|
-
|
|
4231
|
-
|
|
4232
|
-
classification: wired ? "wired" : "superseded",
|
|
4233
|
-
checks: [],
|
|
4234
|
-
...rekeyPending ? { rekeyPending } : {}
|
|
4235
|
-
};
|
|
4236
|
-
if (wired) {
|
|
4237
|
-
const result = await checksForAgent({ directory: dir, identity, sidecar }, input2, deps);
|
|
4238
|
-
entry.checks = result.checks;
|
|
4239
|
-
capabilitiesByDirectory.set(dir, result.signerCapabilities);
|
|
4240
|
-
} else if (rekeyPending) {
|
|
4241
|
-
entry.checks = [rekeyPendingCheck(rekeyPending, void 0, input2.runtime, slug)];
|
|
4424
|
+
try {
|
|
4425
|
+
const identity = JSON.parse(await promises.readFile(identityPath, "utf8"));
|
|
4426
|
+
ids.push(identity.agent_id ?? entry);
|
|
4427
|
+
} catch {
|
|
4428
|
+
ids.push(entry);
|
|
4242
4429
|
}
|
|
4243
|
-
inventory.push(entry);
|
|
4244
4430
|
}
|
|
4245
|
-
|
|
4246
|
-
|
|
4247
|
-
|
|
4248
|
-
|
|
4249
|
-
|
|
4250
|
-
|
|
4431
|
+
return ids;
|
|
4432
|
+
}
|
|
4433
|
+
function printNextSteps(result, log, approval, approvalUrl) {
|
|
4434
|
+
for (const line of completionHandoffLines(result, approval, approvalUrl)) log(line);
|
|
4435
|
+
}
|
|
4436
|
+
exports.CONNECTOR_VERSION = void 0; var CONNECTOR_CLIENT_IDENTITY; exports.CONNECT_OUTCOME_SCHEMA_VERSION = void 0; var failureOutcomesByError, RERUN_HINT;
|
|
4437
|
+
var init_runtime = __esm({
|
|
4438
|
+
"src/runtime.ts"() {
|
|
4439
|
+
init_api();
|
|
4440
|
+
init_key();
|
|
4441
|
+
init_redact();
|
|
4442
|
+
init_server_names();
|
|
4443
|
+
init_storage();
|
|
4444
|
+
init_runtime_install();
|
|
4445
|
+
init_runtime_registry();
|
|
4446
|
+
init_connect_error();
|
|
4447
|
+
init_installed_clients();
|
|
4448
|
+
init_wiring_collision();
|
|
4449
|
+
init_unwire();
|
|
4450
|
+
init_tombstone();
|
|
4451
|
+
init_local_mcp_runtime();
|
|
4452
|
+
init_runtime_manifest();
|
|
4453
|
+
exports.CONNECTOR_VERSION = "0.0.0-dev.202609251409.98ed67a";
|
|
4454
|
+
CONNECTOR_CLIENT_IDENTITY = `@haven_ai/connect/${exports.CONNECTOR_VERSION}`;
|
|
4455
|
+
exports.CONNECT_OUTCOME_SCHEMA_VERSION = 1;
|
|
4456
|
+
failureOutcomesByError = /* @__PURE__ */ new WeakMap();
|
|
4457
|
+
RERUN_HINT = sdk.connectorRerunCommand();
|
|
4251
4458
|
}
|
|
4252
|
-
|
|
4253
|
-
|
|
4254
|
-
|
|
4255
|
-
|
|
4256
|
-
|
|
4257
|
-
|
|
4258
|
-
|
|
4259
|
-
|
|
4260
|
-
|
|
4261
|
-
|
|
4262
|
-
|
|
4263
|
-
|
|
4264
|
-
|
|
4265
|
-
|
|
4266
|
-
|
|
4267
|
-
|
|
4268
|
-
|
|
4269
|
-
|
|
4270
|
-
|
|
4459
|
+
});
|
|
4460
|
+
|
|
4461
|
+
// src/rekey-messages.ts
|
|
4462
|
+
var REKEY_FINISH_NEEDS_API_KEY;
|
|
4463
|
+
var init_rekey_messages = __esm({
|
|
4464
|
+
"src/rekey-messages.ts"() {
|
|
4465
|
+
REKEY_FINISH_NEEDS_API_KEY = "--rekey-finish needs --api-key <key> \u2014 the one the Haven agent page showed once.";
|
|
4466
|
+
}
|
|
4467
|
+
});
|
|
4468
|
+
|
|
4469
|
+
// src/prune-runtimes.ts
|
|
4470
|
+
var prune_runtimes_exports = {};
|
|
4471
|
+
__export(prune_runtimes_exports, {
|
|
4472
|
+
normalizeRuntimePath: () => normalizeRuntimePath,
|
|
4473
|
+
pruneSignerRuntimes: () => pruneSignerRuntimes,
|
|
4474
|
+
referencedRuntimeDirectories: () => referencedRuntimeDirectories,
|
|
4475
|
+
rollUpPruneLevel: () => rollUpPruneLevel,
|
|
4476
|
+
signerRuntimeRoot: () => signerRuntimeRoot
|
|
4477
|
+
});
|
|
4478
|
+
function signerRuntimeRoot(homeDir) {
|
|
4479
|
+
return path.join(homeDir, ".haven", "signer-runtime");
|
|
4480
|
+
}
|
|
4481
|
+
function classifyKey(key) {
|
|
4482
|
+
if (key.startsWith("override-")) return "override";
|
|
4483
|
+
if (key === exports.MCP_RUNTIME_MANIFEST.signerVersion || /^\d+\.\d+\.\d+/.test(key)) return "version";
|
|
4484
|
+
return "unknown";
|
|
4485
|
+
}
|
|
4486
|
+
async function directoryBytes(directory) {
|
|
4487
|
+
let total = 0;
|
|
4488
|
+
const walk = async (dir) => {
|
|
4489
|
+
let entries = [];
|
|
4490
|
+
try {
|
|
4491
|
+
entries = await promises.readdir(dir, { withFileTypes: true });
|
|
4492
|
+
} catch {
|
|
4493
|
+
return;
|
|
4271
4494
|
}
|
|
4272
|
-
for (const
|
|
4273
|
-
const
|
|
4274
|
-
if (
|
|
4495
|
+
for (const entry of entries) {
|
|
4496
|
+
const path$1 = path.join(dir, entry.name);
|
|
4497
|
+
if (entry.isDirectory()) await walk(path$1);
|
|
4498
|
+
else if (entry.isFile()) {
|
|
4499
|
+
try {
|
|
4500
|
+
total += (await promises.stat(path$1)).size;
|
|
4501
|
+
} catch {
|
|
4502
|
+
}
|
|
4503
|
+
}
|
|
4275
4504
|
}
|
|
4505
|
+
};
|
|
4506
|
+
await walk(directory);
|
|
4507
|
+
return total;
|
|
4508
|
+
}
|
|
4509
|
+
async function normalizeRuntimePath(path$1) {
|
|
4510
|
+
const resolved = path.resolve(path$1).replace(/[\\/]+$/, "");
|
|
4511
|
+
try {
|
|
4512
|
+
return await promises.realpath(resolved);
|
|
4513
|
+
} catch {
|
|
4514
|
+
return resolved;
|
|
4276
4515
|
}
|
|
4277
|
-
|
|
4278
|
-
|
|
4279
|
-
|
|
4280
|
-
|
|
4281
|
-
|
|
4282
|
-
|
|
4283
|
-
|
|
4284
|
-
|
|
4285
|
-
|
|
4286
|
-
|
|
4287
|
-
|
|
4288
|
-
|
|
4289
|
-
|
|
4290
|
-
|
|
4291
|
-
|
|
4292
|
-
|
|
4293
|
-
|
|
4294
|
-
|
|
4295
|
-
|
|
4296
|
-
|
|
4297
|
-
|
|
4298
|
-
|
|
4299
|
-
|
|
4300
|
-
}
|
|
4301
|
-
|
|
4302
|
-
|
|
4303
|
-
|
|
4304
|
-
|
|
4305
|
-
|
|
4306
|
-
|
|
4307
|
-
|
|
4308
|
-
|
|
4309
|
-
|
|
4310
|
-
|
|
4311
|
-
|
|
4312
|
-
|
|
4313
|
-
|
|
4314
|
-
|
|
4315
|
-
|
|
4316
|
-
checks.push({
|
|
4317
|
-
id: "runtime_config",
|
|
4318
|
-
label: "Runtime MCP config",
|
|
4319
|
-
level: ok ? "ok" : "failed",
|
|
4320
|
-
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)" : ""}.`,
|
|
4321
|
-
...ok ? {} : { repair: repairCommandFor(input2.runtime) }
|
|
4322
|
-
});
|
|
4323
|
-
}
|
|
4324
|
-
for (const id of ["hosted_mcp", "identity_match", "rekey_pending"]) {
|
|
4325
|
-
const check = primaryChecksById.get(id);
|
|
4326
|
-
if (check) checks.push(check);
|
|
4516
|
+
}
|
|
4517
|
+
function escapeRegExp(text) {
|
|
4518
|
+
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
4519
|
+
}
|
|
4520
|
+
async function referencedRuntimeDirectories(homeDir, credentialsDir) {
|
|
4521
|
+
const roots = /* @__PURE__ */ new Set([path.join(homeDir, ".haven", "agents")]);
|
|
4522
|
+
if (credentialsDir) roots.add(path.dirname(path.resolve(credentialsDir)));
|
|
4523
|
+
const referenced = /* @__PURE__ */ new Map();
|
|
4524
|
+
const runtimeRoot = await normalizeRuntimePath(signerRuntimeRoot(homeDir));
|
|
4525
|
+
const rootSpellings = [.../* @__PURE__ */ new Set([path.resolve(signerRuntimeRoot(homeDir)), runtimeRoot])];
|
|
4526
|
+
const wrapperRe = new RegExp(`(?:${rootSpellings.map(escapeRegExp).join("|")})[\\/]+([^\\/'"\\s]+)`, "g");
|
|
4527
|
+
const add = async (runtimeDirectory, by) => {
|
|
4528
|
+
const key = await normalizeRuntimePath(runtimeDirectory);
|
|
4529
|
+
const list = referenced.get(key) ?? [];
|
|
4530
|
+
if (!list.includes(by)) list.push(by);
|
|
4531
|
+
referenced.set(key, list);
|
|
4532
|
+
};
|
|
4533
|
+
for (const root of roots) {
|
|
4534
|
+
let entries = [];
|
|
4535
|
+
try {
|
|
4536
|
+
entries = await promises.readdir(root);
|
|
4537
|
+
} catch {
|
|
4538
|
+
continue;
|
|
4539
|
+
}
|
|
4540
|
+
for (const entry of entries) {
|
|
4541
|
+
const directory = path.join(root, entry);
|
|
4542
|
+
try {
|
|
4543
|
+
const sidecar = JSON.parse(await promises.readFile(path.join(directory, "signer-runtime.json"), "utf8"));
|
|
4544
|
+
if (typeof sidecar.runtime_directory === "string" && sidecar.runtime_directory.length > 0) {
|
|
4545
|
+
await add(sidecar.runtime_directory, directory);
|
|
4546
|
+
}
|
|
4547
|
+
} catch {
|
|
4548
|
+
}
|
|
4549
|
+
try {
|
|
4550
|
+
const wrapper = await promises.readFile(path.join(directory, "bin", "haven-signer.mjs"), "utf8");
|
|
4551
|
+
for (const match of wrapper.matchAll(wrapperRe)) await add(path.join(runtimeRoot, match[1]), directory);
|
|
4552
|
+
} catch {
|
|
4553
|
+
}
|
|
4554
|
+
}
|
|
4327
4555
|
}
|
|
4328
|
-
|
|
4329
|
-
if (otherEntries.length > 0) {
|
|
4330
|
-
const live = [];
|
|
4331
|
-
const revoked = [];
|
|
4332
|
-
const unverifiable = [];
|
|
4333
|
-
const retired = [];
|
|
4334
|
-
for (const entry of otherEntries) {
|
|
4335
|
-
const identity = await readIdentity(entry.directory);
|
|
4336
|
-
const tombstone = await readAgentTombstone(entry.directory);
|
|
4337
|
-
const otherAgent = entry.agentId ?? path.basename(entry.directory);
|
|
4338
|
-
if (!identity?.api_key || !identity.api_url) {
|
|
4339
|
-
if (tombstone) retired.push(`${otherAgent} (retired ${tombstone.retired_at})`);
|
|
4340
|
-
else unverifiable.push(`${otherAgent} (no stored key/API URL to probe)`);
|
|
4341
|
-
continue;
|
|
4342
|
-
}
|
|
4343
|
-
const suffix = tombstone ? " [tombstoned \u2014 key material still present]" : "";
|
|
4344
|
-
const probe = await (deps.probeHostedIdentity ?? probeHostedAgentIdentity)(
|
|
4345
|
-
identity.api_key,
|
|
4346
|
-
identity.api_url,
|
|
4347
|
-
deps.fetch
|
|
4348
|
-
);
|
|
4349
|
-
if (probe.status === "ok") live.push({ label: `${otherAgent}${suffix}`, entry });
|
|
4350
|
-
else if (probe.status === "unauthorized") revoked.push(`${otherAgent}${suffix}`);
|
|
4351
|
-
else unverifiable.push(`${otherAgent} (${probe.status})${suffix}`);
|
|
4352
|
-
}
|
|
4353
|
-
const parts = [];
|
|
4354
|
-
if (live.length > 0) parts.push(`STILL SPEND-CAPABLE: ${live.map((item) => item.label).join(", ")}`);
|
|
4355
|
-
if (revoked.length > 0) parts.push(`already revoked: ${revoked.join(", ")}`);
|
|
4356
|
-
if (retired.length > 0) parts.push(`tombstoned (keys removed): ${retired.join(", ")}`);
|
|
4357
|
-
if (unverifiable.length > 0) parts.push(`could not verify: ${unverifiable.join(", ")}`);
|
|
4358
|
-
const knownIds = new Set([...inventory].map((e) => e.agentId ?? path.basename(e.directory)));
|
|
4359
|
-
const ledgerDir = input.credentialsDir ? tombstonesDirForAgentDirectory(input.credentialsDir, homeDir) : path.join(homeDir, ".haven", "tombstones");
|
|
4360
|
-
const ghostRecords = (await readTombstoneRecords(ledgerDir)).filter(
|
|
4361
|
-
(rec) => !knownIds.has(rec.agent_id)
|
|
4362
|
-
);
|
|
4363
|
-
if (ghostRecords.length > 0) {
|
|
4364
|
-
parts.push(
|
|
4365
|
-
`retired records (dir removed): ${ghostRecords.map((rec) => `${rec.agent_id} (${rec.reason})`).join(", ")}`
|
|
4366
|
-
);
|
|
4367
|
-
}
|
|
4368
|
-
const supersededLive = live.filter((item) => item.entry.classification !== "wired").map((item) => item.label);
|
|
4369
|
-
const classificationUnreliable = configText === null && runtimeOwnsNoConfig;
|
|
4370
|
-
const supersededLevel = supersededLive.length === 0 ? "ok" : classificationUnreliable ? "advisory" : "failed";
|
|
4371
|
-
checks.push({
|
|
4372
|
-
id: "superseded_agents",
|
|
4373
|
-
label: "Superseded agent credentials",
|
|
4374
|
-
level: supersededLevel,
|
|
4375
|
-
detail: supersededLevel === "failed" ? `${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.` : supersededLevel === "advisory" ? `${otherEntries.length} other credential dir(s) found \u2014 ${parts.join("; ")}. Runtime '${input2.runtime}' has no config file the connector can read, so which of these agents are wired cannot be verified from this machine: a live key here may be an agent you use deliberately, or one a host started before your latest setup is still spending as.` : `${otherEntries.length} other credential dir(s) found \u2014 ${parts.join("; ")}.`,
|
|
4376
|
-
...supersededLevel === "failed" ? {
|
|
4377
|
-
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.`
|
|
4378
|
-
} : supersededLevel === "advisory" ? {
|
|
4379
|
-
repair: `Check ${supersededLive.join(", ")} on the Haven agent page: revoke the ones you no longer use, then remove their director(y/ies) under ~/.haven/agents. Connect never revokes or deletes for you.`
|
|
4380
|
-
} : {}
|
|
4381
|
-
});
|
|
4382
|
-
}
|
|
4383
|
-
const bindings = (await Promise.all(
|
|
4384
|
-
inventory.filter((entry) => entry.classification !== "retired").map(async (entry) => ({ entry, binding: await readMcpServerBinding(entry.directory) }))
|
|
4385
|
-
)).filter((item) => item.binding !== null);
|
|
4386
|
-
const byName = /* @__PURE__ */ new Map();
|
|
4387
|
-
for (const item of bindings) {
|
|
4388
|
-
const list = byName.get(item.binding.server_name) ?? [];
|
|
4389
|
-
list.push(item);
|
|
4390
|
-
byName.set(item.binding.server_name, list);
|
|
4391
|
-
}
|
|
4392
|
-
const rebound = [...byName.entries()].filter(([, items]) => items.length > 1);
|
|
4393
|
-
if (rebound.length > 0) {
|
|
4394
|
-
const parts = rebound.map(([name, items]) => {
|
|
4395
|
-
const ordered = [...items].sort((a, b) => a.binding.bound_at < b.binding.bound_at ? -1 : a.binding.bound_at > b.binding.bound_at ? 1 : 0);
|
|
4396
|
-
const backends = new Set(ordered.map((i) => withoutUserinfo(i.binding.api_url)));
|
|
4397
|
-
return `'${name}': ` + ordered.map((i) => `${i.binding.agent_id} on ${withoutUserinfo(i.binding.api_url)} at ${i.binding.bound_at} [${i.entry.classification}]`).join(" \u2192 ") + (backends.size > 1 ? " (BACKEND CHANGED)" : "");
|
|
4398
|
-
});
|
|
4399
|
-
checks.push({
|
|
4400
|
-
id: "mcp_server_name_rebound",
|
|
4401
|
-
label: "MCP server names bound more than once",
|
|
4402
|
-
level: "advisory",
|
|
4403
|
-
detail: `${rebound.length} MCP server name${rebound.length === 1 ? "" : "s"} changed hands on this machine (locally recorded bindings; the backend's own record is the authority for the same backend): ${parts.join("; ")}. A saved session, script or document naming the server may still mean the earlier agent.`,
|
|
4404
|
-
repair: `Retire the earlier director(y/ies) with ${RERUN} --unwire <dir> to release the name, or keep both and address them by --name.`
|
|
4405
|
-
});
|
|
4406
|
-
}
|
|
4407
|
-
const parkedElsewhere = inventory.filter((entry) => entry.directory !== primaryDirectory && entry.rekeyPending).map((entry) => ({ entry, pending: entry.rekeyPending }));
|
|
4408
|
-
if (parkedElsewhere.length > 0) {
|
|
4409
|
-
const abandoned = parkedElsewhere.filter((item) => item.pending.state !== "pending");
|
|
4410
|
-
const describe = (item) => `${item.entry.slug ?? item.entry.agentId ?? path.basename(item.entry.directory)} (${item.pending.state}, ${item.pending.path})`;
|
|
4411
|
-
checks.push({
|
|
4412
|
-
id: "rekey_pending_elsewhere",
|
|
4413
|
-
label: "Parked re-keys in other credential directories",
|
|
4414
|
-
level: abandoned.length === 0 ? "ok" : "failed",
|
|
4415
|
-
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(", ")}.`,
|
|
4416
|
-
...abandoned.length > 0 ? {
|
|
4417
|
-
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."
|
|
4418
|
-
} : {}
|
|
4419
|
-
});
|
|
4420
|
-
}
|
|
4421
|
-
const signerProcess = primaryChecksById.get("signer_process");
|
|
4422
|
-
if (signerProcess) checks.push(signerProcess);
|
|
4423
|
-
const prune = await (deps.pruneSignerRuntimes ?? pruneSignerRuntimes)({ dryRun: true, measure: false }, { homeDir, credentialsDir: input.credentialsDir });
|
|
4424
|
-
const unused = prune.entries.filter((entry) => entry.action === "would_remove");
|
|
4425
|
-
if (unused.length > 0) {
|
|
4426
|
-
checks.push({
|
|
4427
|
-
id: "signer_runtime_unused",
|
|
4428
|
-
label: "Unused signer-runtime directories",
|
|
4429
|
-
level: "advisory",
|
|
4430
|
-
detail: `${unused.length} signer-runtime director${unused.length === 1 ? "y" : "ies"} under ${prune.root} that no credential directory names: ${unused.map((entry) => entry.key).join(", ")}. Nothing is broken; they are left over from earlier pins or overrides (sizes: --prune-signer-runtimes --dry-run).`,
|
|
4431
|
-
repair: `Run: ${RERUN} --prune-signer-runtimes (add --dry-run to list only).`
|
|
4432
|
-
});
|
|
4433
|
-
}
|
|
4434
|
-
if (resolution.origin === "record") {
|
|
4435
|
-
const rc = checks.find((check) => check.id === "runtime_config");
|
|
4436
|
-
if (rc) {
|
|
4437
|
-
rc.detail += ` (Resolved '${resolution.runtime}' from ${path.join(directory ?? "", exports.CONNECT_OUTCOME_FILENAME)}; pass --runtime to check a different one.)`;
|
|
4438
|
-
}
|
|
4439
|
-
}
|
|
4440
|
-
const restart = normalizedRuntime === null ? false : restartRequiredForRuntime(input2.runtime, deps.env);
|
|
4441
|
-
checks.push({
|
|
4442
|
-
id: "restart",
|
|
4443
|
-
label: "Runtime restart",
|
|
4444
|
-
level: "ok",
|
|
4445
|
-
detail: restart ? "This runtime loads MCP config at startup \u2014 restart it after any repair before expecting the tools to appear." : input2.runtime === "" ? "Runtime is unknown \u2014 whether a restart is needed cannot be determined. Re-run the doctor naming the runtime for a definitive answer." : "No restart requirement known for this runtime."
|
|
4446
|
-
});
|
|
4447
|
-
const wiredChecks = inventory.filter((entry) => entry.classification === "wired").flatMap((entry) => entry.checks);
|
|
4448
|
-
const finalChecks = checks.map(finalizeCheck);
|
|
4449
|
-
const level = rollUpLevel([...finalChecks, ...wiredChecks]);
|
|
4450
|
-
return {
|
|
4451
|
-
version: 1,
|
|
4452
|
-
ok: level !== "failed",
|
|
4453
|
-
level,
|
|
4454
|
-
runtime: input2.runtime,
|
|
4455
|
-
credentialDirectory: primaryDirectory,
|
|
4456
|
-
checks: finalChecks,
|
|
4457
|
-
agents: inventory,
|
|
4458
|
-
...signerCapabilities ? { signerCapabilities } : {}
|
|
4459
|
-
};
|
|
4556
|
+
return referenced;
|
|
4460
4557
|
}
|
|
4461
|
-
|
|
4558
|
+
function rollUpPruneLevel(entries) {
|
|
4559
|
+
if (entries.some((e) => e.level === "failed")) return "failed";
|
|
4560
|
+
if (entries.some((e) => e.level === "advisory")) return "advisory";
|
|
4561
|
+
return "ok";
|
|
4562
|
+
}
|
|
4563
|
+
async function pruneSignerRuntimes(input, deps = {}) {
|
|
4462
4564
|
const homeDir = deps.homeDir ?? os.homedir();
|
|
4463
|
-
const
|
|
4464
|
-
const
|
|
4465
|
-
|
|
4466
|
-
|
|
4467
|
-
}
|
|
4468
|
-
|
|
4469
|
-
|
|
4470
|
-
ok: false,
|
|
4471
|
-
messages: [`No agent credentials found to repair \u2014 run the full setup: ${RERUN} --setup <token>.`]
|
|
4472
|
-
};
|
|
4473
|
-
}
|
|
4474
|
-
const resolution = await resolveDoctorRuntime(input, directory);
|
|
4475
|
-
if (resolution.origin === "record") {
|
|
4476
|
-
messages.push(`Runtime not given \u2014 resolved '${resolution.runtime}' from ${path.join(directory, exports.CONNECT_OUTCOME_FILENAME)}.`);
|
|
4477
|
-
}
|
|
4478
|
-
const runtime = resolution.runtime;
|
|
4479
|
-
const input2 = { ...input, runtime };
|
|
4480
|
-
if (runtime === "") {
|
|
4481
|
-
return {
|
|
4482
|
-
ok: false,
|
|
4483
|
-
messages: [
|
|
4484
|
-
"Runtime is unknown \u2014 no runtime flag was given and the connector record carries no resolvable runtime.",
|
|
4485
|
-
`Repair rewrites the runtime config, so it will not guess. Re-run repair naming the runtime \u2014 one of: ${RUNTIME_FLAG_VALUE_LIST.join(", ")}.`
|
|
4486
|
-
]
|
|
4487
|
-
};
|
|
4488
|
-
}
|
|
4489
|
-
let identity;
|
|
4565
|
+
const root = signerRuntimeRoot(homeDir);
|
|
4566
|
+
const measure = input.measure ?? true;
|
|
4567
|
+
const referenced = await referencedRuntimeDirectories(homeDir, deps.credentialsDir);
|
|
4568
|
+
const pin = await normalizeRuntimePath(path.join(root, exports.MCP_RUNTIME_MANIFEST.signerVersion));
|
|
4569
|
+
const remove = deps.rm ?? (async (directory) => promises.rm(directory, { recursive: true, force: false }));
|
|
4570
|
+
const entries = [];
|
|
4571
|
+
let keys = [];
|
|
4490
4572
|
try {
|
|
4491
|
-
|
|
4573
|
+
keys = (await promises.readdir(root, { withFileTypes: true })).filter((d) => d.isDirectory()).map((d) => d.name).sort();
|
|
4492
4574
|
} catch {
|
|
4493
|
-
return {
|
|
4494
|
-
}
|
|
4495
|
-
if (!identity.api_key || !(identity.hosted_mcp_url || identity.api_url)) {
|
|
4496
|
-
return { ok: false, messages: ["identity.json lacks the stored API key / hosted URL \u2014 re-run the full setup."] };
|
|
4575
|
+
return { version: 1, root, dryRun: input.dryRun, entries, removed: 0, reclaimedBytes: 0, level: "ok" };
|
|
4497
4576
|
}
|
|
4498
|
-
|
|
4499
|
-
|
|
4577
|
+
let removed = 0;
|
|
4578
|
+
let reclaimedBytes = 0;
|
|
4579
|
+
for (const key of keys) {
|
|
4580
|
+
const directory = path.join(root, key);
|
|
4581
|
+
const normalized = await normalizeRuntimePath(directory);
|
|
4582
|
+
const referencedBy = referenced.get(normalized) ?? [];
|
|
4583
|
+
const kind = classifyKey(key);
|
|
4584
|
+
if (referencedBy.length > 0 || normalized === pin) {
|
|
4585
|
+
entries.push({
|
|
4586
|
+
directory,
|
|
4587
|
+
key,
|
|
4588
|
+
kind,
|
|
4589
|
+
bytes: 0,
|
|
4590
|
+
referencedBy,
|
|
4591
|
+
action: "kept",
|
|
4592
|
+
level: "ok",
|
|
4593
|
+
detail: referencedBy.length > 0 ? `kept \u2014 named by ${referencedBy.length} credential director${referencedBy.length === 1 ? "y" : "ies"} (sidecar or wrapper)` : "kept \u2014 the connector's current pinned version (what --repair installs)"
|
|
4594
|
+
});
|
|
4595
|
+
continue;
|
|
4596
|
+
}
|
|
4597
|
+
const bytes = measure ? await directoryBytes(directory) : 0;
|
|
4598
|
+
if (input.dryRun) {
|
|
4599
|
+
entries.push({
|
|
4600
|
+
directory,
|
|
4601
|
+
key,
|
|
4602
|
+
kind,
|
|
4603
|
+
bytes,
|
|
4604
|
+
referencedBy,
|
|
4605
|
+
action: "would_remove",
|
|
4606
|
+
level: "advisory",
|
|
4607
|
+
detail: `would remove \u2014 no credential directory names it (${kind}-keyed)`
|
|
4608
|
+
});
|
|
4609
|
+
continue;
|
|
4610
|
+
}
|
|
4500
4611
|
try {
|
|
4501
|
-
|
|
4502
|
-
|
|
4503
|
-
|
|
4504
|
-
|
|
4505
|
-
|
|
4506
|
-
|
|
4507
|
-
|
|
4508
|
-
|
|
4509
|
-
|
|
4510
|
-
|
|
4511
|
-
|
|
4612
|
+
await remove(directory);
|
|
4613
|
+
removed += 1;
|
|
4614
|
+
reclaimedBytes += bytes;
|
|
4615
|
+
entries.push({ directory, key, kind, bytes, referencedBy, action: "removed", level: "ok", detail: `removed \u2014 no credential directory named it (${kind}-keyed)` });
|
|
4616
|
+
} catch (err) {
|
|
4617
|
+
entries.push({
|
|
4618
|
+
directory,
|
|
4619
|
+
key,
|
|
4620
|
+
kind,
|
|
4621
|
+
bytes,
|
|
4622
|
+
referencedBy,
|
|
4623
|
+
action: "failed",
|
|
4624
|
+
level: "failed",
|
|
4625
|
+
detail: `removal failed: ${err instanceof Error ? err.message : String(err)} \u2014 a signer process may still hold it open; stop it and re-run`
|
|
4626
|
+
});
|
|
4512
4627
|
}
|
|
4513
4628
|
}
|
|
4514
|
-
|
|
4515
|
-
const serverName = existingSidecar?.server_name;
|
|
4516
|
-
const signerPath = path.join(directory, "signer.json");
|
|
4517
|
-
const prepared = await prepareSignerRuntime(
|
|
4518
|
-
{ credentialDirectory: directory, signerPath, homeDir, serverName },
|
|
4519
|
-
{ runCommand: deps.runCommand, env: deps.env }
|
|
4520
|
-
);
|
|
4521
|
-
messages.push(...prepared.messages);
|
|
4522
|
-
const names = serverNamesFor(serverName);
|
|
4523
|
-
messages.push(`Rewriting MCP entries ${names.hosted} / ${names.signer}${serverName ? ` (agent "${serverName}")` : " (unnamed pair)"} \u2014 no other pair is touched.`);
|
|
4524
|
-
const configResult = await writeRuntimeConfig({
|
|
4525
|
-
// Normalized for the WRITE too (#3145 review round 3): `writeRuntimeConfig`
|
|
4526
|
-
// switches on the id, and the raw alias fell to its "manual runtime" arm
|
|
4527
|
-
// — a repair that reported success while writing nothing.
|
|
4528
|
-
runtime: normalizeRuntimeName(input2.runtime) ?? input2.runtime,
|
|
4529
|
-
hostedMcpUrl: identity.hosted_mcp_url ?? `${identity.api_url}/mcp`,
|
|
4530
|
-
apiKey: identity.api_key,
|
|
4531
|
-
identityPath: path.join(directory, "identity.json"),
|
|
4532
|
-
signerPath,
|
|
4533
|
-
credentialDirectory: directory,
|
|
4534
|
-
signerCommand: { command: prepared.command, args: prepared.args },
|
|
4535
|
-
homeDir,
|
|
4536
|
-
mode: "hosted",
|
|
4537
|
-
serverName
|
|
4538
|
-
});
|
|
4539
|
-
messages.push(...configResult.messages);
|
|
4540
|
-
messages.push("Repair complete \u2014 restart the runtime, then verify with --doctor.");
|
|
4541
|
-
return { ok: true, messages };
|
|
4629
|
+
return { version: 1, root, dryRun: input.dryRun, entries, removed, reclaimedBytes, level: rollUpPruneLevel(entries) };
|
|
4542
4630
|
}
|
|
4543
|
-
var
|
|
4544
|
-
|
|
4545
|
-
"src/doctor.ts"() {
|
|
4546
|
-
init_prune_runtimes();
|
|
4631
|
+
var init_prune_runtimes = __esm({
|
|
4632
|
+
"src/prune-runtimes.ts"() {
|
|
4547
4633
|
init_runtime_manifest();
|
|
4548
|
-
init_probes();
|
|
4549
|
-
init_signer_runtime();
|
|
4550
|
-
init_runtime_spec_override();
|
|
4551
|
-
init_config_writers();
|
|
4552
|
-
init_runtime_registry();
|
|
4553
|
-
init_signer_consent();
|
|
4554
|
-
init_tombstone();
|
|
4555
|
-
init_server_names();
|
|
4556
|
-
init_storage();
|
|
4557
|
-
init_redact();
|
|
4558
|
-
RERUN = sdk.connectorRerunCommand();
|
|
4559
4634
|
}
|
|
4560
4635
|
});
|
|
4561
4636
|
|
|
4562
|
-
// src/
|
|
4563
|
-
|
|
4564
|
-
|
|
4565
|
-
|
|
4566
|
-
|
|
4567
|
-
|
|
4568
|
-
|
|
4569
|
-
|
|
4570
|
-
|
|
4571
|
-
|
|
4572
|
-
|
|
4573
|
-
|
|
4574
|
-
|
|
4575
|
-
|
|
4576
|
-
|
|
4577
|
-
|
|
4578
|
-
|
|
4579
|
-
|
|
4580
|
-
|
|
4581
|
-
|
|
4582
|
-
|
|
4583
|
-
|
|
4584
|
-
|
|
4585
|
-
|
|
4586
|
-
|
|
4587
|
-
{
|
|
4588
|
-
runtime: "claude-code",
|
|
4589
|
-
label: "Claude Code",
|
|
4590
|
-
// Claude Code is configured through its own CLI (`claude mcp add-json`),
|
|
4591
|
-
// not by writing a file this module owns — so its evidence is the
|
|
4592
|
-
// client directory, never a config path.
|
|
4593
|
-
configPath: null,
|
|
4594
|
-
markers: [path.join(homeDir, ".claude"), path.join(homeDir, ".claude.json")]
|
|
4595
|
-
},
|
|
4596
|
-
{
|
|
4597
|
-
runtime: "codex-cli",
|
|
4598
|
-
// Both Codex surfaces write the same ~/.codex/config.toml, so they are
|
|
4599
|
-
// ONE candidate. Splitting them would ask the user to answer a question
|
|
4600
|
-
// whose answers are the same write.
|
|
4601
|
-
label: "Codex (CLI or Desktop)",
|
|
4602
|
-
configPath: runtimeConfigPathFor("codex-cli", homeDir),
|
|
4603
|
-
markers: [path.join(homeDir, ".codex")]
|
|
4604
|
-
},
|
|
4605
|
-
{
|
|
4606
|
-
runtime: "cursor",
|
|
4607
|
-
label: "Cursor",
|
|
4608
|
-
configPath: runtimeConfigPathFor("cursor", homeDir),
|
|
4609
|
-
markers: [path.join(homeDir, ".cursor")]
|
|
4610
|
-
},
|
|
4611
|
-
{
|
|
4612
|
-
runtime: "vscode",
|
|
4613
|
-
label: "VS Code",
|
|
4614
|
-
configPath: runtimeConfigPathFor("vscode", homeDir),
|
|
4615
|
-
markers: [path.resolve(cwd, ".vscode")]
|
|
4616
|
-
},
|
|
4617
|
-
{
|
|
4618
|
-
runtime: "vscode-insiders",
|
|
4619
|
-
label: "VS Code Insiders",
|
|
4620
|
-
configPath: runtimeConfigPathFor("vscode-insiders", homeDir),
|
|
4621
|
-
markers: []
|
|
4622
|
-
},
|
|
4623
|
-
{
|
|
4624
|
-
runtime: "claude-desktop",
|
|
4625
|
-
label: "Claude Desktop",
|
|
4626
|
-
configPath: runtimeConfigPathFor("claude-desktop", homeDir),
|
|
4627
|
-
markers: []
|
|
4628
|
-
},
|
|
4629
|
-
{
|
|
4630
|
-
runtime: "hermes",
|
|
4631
|
-
label: "Hermes Agent",
|
|
4632
|
-
configPath: runtimeConfigPathFor("hermes", homeDir),
|
|
4633
|
-
markers: [env.HERMES_HOME ?? path.join(homeDir, ".hermes")]
|
|
4634
|
-
}
|
|
4635
|
-
];
|
|
4636
|
-
return targets.filter((target) => runtimeProfile(target.runtime, {}).canWriteRuntimeConfig);
|
|
4637
|
-
}
|
|
4638
|
-
async function scanInstalledClients(options = {}) {
|
|
4639
|
-
const exists = options.exists ?? pathExists;
|
|
4640
|
-
const targets = installedClientTargets(options.homeDir, options.cwd, options.env ?? process.env);
|
|
4641
|
-
const found = [];
|
|
4642
|
-
for (const target of targets) {
|
|
4643
|
-
if (target.configPath && await exists(target.configPath)) {
|
|
4644
|
-
found.push({
|
|
4645
|
-
runtime: target.runtime,
|
|
4646
|
-
label: target.label,
|
|
4647
|
-
detail: `MCP config found at ${target.configPath}`,
|
|
4648
|
-
configPath: target.configPath,
|
|
4649
|
-
evidence: "config-file"
|
|
4650
|
-
});
|
|
4651
|
-
continue;
|
|
4652
|
-
}
|
|
4653
|
-
for (const marker of target.markers) {
|
|
4654
|
-
if (!await exists(marker)) continue;
|
|
4655
|
-
found.push({
|
|
4656
|
-
runtime: target.runtime,
|
|
4657
|
-
label: target.label,
|
|
4658
|
-
detail: `installed (${marker})`,
|
|
4659
|
-
configPath: target.configPath,
|
|
4660
|
-
evidence: "client-directory"
|
|
4661
|
-
});
|
|
4662
|
-
break;
|
|
4663
|
-
}
|
|
4664
|
-
}
|
|
4665
|
-
return found.sort((a, b) => {
|
|
4666
|
-
if (a.evidence !== b.evidence) return a.evidence === "config-file" ? -1 : 1;
|
|
4667
|
-
return SCAN_ORDER.indexOf(a.runtime) - SCAN_ORDER.indexOf(b.runtime);
|
|
4637
|
+
// src/rekey.ts
|
|
4638
|
+
var rekey_exports = {};
|
|
4639
|
+
__export(rekey_exports, {
|
|
4640
|
+
finishRekey: () => finishRekey,
|
|
4641
|
+
startRekey: () => startRekey
|
|
4642
|
+
});
|
|
4643
|
+
async function startRekey(options, deps = {}) {
|
|
4644
|
+
const now = deps.now ?? (() => Date.now());
|
|
4645
|
+
const stored = await readStoredCredentials(
|
|
4646
|
+
options.serverName,
|
|
4647
|
+
options.agentId,
|
|
4648
|
+
options.credentialsDir
|
|
4649
|
+
);
|
|
4650
|
+
const api = (deps.createApi ?? ((url) => createConnectApiClient(url, void 0, CONNECTOR_CLIENT_IDENTITY)))(stored.apiUrl);
|
|
4651
|
+
const identity = await probeIdentity(api, stored.apiKey, "current");
|
|
4652
|
+
assertRekeyable(identity, stored);
|
|
4653
|
+
const key = (deps.generateKey ?? generateDelegateKey)();
|
|
4654
|
+
const startedAt = new Date(now()).toISOString();
|
|
4655
|
+
const expiresAt = new Date(now() + REKEY_PENDING_TTL_MS).toISOString();
|
|
4656
|
+
await writeRekeyPending(stored.directory, {
|
|
4657
|
+
agent_id: stored.agentId,
|
|
4658
|
+
new_delegate_address: key.address,
|
|
4659
|
+
new_delegate_key: key.privateKey,
|
|
4660
|
+
started_at: startedAt,
|
|
4661
|
+
expires_at: expiresAt
|
|
4668
4662
|
});
|
|
4663
|
+
const finishCommand = [
|
|
4664
|
+
sdk.connectorRerunCommand("--rekey-finish"),
|
|
4665
|
+
options.serverName ? `--name ${options.serverName}` : void 0,
|
|
4666
|
+
"--api-key <the key the dashboard showed you>",
|
|
4667
|
+
options.runtime ? `--runtime ${options.runtime}` : "--runtime <your runtime>"
|
|
4668
|
+
].filter(Boolean).join(" ");
|
|
4669
|
+
return {
|
|
4670
|
+
started: true,
|
|
4671
|
+
agentId: stored.agentId,
|
|
4672
|
+
directory: stored.directory,
|
|
4673
|
+
newDelegateAddress: key.address,
|
|
4674
|
+
expiresAt,
|
|
4675
|
+
messages: [
|
|
4676
|
+
`New signing key generated on this machine for agent ${identity.name || stored.agentId}.`,
|
|
4677
|
+
"",
|
|
4678
|
+
` New signing address: ${key.address}`,
|
|
4679
|
+
"",
|
|
4680
|
+
"The private half stays here \u2014 Haven never receives it, and there is no way to move it",
|
|
4681
|
+
"between machines. That is what keeps the account non-custodial.",
|
|
4682
|
+
"",
|
|
4683
|
+
'Next, on the Haven agent page: choose "Replace signing key" and paste that address.',
|
|
4684
|
+
"When it finishes it shows a new API key ONCE. Come back here and run:",
|
|
4685
|
+
"",
|
|
4686
|
+
` ${finishCommand}`,
|
|
4687
|
+
"",
|
|
4688
|
+
`Nothing has changed yet \u2014 the agent keeps working on its old key until you finish.`,
|
|
4689
|
+
`This pending re-key expires ${expiresAt}.`
|
|
4690
|
+
]
|
|
4691
|
+
};
|
|
4669
4692
|
}
|
|
4670
|
-
function
|
|
4671
|
-
const
|
|
4672
|
-
if (
|
|
4673
|
-
|
|
4674
|
-
}
|
|
4675
|
-
const configured = candidates.filter((candidate) => candidate.evidence === "config-file");
|
|
4676
|
-
return configured.length === 1 ? { installedClients, suggestedRuntime: configured[0].runtime } : { installedClients };
|
|
4677
|
-
}
|
|
4678
|
-
var MAX_PROMPT_ATTEMPTS = 3;
|
|
4679
|
-
async function promptForInstalledClient(candidates, io = defaultPromptIo()) {
|
|
4680
|
-
if (candidates.length === 0) throw noInstalledClientsError();
|
|
4681
|
-
io.write("Haven could not detect which agent runtime this is.\n");
|
|
4682
|
-
io.write("These agent clients are installed on this machine:\n");
|
|
4683
|
-
candidates.forEach((candidate, index) => {
|
|
4684
|
-
io.write(` ${index + 1}) ${candidate.label} \u2014 ${candidate.detail}
|
|
4685
|
-
`);
|
|
4686
|
-
});
|
|
4687
|
-
io.write("Haven writes an API key and a signing key into the client you pick, so pick the one your agent actually runs in.\n");
|
|
4688
|
-
for (let attempt = 0; attempt < MAX_PROMPT_ATTEMPTS; attempt += 1) {
|
|
4689
|
-
const answer = await io.question(`Which one? [1-${candidates.length}] (default 1 \u2014 ${candidates[0].label}): `);
|
|
4690
|
-
if (answer === null) throw promptAbortedError("the prompt was cancelled");
|
|
4691
|
-
const trimmed = answer.trim();
|
|
4692
|
-
if (trimmed === "") return candidates[0].runtime;
|
|
4693
|
-
const picked = Number.parseInt(trimmed, 10);
|
|
4694
|
-
if (Number.isInteger(picked) && picked >= 1 && picked <= candidates.length) {
|
|
4695
|
-
return candidates[picked - 1].runtime;
|
|
4696
|
-
}
|
|
4697
|
-
io.write(`"${trimmed}" is not one of 1-${candidates.length}.
|
|
4698
|
-
`);
|
|
4693
|
+
async function finishRekey(options, deps = {}) {
|
|
4694
|
+
const now = deps.now ?? (() => Date.now());
|
|
4695
|
+
if (!options.newApiKey) {
|
|
4696
|
+
throw new Error(REKEY_FINISH_NEEDS_API_KEY);
|
|
4699
4697
|
}
|
|
4700
|
-
|
|
4701
|
-
|
|
4702
|
-
|
|
4703
|
-
|
|
4704
|
-
if (candidates.length === 0) throw noInstalledClientsError();
|
|
4705
|
-
return promptForInstalledClient(candidates, options.io ?? defaultPromptIo());
|
|
4706
|
-
}
|
|
4707
|
-
function noInstalledClientsError() {
|
|
4708
|
-
return new exports.ConnectError(
|
|
4709
|
-
"runtime_no_installed_clients",
|
|
4710
|
-
"Could not determine the agent runtime: nothing was detected in this environment, and no agent client Haven can configure is installed on this machine. Re-run with --runtime <name> naming the client you want configured, or --runtime other to store credentials and finish the MCP setup by hand.",
|
|
4711
|
-
"rerun_connect_with_explicit_runtime"
|
|
4712
|
-
);
|
|
4713
|
-
}
|
|
4714
|
-
function promptAbortedError(reason) {
|
|
4715
|
-
return new exports.ConnectError(
|
|
4716
|
-
"runtime_prompt_aborted",
|
|
4717
|
-
`Runtime not chosen (${reason}). Nothing was written: no agent was created, no credentials were stored, and the Haven setup token is still unused. Run the connector command again, or pass --runtime <name> to skip the prompt.`,
|
|
4718
|
-
"rerun_connect_and_choose_a_runtime"
|
|
4698
|
+
const stored = await readStoredCredentials(
|
|
4699
|
+
options.serverName,
|
|
4700
|
+
options.agentId,
|
|
4701
|
+
options.credentialsDir
|
|
4719
4702
|
);
|
|
4720
|
-
|
|
4721
|
-
|
|
4722
|
-
|
|
4723
|
-
|
|
4724
|
-
|
|
4725
|
-
} catch {
|
|
4726
|
-
return false;
|
|
4703
|
+
const pending = await readRekeyPending(stored.directory, now());
|
|
4704
|
+
if (pending.agent_id !== stored.agentId) {
|
|
4705
|
+
throw new Error(
|
|
4706
|
+
`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.`
|
|
4707
|
+
);
|
|
4727
4708
|
}
|
|
4728
|
-
|
|
4729
|
-
|
|
4730
|
-
|
|
4731
|
-
|
|
4732
|
-
|
|
4733
|
-
|
|
4734
|
-
let settled = false;
|
|
4735
|
-
const settle = (value) => {
|
|
4736
|
-
if (settled) return;
|
|
4737
|
-
settled = true;
|
|
4738
|
-
rl.close();
|
|
4739
|
-
resolvePromise(value);
|
|
4740
|
-
};
|
|
4741
|
-
rl.once("SIGINT", () => settle(null));
|
|
4742
|
-
rl.once("close", () => settle(null));
|
|
4743
|
-
rl.question(query, (answer) => settle(answer));
|
|
4744
|
-
})
|
|
4745
|
-
};
|
|
4746
|
-
}
|
|
4747
|
-
|
|
4748
|
-
// src/wiring-collision.ts
|
|
4749
|
-
init_server_names();
|
|
4750
|
-
init_signer_runtime();
|
|
4751
|
-
init_storage();
|
|
4752
|
-
init_tombstone();
|
|
4753
|
-
async function detectWiringCollision(input) {
|
|
4754
|
-
const root = defaultCredentialRoot(input.credentialsDir);
|
|
4755
|
-
let entries = [];
|
|
4756
|
-
try {
|
|
4757
|
-
entries = await promises.readdir(root);
|
|
4758
|
-
} catch {
|
|
4759
|
-
return null;
|
|
4709
|
+
const api = (deps.createApi ?? ((url) => createConnectApiClient(url, void 0, CONNECTOR_CLIENT_IDENTITY)))(stored.apiUrl);
|
|
4710
|
+
const identity = await probeIdentity(api, options.newApiKey, "new");
|
|
4711
|
+
if (identity.id !== stored.agentId) {
|
|
4712
|
+
throw new Error(
|
|
4713
|
+
`That API key belongs to agent ${identity.id}, not ${stored.agentId}. Nothing was changed.`
|
|
4714
|
+
);
|
|
4760
4715
|
}
|
|
4761
|
-
const
|
|
4762
|
-
const
|
|
4763
|
-
|
|
4764
|
-
|
|
4765
|
-
|
|
4766
|
-
|
|
4767
|
-
|
|
4768
|
-
|
|
4769
|
-
|
|
4716
|
+
const onChain = (identity.delegate_address ?? "").toLowerCase();
|
|
4717
|
+
const expected = pending.new_delegate_address.toLowerCase();
|
|
4718
|
+
if (onChain !== expected) {
|
|
4719
|
+
throw new Error(
|
|
4720
|
+
`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.`
|
|
4721
|
+
);
|
|
4722
|
+
}
|
|
4723
|
+
await rewriteCredentialFiles({
|
|
4724
|
+
baseDir: options.credentialsDir,
|
|
4725
|
+
agentId: stored.agentId,
|
|
4726
|
+
serverName: options.serverName,
|
|
4727
|
+
apiKey: options.newApiKey,
|
|
4728
|
+
delegateKey: pending.new_delegate_key,
|
|
4729
|
+
delegateAddress: pending.new_delegate_address,
|
|
4730
|
+
// The stored value (already new-name-first, from the credential-FILE
|
|
4731
|
+
// permanent fallback) wins; the hosted identity's `account_address` is a
|
|
4732
|
+
// LIVE server read, which as of #2914 emits only that name.
|
|
4733
|
+
accountAddress: stored.accountAddress ?? identity.account_address ?? void 0,
|
|
4734
|
+
chainId: stored.chainId ?? identity.chain_id ?? void 0,
|
|
4735
|
+
network: stored.network,
|
|
4736
|
+
agentBudget: stored.agentBudget,
|
|
4737
|
+
apiUrl: stored.apiUrl,
|
|
4738
|
+
hostedMcpUrl: stored.hostedMcpUrl,
|
|
4739
|
+
x402BindingSigner: stored.x402BindingSigner,
|
|
4740
|
+
warn: deps.log
|
|
4741
|
+
});
|
|
4742
|
+
await clearRekeyPending(stored.directory);
|
|
4743
|
+
const names = serverNamesFor(options.serverName);
|
|
4744
|
+
const messages = [
|
|
4745
|
+
`Agent ${identity.name || stored.agentId} is now on its new signing key.`,
|
|
4746
|
+
` Signing address: ${pending.new_delegate_address}`,
|
|
4747
|
+
` Credentials: ${stored.directory} (rewritten in place)`,
|
|
4748
|
+
` MCP servers: ${names.hosted} / ${names.signer} (unchanged names)`
|
|
4749
|
+
];
|
|
4750
|
+
let configRewritten = false;
|
|
4751
|
+
if (options.runtime) {
|
|
4752
|
+
const prepared = await (deps.prepareSigner ?? prepareSignerRuntime)(
|
|
4753
|
+
{
|
|
4754
|
+
credentialDirectory: stored.directory,
|
|
4755
|
+
signerPath: `${stored.directory}/signer.json`,
|
|
4756
|
+
homeDir: options.homeDir
|
|
4757
|
+
},
|
|
4758
|
+
{ runCommand: deps.runCommand, env: deps.env }
|
|
4759
|
+
);
|
|
4760
|
+
const result = await (deps.writeConfig ?? writeHostedRuntimeConfig)(
|
|
4761
|
+
{ runCommand: deps.runCommand, homeDir: options.homeDir },
|
|
4762
|
+
{
|
|
4763
|
+
runtime: options.runtime,
|
|
4764
|
+
hostedMcpUrl: stored.hostedMcpUrl,
|
|
4765
|
+
apiKey: options.newApiKey,
|
|
4766
|
+
identityPath: `${stored.directory}/identity.json`,
|
|
4767
|
+
signerPath: `${stored.directory}/signer.json`,
|
|
4768
|
+
credentialDirectory: stored.directory,
|
|
4769
|
+
serverName: options.serverName
|
|
4770
|
+
},
|
|
4771
|
+
{ command: prepared.command, args: prepared.args }
|
|
4772
|
+
);
|
|
4773
|
+
configRewritten = result.hostedConfigured;
|
|
4774
|
+
if (prepared.runtimeSpecOverride) {
|
|
4775
|
+
messages.push(
|
|
4776
|
+
` Signer runtime: RUNTIME SPEC OVERRIDE ACTIVE \u2014 ${describeRuntimeSpecOverride(prepared.runtimeSpecOverride.specs)} (NOT the pinned manifest; installed into ${prepared.runtimeDirectory})`
|
|
4777
|
+
);
|
|
4770
4778
|
}
|
|
4771
|
-
|
|
4772
|
-
|
|
4773
|
-
|
|
4774
|
-
|
|
4775
|
-
|
|
4776
|
-
|
|
4779
|
+
messages.push(` Config: ${result.target}`);
|
|
4780
|
+
messages.push(...result.messages.map((line) => ` ${line}`));
|
|
4781
|
+
if (!configRewritten) {
|
|
4782
|
+
messages.push(
|
|
4783
|
+
"",
|
|
4784
|
+
"WARNING: the MCP config was NOT updated, so it still carries the OLD API key and every",
|
|
4785
|
+
`wired host will fail with 401. Fix the cause above and re-run with --runtime ${options.runtime},`,
|
|
4786
|
+
"or update the config by hand. The credential files on disk are already on the new key."
|
|
4787
|
+
);
|
|
4777
4788
|
}
|
|
4778
|
-
|
|
4779
|
-
|
|
4780
|
-
|
|
4781
|
-
|
|
4782
|
-
|
|
4789
|
+
} else {
|
|
4790
|
+
messages.push(
|
|
4791
|
+
"",
|
|
4792
|
+
"NOTE: no --runtime was given, so the MCP config still carries the OLD API key and every",
|
|
4793
|
+
"wired host will fail with 401. Re-run with --runtime <name> to rewrite it."
|
|
4794
|
+
);
|
|
4783
4795
|
}
|
|
4784
|
-
if (superseded.length === 0) return null;
|
|
4785
4796
|
return {
|
|
4786
|
-
|
|
4787
|
-
|
|
4797
|
+
finished: true,
|
|
4798
|
+
agentId: stored.agentId,
|
|
4799
|
+
directory: stored.directory,
|
|
4800
|
+
newDelegateAddress: pending.new_delegate_address,
|
|
4801
|
+
serverNames: { hosted: names.hosted, signer: names.signer },
|
|
4802
|
+
configRewritten,
|
|
4803
|
+
messages
|
|
4788
4804
|
};
|
|
4789
4805
|
}
|
|
4790
|
-
function
|
|
4791
|
-
let base = agentName.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").replace(/-{2,}/g, "-").slice(0, 32).replace(/-+$/g, "");
|
|
4792
|
-
if (!slugIsValid(base)) base = "agent";
|
|
4793
|
-
if (!taken.has(base)) return base;
|
|
4794
|
-
for (let n = 2; n < 1e3; n += 1) {
|
|
4795
|
-
const suffix = `-${n}`;
|
|
4796
|
-
const candidate = `${base.slice(0, 32 - suffix.length).replace(/-+$/g, "")}${suffix}`;
|
|
4797
|
-
if (slugIsValid(candidate) && !taken.has(candidate)) return candidate;
|
|
4798
|
-
}
|
|
4799
|
-
throw new Error(`Could not propose an unused server name for ${JSON.stringify(agentName)}.`);
|
|
4800
|
-
}
|
|
4801
|
-
function slugIsValid(slug) {
|
|
4806
|
+
async function probeIdentity(api, apiKey, which) {
|
|
4802
4807
|
try {
|
|
4803
|
-
|
|
4804
|
-
|
|
4805
|
-
|
|
4806
|
-
|
|
4807
|
-
|
|
4808
|
-
|
|
4809
|
-
|
|
4810
|
-
async function promptWiringCollisionResolution(collision, agentName, io) {
|
|
4811
|
-
const ids = collision.superseded.map((entry) => entry.agentId).join(", ");
|
|
4812
|
-
io.write(`This machine is already wired to a Haven agent with a live key: ${ids}.
|
|
4813
|
-
`);
|
|
4814
|
-
io.write(`Setting up "${agentName}" on the bare haven / haven-signer pair would replace that wiring.
|
|
4815
|
-
`);
|
|
4816
|
-
io.write(" r) replace \u2014 re-point haven / haven-signer at the new agent and retire the previous directory locally\n");
|
|
4817
|
-
io.write(" (tombstoned, local key files removed; you still revoke it on the Haven agent page)\n");
|
|
4818
|
-
io.write(` a) alongside \u2014 install as a named agent (suggested: ${collision.suggestedServerName}) with its own
|
|
4819
|
-
`);
|
|
4820
|
-
io.write(` haven-<name> / haven-signer-<name> pair, leaving the current wiring untouched
|
|
4821
|
-
`);
|
|
4822
|
-
io.write(" q) quit \u2014 nothing is written and the setup token stays unused\n");
|
|
4823
|
-
for (let attempt = 0; attempt < MAX_PROMPT_ATTEMPTS2; attempt += 1) {
|
|
4824
|
-
const answer = await io.question("Replace, install alongside, or quit? [r/a/q]: ");
|
|
4825
|
-
if (answer === null) return { action: "abort" };
|
|
4826
|
-
const trimmed = answer.trim().toLowerCase();
|
|
4827
|
-
if (trimmed === "r" || trimmed === "replace") return { action: "replace" };
|
|
4828
|
-
if (trimmed === "q" || trimmed === "quit") return { action: "abort" };
|
|
4829
|
-
if (trimmed === "a" || trimmed === "alongside") {
|
|
4830
|
-
const typed = await io.question(`Server name [${collision.suggestedServerName}]: `);
|
|
4831
|
-
if (typed === null) return { action: "abort" };
|
|
4832
|
-
const serverName = typed.trim() === "" ? collision.suggestedServerName : typed.trim();
|
|
4833
|
-
try {
|
|
4834
|
-
assertValidServerSlug(serverName);
|
|
4835
|
-
} catch (err) {
|
|
4836
|
-
io.write(`${err instanceof Error ? err.message : String(err)}
|
|
4837
|
-
`);
|
|
4838
|
-
continue;
|
|
4839
|
-
}
|
|
4840
|
-
return { action: "alongside", serverName };
|
|
4808
|
+
return await api.getAgentIdentity(apiKey);
|
|
4809
|
+
} catch (err) {
|
|
4810
|
+
const status = err?.status;
|
|
4811
|
+
if (status === 401 || status === 403) {
|
|
4812
|
+
throw new Error(
|
|
4813
|
+
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."
|
|
4814
|
+
);
|
|
4841
4815
|
}
|
|
4842
|
-
|
|
4843
|
-
`
|
|
4816
|
+
throw new Error(
|
|
4817
|
+
`Could not reach Haven to check this agent (${redactSecrets(
|
|
4818
|
+
err instanceof Error ? err.message : String(err)
|
|
4819
|
+
)}). Nothing was changed.`
|
|
4820
|
+
);
|
|
4844
4821
|
}
|
|
4845
|
-
return { action: "abort" };
|
|
4846
4822
|
}
|
|
4847
|
-
|
|
4848
|
-
|
|
4849
|
-
|
|
4850
|
-
|
|
4851
|
-
|
|
4852
|
-
return false;
|
|
4823
|
+
function assertRekeyable(identity, stored) {
|
|
4824
|
+
if (identity.id !== stored.agentId) {
|
|
4825
|
+
throw new Error(
|
|
4826
|
+
`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.`
|
|
4827
|
+
);
|
|
4853
4828
|
}
|
|
4854
|
-
|
|
4855
|
-
|
|
4856
|
-
|
|
4857
|
-
|
|
4858
|
-
init_tombstone();
|
|
4859
|
-
init_local_mcp_runtime();
|
|
4860
|
-
init_runtime_manifest();
|
|
4861
|
-
var CONNECTOR_VERSION = "0.0.0-dev.202609250737.3bd5a51";
|
|
4862
|
-
var CONNECT_OUTCOME_SCHEMA_VERSION = 1;
|
|
4863
|
-
var failureOutcomesByError = /* @__PURE__ */ new WeakMap();
|
|
4864
|
-
function failureOutcomeFor(runtimeHint, error) {
|
|
4865
|
-
if (error !== null && typeof error === "object") {
|
|
4866
|
-
const recorded = failureOutcomesByError.get(error);
|
|
4867
|
-
if (recorded) return recorded;
|
|
4829
|
+
if (identity.execution_rail === "legacy") {
|
|
4830
|
+
throw new Error(
|
|
4831
|
+
`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.`
|
|
4832
|
+
);
|
|
4868
4833
|
}
|
|
4869
|
-
|
|
4870
|
-
|
|
4871
|
-
|
|
4872
|
-
|
|
4873
|
-
try {
|
|
4874
|
-
return await executeConnect(options, deps, trace);
|
|
4875
|
-
} catch (err) {
|
|
4876
|
-
const outcome = failedConnectOutcome(trace.runtime ?? options.runtime, err);
|
|
4877
|
-
if (err !== null && typeof err === "object") failureOutcomesByError.set(err, outcome);
|
|
4878
|
-
if (trace.directory) await recordConnectOutcome(deps, trace.directory, outcome);
|
|
4879
|
-
throw err;
|
|
4834
|
+
if (identity.status === "revoked") {
|
|
4835
|
+
throw new Error(
|
|
4836
|
+
`Agent ${identity.name || identity.id} is revoked. Re-keying would hand a revoked agent fresh credentials \u2014 create a new agent instead.`
|
|
4837
|
+
);
|
|
4880
4838
|
}
|
|
4881
4839
|
}
|
|
4882
|
-
|
|
4883
|
-
|
|
4884
|
-
|
|
4885
|
-
|
|
4886
|
-
|
|
4840
|
+
var init_rekey = __esm({
|
|
4841
|
+
"src/rekey.ts"() {
|
|
4842
|
+
init_api();
|
|
4843
|
+
init_runtime_install();
|
|
4844
|
+
init_signer_runtime();
|
|
4845
|
+
init_runtime_spec_override();
|
|
4846
|
+
init_key();
|
|
4847
|
+
init_redact();
|
|
4848
|
+
init_rekey_messages();
|
|
4849
|
+
init_runtime();
|
|
4850
|
+
init_server_names();
|
|
4851
|
+
init_storage();
|
|
4887
4852
|
}
|
|
4888
|
-
}
|
|
4889
|
-
|
|
4890
|
-
|
|
4891
|
-
|
|
4892
|
-
|
|
4893
|
-
|
|
4894
|
-
|
|
4895
|
-
|
|
4896
|
-
|
|
4897
|
-
|
|
4898
|
-
|
|
4899
|
-
|
|
4900
|
-
|
|
4901
|
-
|
|
4902
|
-
|
|
4903
|
-
|
|
4904
|
-
|
|
4905
|
-
selfReported: options.runtimeSelfReport,
|
|
4906
|
-
promptForRuntime: runtimeSelectionPrompt(options, deps)
|
|
4907
|
-
});
|
|
4908
|
-
if (!selection.runtime) {
|
|
4909
|
-
const hint = await installedClientHintFor(deps);
|
|
4910
|
-
throw new exports.ConnectError(
|
|
4911
|
-
"runtime_undetermined",
|
|
4912
|
-
`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: ${exports.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. ` + installedClientProse(hint) + "Nothing was written and the Haven setup token is still unused.",
|
|
4913
|
-
"rerun_connect_with_explicit_runtime",
|
|
4914
|
-
// #2091: the values must ride structurally too. The backend's setup
|
|
4915
|
-
// prompt permits a retry only with "one of the values that refusal
|
|
4916
|
-
// lists" — and --json discards prose, so a prose-only list deadlocked
|
|
4917
|
-
// every automation run in an undetected runtime (Codex in the field:
|
|
4918
|
-
// npx needs network, Codex runs network commands unsandboxed, and the
|
|
4919
|
-
// unsandboxed path carries none of the CODEX_* detection vars).
|
|
4920
|
-
//
|
|
4921
|
-
// #2174: the list alone still leaves the retry a nine-value guess. The
|
|
4922
|
-
// scan below narrows it to what is actually on this machine — as a
|
|
4923
|
-
// HINT. It does not select, and this stays a refusal: see
|
|
4924
|
-
// `installedClientHint`.
|
|
4925
|
-
{ allowedRuntimes: RUNTIME_FLAG_VALUE_LIST, ...hint }
|
|
4853
|
+
});
|
|
4854
|
+
|
|
4855
|
+
// src/rekey-restart.ts
|
|
4856
|
+
var rekey_restart_exports = {};
|
|
4857
|
+
__export(rekey_restart_exports, {
|
|
4858
|
+
restartGuidance: () => restartGuidance
|
|
4859
|
+
});
|
|
4860
|
+
function restartGuidance(runtime) {
|
|
4861
|
+
const profile = runtime ? BY_RUNTIME[runtime] : void 0;
|
|
4862
|
+
const lines = ["The new key is only live in a process that started after now.", ""];
|
|
4863
|
+
if (profile) {
|
|
4864
|
+
lines.push(profile.how);
|
|
4865
|
+
for (const command of profile.commands) lines.push(` ${command}`);
|
|
4866
|
+
if (profile.commands.length > 0) lines.push("");
|
|
4867
|
+
} else {
|
|
4868
|
+
lines.push(
|
|
4869
|
+
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."
|
|
4926
4870
|
);
|
|
4871
|
+
lines.push("");
|
|
4927
4872
|
}
|
|
4928
|
-
|
|
4929
|
-
|
|
4930
|
-
|
|
4931
|
-
|
|
4932
|
-
|
|
4933
|
-
|
|
4934
|
-
|
|
4935
|
-
|
|
4936
|
-
|
|
4937
|
-
|
|
4938
|
-
|
|
4939
|
-
|
|
4940
|
-
|
|
4941
|
-
|
|
4942
|
-
|
|
4873
|
+
lines.push(SWEEP);
|
|
4874
|
+
return { commands: profile?.commands ?? [], lines };
|
|
4875
|
+
}
|
|
4876
|
+
var SWEEP, BY_RUNTIME;
|
|
4877
|
+
var init_rekey_restart = __esm({
|
|
4878
|
+
"src/rekey-restart.ts"() {
|
|
4879
|
+
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.";
|
|
4880
|
+
BY_RUNTIME = {
|
|
4881
|
+
"claude-code": {
|
|
4882
|
+
commands: ["claude --continue"],
|
|
4883
|
+
how: "Exit this Claude Code session and start a new one:"
|
|
4884
|
+
},
|
|
4885
|
+
"codex-cli": {
|
|
4886
|
+
commands: ["codex resume --last"],
|
|
4887
|
+
how: "Start a fresh Codex CLI session:"
|
|
4888
|
+
},
|
|
4889
|
+
"codex-desktop": {
|
|
4890
|
+
commands: [],
|
|
4891
|
+
how: "Quit Codex Desktop completely (not just the window) and reopen it."
|
|
4892
|
+
},
|
|
4893
|
+
"claude-desktop": {
|
|
4894
|
+
commands: [],
|
|
4895
|
+
how: "Quit Claude Desktop completely (not just the window) and reopen it."
|
|
4896
|
+
},
|
|
4897
|
+
hermes: {
|
|
4898
|
+
commands: ["systemctl --user restart hermes-gateway", "/restart"],
|
|
4899
|
+
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:"
|
|
4900
|
+
},
|
|
4901
|
+
cursor: {
|
|
4902
|
+
commands: [],
|
|
4903
|
+
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").'
|
|
4904
|
+
},
|
|
4905
|
+
vscode: {
|
|
4906
|
+
commands: [],
|
|
4907
|
+
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").'
|
|
4908
|
+
},
|
|
4909
|
+
"vscode-insiders": {
|
|
4910
|
+
commands: [],
|
|
4911
|
+
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").'
|
|
4912
|
+
}
|
|
4913
|
+
};
|
|
4943
4914
|
}
|
|
4944
|
-
|
|
4945
|
-
|
|
4915
|
+
});
|
|
4916
|
+
|
|
4917
|
+
// src/doctor.ts
|
|
4918
|
+
var doctor_exports = {};
|
|
4919
|
+
__export(doctor_exports, {
|
|
4920
|
+
describeAccountAddressKey: () => describeAccountAddressKey,
|
|
4921
|
+
rollUpLevel: () => rollUpLevel,
|
|
4922
|
+
runDoctor: () => runDoctor,
|
|
4923
|
+
runRepair: () => runRepair
|
|
4924
|
+
});
|
|
4925
|
+
function finalizeCheck(check) {
|
|
4926
|
+
return { ...check, ok: check.level !== "failed" };
|
|
4927
|
+
}
|
|
4928
|
+
function rollUpLevel(checks) {
|
|
4929
|
+
if (checks.some((check) => check.level === "failed")) return "failed";
|
|
4930
|
+
if (checks.some((check) => check.level === "advisory")) return "advisory";
|
|
4931
|
+
return "ok";
|
|
4932
|
+
}
|
|
4933
|
+
function runtimeFlagFor(runtime) {
|
|
4934
|
+
return normalizeRuntimeName(runtime) ? ` --runtime ${runtime}` : "";
|
|
4935
|
+
}
|
|
4936
|
+
function repairCommandFor(runtime, suffix = "") {
|
|
4937
|
+
if (normalizeRuntimeName(runtime)) return `Run: ${RERUN} --doctor --repair --runtime ${runtime}${suffix}`;
|
|
4938
|
+
return `Run: ${RERUN} --doctor --repair --runtime <runtime>${suffix.replace(/\.$/, "")} \u2014 --repair needs the runtime named; one of: ${RUNTIME_FLAG_VALUE_LIST.join(", ")}.`;
|
|
4939
|
+
}
|
|
4940
|
+
async function resolveDoctorRuntime(input, directory) {
|
|
4941
|
+
const explicit = input.runtime.trim();
|
|
4942
|
+
if (explicit) return { runtime: explicit, origin: "flag" };
|
|
4943
|
+
if (directory) {
|
|
4944
|
+
const recorded = await readConnectOutcomeRuntime(directory);
|
|
4945
|
+
if (recorded !== null && normalizeRuntimeName(recorded)) {
|
|
4946
|
+
return { runtime: recorded, origin: "record" };
|
|
4947
|
+
}
|
|
4946
4948
|
}
|
|
4947
|
-
|
|
4948
|
-
|
|
4949
|
+
return { runtime: "", origin: "unknown" };
|
|
4950
|
+
}
|
|
4951
|
+
async function discoverCredentialDirectory(homeDir, explicit) {
|
|
4952
|
+
const root = explicit ? path.dirname(explicit) : path.join(homeDir, ".haven", "agents");
|
|
4953
|
+
let entries = [];
|
|
4949
4954
|
try {
|
|
4950
|
-
|
|
4951
|
-
|
|
4952
|
-
|
|
4953
|
-
runtime
|
|
4954
|
-
});
|
|
4955
|
-
} catch (err) {
|
|
4956
|
-
throw deadSetupTokenError(err) ?? err;
|
|
4957
|
-
}
|
|
4958
|
-
assertSetupChallengeIsUsable(setup.challenge.expires_at);
|
|
4959
|
-
printSetupSummary(setup, log);
|
|
4960
|
-
await preflightStorage({ baseDir: options.credentialsDir, warn: log });
|
|
4961
|
-
if (options.serverName) {
|
|
4962
|
-
assertValidServerSlug(options.serverName);
|
|
4963
|
-
await assertServerSlugAvailable(options.serverName, options.credentialsDir);
|
|
4955
|
+
entries = await promises.readdir(root);
|
|
4956
|
+
} catch {
|
|
4957
|
+
return explicit ? { directory: explicit, others: [], parkedOnly: /* @__PURE__ */ new Set() } : { others: [], parkedOnly: /* @__PURE__ */ new Set() };
|
|
4964
4958
|
}
|
|
4965
|
-
|
|
4966
|
-
|
|
4967
|
-
|
|
4968
|
-
|
|
4969
|
-
const
|
|
4970
|
-
|
|
4971
|
-
|
|
4972
|
-
|
|
4973
|
-
|
|
4974
|
-
|
|
4975
|
-
|
|
4976
|
-
|
|
4977
|
-
|
|
4978
|
-
|
|
4979
|
-
|
|
4980
|
-
|
|
4981
|
-
|
|
4982
|
-
|
|
4983
|
-
await assertServerSlugAvailable(serverName, options.credentialsDir);
|
|
4984
|
-
log(`Installing alongside the existing wiring as a named agent: ${serverNamesFor(serverName).hosted} / ${serverNamesFor(serverName).signer}.`);
|
|
4959
|
+
const candidates = [];
|
|
4960
|
+
const tombstonedOnly = [];
|
|
4961
|
+
const parkedOnly = [];
|
|
4962
|
+
for (const entry of entries) {
|
|
4963
|
+
const directory = path.join(root, entry);
|
|
4964
|
+
try {
|
|
4965
|
+
const s = await promises.stat(path.join(directory, "identity.json"));
|
|
4966
|
+
candidates.push({ directory, mtimeMs: s.mtimeMs });
|
|
4967
|
+
} catch {
|
|
4968
|
+
try {
|
|
4969
|
+
await promises.stat(path.join(directory, TOMBSTONE_FILENAME));
|
|
4970
|
+
tombstonedOnly.push(directory);
|
|
4971
|
+
} catch {
|
|
4972
|
+
try {
|
|
4973
|
+
await promises.stat(path.join(directory, REKEY_PENDING_FILENAME));
|
|
4974
|
+
parkedOnly.push(directory);
|
|
4975
|
+
} catch {
|
|
4976
|
+
}
|
|
4985
4977
|
}
|
|
4986
4978
|
}
|
|
4987
4979
|
}
|
|
4988
|
-
const
|
|
4989
|
-
|
|
4990
|
-
|
|
4991
|
-
|
|
4992
|
-
|
|
4993
|
-
|
|
4980
|
+
const parkedOnlySet = new Set(parkedOnly);
|
|
4981
|
+
candidates.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
|
4982
|
+
if (explicit) {
|
|
4983
|
+
return {
|
|
4984
|
+
directory: explicit,
|
|
4985
|
+
others: [...candidates.map((c) => c.directory), ...tombstonedOnly, ...parkedOnly].filter((d) => d !== explicit),
|
|
4986
|
+
parkedOnly: parkedOnlySet
|
|
4987
|
+
};
|
|
4994
4988
|
}
|
|
4995
|
-
|
|
4996
|
-
|
|
4997
|
-
const holders = (await listMcpServerBindings(options.credentialsDir)).filter(({ binding }) => binding.server_name === hostedNameForRun).sort((a, b) => a.binding.bound_at < b.binding.bound_at ? 1 : a.binding.bound_at > b.binding.bound_at ? -1 : 0);
|
|
4998
|
-
const newest = holders[0];
|
|
4999
|
-
if (newest) {
|
|
5000
|
-
const { binding, directory } = newest;
|
|
5001
|
-
const backendChanged = withoutUserinfo(binding.api_url) !== withoutUserinfo(options.apiBaseUrl);
|
|
5002
|
-
const previousApiUrl = withoutUserinfo(binding.api_url);
|
|
5003
|
-
reboundFrom = { server_name: binding.server_name, agent_id: binding.agent_id, api_url: previousApiUrl, bound_at: binding.bound_at, backend_changed: backendChanged };
|
|
5004
|
-
const beingReplaced = replacing?.superseded.some((entry) => entry.directory === directory) ?? false;
|
|
5005
|
-
log(
|
|
5006
|
-
`Heads-up: the MCP server name '${binding.server_name}' was bound to agent ${binding.agent_id} on ${previousApiUrl} at ${binding.bound_at} (locally recorded${holders.length > 1 ? `; ${holders.length - 1} older record${holders.length > 2 ? "s" : ""} also claim${holders.length > 2 ? "" : "s"} it` : ""}). ` + (beingReplaced ? `This run replaces that wiring, as you chose, with a new agent on ${withoutUserinfo(options.apiBaseUrl)}` : `This run rebinds it to a new agent on ${withoutUserinfo(options.apiBaseUrl)}`) + (backendChanged ? " \u2014 a DIFFERENT backend: any saved session, script or document naming this MCP server now resolves to a different backend and agent." : ".")
|
|
5007
|
-
);
|
|
4989
|
+
if (candidates.length === 0 && tombstonedOnly.length === 0 && parkedOnly.length === 0) {
|
|
4990
|
+
return { others: [], parkedOnly: parkedOnlySet };
|
|
5008
4991
|
}
|
|
5009
|
-
|
|
5010
|
-
|
|
5011
|
-
|
|
5012
|
-
|
|
5013
|
-
|
|
5014
|
-
|
|
5015
|
-
|
|
5016
|
-
|
|
5017
|
-
|
|
5018
|
-
|
|
5019
|
-
|
|
5020
|
-
challengeId: setup.challenge.id,
|
|
5021
|
-
delegateAddress: localKey.address,
|
|
5022
|
-
proofSignature,
|
|
5023
|
-
apiKeyHash: hashAgentApiKey(localApiKey),
|
|
5024
|
-
apiKeyPrefix: agentApiKeyPrefix(localApiKey),
|
|
5025
|
-
// #1878: report the pair we are ACTUALLY wiring, bare pair included, so
|
|
5026
|
-
// the dashboard can name it. Derived here rather than sent as the raw
|
|
5027
|
-
// slug — `serverNamesFor` is the one place the naming rule lives, and
|
|
5028
|
-
// the hosted name is what a user pastes into an MCP config.
|
|
5029
|
-
mcpServerName: serverNamesFor(serverName).hosted,
|
|
5030
|
-
// #2528: 'prose' is the default because it is what a caller who says
|
|
5031
|
-
// nothing is doing — the library entry point is not a --json run.
|
|
5032
|
-
runMode: options.runMode ?? "prose",
|
|
5033
|
-
connectorContext: {
|
|
5034
|
-
environment_label: options.environmentLabel ?? "Local workspace",
|
|
5035
|
-
config_target: installCapabilities.canWriteRuntimeConfig ? "agent runtime MCP config" : "local credential files"
|
|
5036
|
-
},
|
|
5037
|
-
installCapabilities
|
|
5038
|
-
});
|
|
5039
|
-
} catch (err) {
|
|
5040
|
-
const dead = deadSetupTokenError(err);
|
|
5041
|
-
if (dead) throw dead;
|
|
5042
|
-
if (isExpiredSetupChallenge(err)) {
|
|
5043
|
-
throw new Error(
|
|
5044
|
-
"The Haven setup challenge expired while connecting. Return to Haven, start a fresh connection, and run its new connector command. Do not reuse or paste credentials."
|
|
5045
|
-
);
|
|
4992
|
+
return {
|
|
4993
|
+
directory: candidates[0]?.directory,
|
|
4994
|
+
others: [...candidates.slice(1).map((c) => c.directory), ...tombstonedOnly, ...parkedOnly],
|
|
4995
|
+
parkedOnly: parkedOnlySet
|
|
4996
|
+
};
|
|
4997
|
+
}
|
|
4998
|
+
function agentIsWired(configText, names, slug, identity, sidecar, isPrimary, bareOwnerExists) {
|
|
4999
|
+
if (configText === null) return isPrimary;
|
|
5000
|
+
if (slug) {
|
|
5001
|
+
for (const name of [names.hosted, names.codexHosted, names.signer, names.codexSigner]) {
|
|
5002
|
+
if (new RegExp(`(^|[."'\\s\\[])${name}(["'\\]:\\s]|$)`, "m").test(configText)) return true;
|
|
5046
5003
|
}
|
|
5047
|
-
|
|
5004
|
+
return false;
|
|
5048
5005
|
}
|
|
5049
|
-
|
|
5050
|
-
|
|
5051
|
-
|
|
5052
|
-
|
|
5053
|
-
|
|
5054
|
-
|
|
5055
|
-
|
|
5056
|
-
|
|
5057
|
-
|
|
5058
|
-
|
|
5059
|
-
|
|
5060
|
-
|
|
5061
|
-
|
|
5062
|
-
|
|
5063
|
-
|
|
5064
|
-
|
|
5065
|
-
|
|
5066
|
-
apiUrl: options.apiBaseUrl,
|
|
5067
|
-
hostedMcpUrl: registration.hosted_mcp_url,
|
|
5068
|
-
x402BindingSigner: setup.x402_binding_signer ?? void 0,
|
|
5069
|
-
warn: log
|
|
5070
|
-
});
|
|
5071
|
-
trace.directory = credentialPaths.directory;
|
|
5072
|
-
try {
|
|
5073
|
-
const bindingRecord = {
|
|
5074
|
-
version: 1,
|
|
5075
|
-
server_name: hostedNameForRun,
|
|
5076
|
-
signer_name: serverNamesFor(serverName).signer,
|
|
5077
|
-
agent_id: registration.agent_id,
|
|
5078
|
-
api_url: withoutUserinfo(options.apiBaseUrl),
|
|
5079
|
-
// never persist `user:pass@` (#3154 doc review r2)
|
|
5080
|
-
...registration.hosted_mcp_url ? { hosted_mcp_url: registration.hosted_mcp_url } : {},
|
|
5081
|
-
bound_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
5006
|
+
if (sidecar?.wrapper_path && configText.includes(sidecar.wrapper_path)) return true;
|
|
5007
|
+
if (bareOwnerExists) return false;
|
|
5008
|
+
return isPrimary && Boolean(identity?.hosted_mcp_url && configText.includes(identity.hosted_mcp_url));
|
|
5009
|
+
}
|
|
5010
|
+
function rekeyPendingCheck(status, hostedDelegateAddress, runtime, slug) {
|
|
5011
|
+
return finalizeCheck(rekeyPendingVerdict(status, hostedDelegateAddress, runtime, slug));
|
|
5012
|
+
}
|
|
5013
|
+
function rekeyPendingVerdict(status, hostedDelegateAddress, runtime, slug) {
|
|
5014
|
+
const label = "Pending re-key";
|
|
5015
|
+
const nameFlag = slug ? ` --name ${slug}` : "";
|
|
5016
|
+
if (status.state === "unreadable") {
|
|
5017
|
+
return {
|
|
5018
|
+
id: "rekey_pending",
|
|
5019
|
+
label,
|
|
5020
|
+
level: "failed",
|
|
5021
|
+
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.`,
|
|
5022
|
+
repair: `Delete ${status.path}, then start again: ${RERUN} --rekey${nameFlag}`
|
|
5082
5023
|
};
|
|
5083
|
-
await writeMcpServerBinding(credentialPaths.directory, bindingRecord);
|
|
5084
|
-
} catch {
|
|
5085
|
-
log("Could not record the MCP server-name binding locally (non-fatal; the next setup cannot see this binding).");
|
|
5086
5024
|
}
|
|
5087
|
-
|
|
5088
|
-
|
|
5089
|
-
|
|
5090
|
-
if (
|
|
5091
|
-
|
|
5092
|
-
|
|
5093
|
-
|
|
5094
|
-
|
|
5025
|
+
const started = status.startedAt ?? "an unknown time";
|
|
5026
|
+
const address = status.newDelegateAddress ?? "unknown";
|
|
5027
|
+
const completedOnHaven = hostedDelegateAddress !== void 0 && status.newDelegateAddress !== void 0 && hostedDelegateAddress.toLowerCase() === status.newDelegateAddress.toLowerCase();
|
|
5028
|
+
if (completedOnHaven) {
|
|
5029
|
+
return {
|
|
5030
|
+
id: "rekey_pending",
|
|
5031
|
+
label,
|
|
5032
|
+
level: "failed",
|
|
5033
|
+
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." : ""),
|
|
5034
|
+
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>${runtimeFlagFor(runtime)}`
|
|
5035
|
+
};
|
|
5036
|
+
}
|
|
5037
|
+
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.";
|
|
5038
|
+
if (status.state === "expired") {
|
|
5039
|
+
return {
|
|
5040
|
+
id: "rekey_pending",
|
|
5041
|
+
label,
|
|
5042
|
+
level: "failed",
|
|
5043
|
+
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,
|
|
5044
|
+
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.`
|
|
5045
|
+
};
|
|
5046
|
+
}
|
|
5047
|
+
return {
|
|
5048
|
+
id: "rekey_pending",
|
|
5049
|
+
label,
|
|
5050
|
+
level: "ok",
|
|
5051
|
+
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
|
|
5052
|
+
};
|
|
5053
|
+
}
|
|
5054
|
+
async function runtimeSpecOverrideCheck(directory, sidecar, env) {
|
|
5055
|
+
const facts = [];
|
|
5056
|
+
const installed = sidecar?.runtime_spec_override;
|
|
5057
|
+
if (installed) {
|
|
5058
|
+
facts.push(
|
|
5059
|
+
`signer runtime installed under ${describeRuntimeSpecOverride(installed.specs)} (resolved: ${installed.resolved_specs.join(" ")}; directory key ${installed.directory_key})`
|
|
5095
5060
|
);
|
|
5096
5061
|
}
|
|
5097
|
-
const
|
|
5098
|
-
|
|
5099
|
-
|
|
5100
|
-
|
|
5101
|
-
|
|
5102
|
-
identityPath: credentialPaths.identityPath,
|
|
5103
|
-
credentialDirectory: credentialPaths.directory,
|
|
5104
|
-
environmentLabel: options.environmentLabel ?? "Local workspace",
|
|
5105
|
-
ackSigner: options.ackSigner,
|
|
5106
|
-
ackLocalTools: options.ackLocalTools,
|
|
5107
|
-
localMcp: options.localMcp,
|
|
5108
|
-
serverName
|
|
5109
|
-
}, {
|
|
5110
|
-
onProgress: log,
|
|
5111
|
-
// #1543: report "runtime configured" the moment the config write settles,
|
|
5112
|
-
// so the dashboard can expose its budget-approval controls without
|
|
5113
|
-
// waiting on the probes and skill install — a tail that approval does not
|
|
5114
|
-
// depend on. Silent and best-effort: the complete report below remains
|
|
5115
|
-
// authoritative (it overwrites these keys, adding the probe verdicts and
|
|
5116
|
-
// skill state), so an early failure costs nothing but the head start.
|
|
5117
|
-
onRuntimeConfigured: async (early) => {
|
|
5118
|
-
try {
|
|
5119
|
-
await api.updateInstallStatus(registration.setup_id, localApiKey, {
|
|
5120
|
-
runtime: early.runtime,
|
|
5121
|
-
connectorVersion,
|
|
5122
|
-
runtimeMcpMode: early.runtimeMcpMode,
|
|
5123
|
-
hostedMcpConfigured: early.hostedMcpConfigured,
|
|
5124
|
-
localSignerConfigured: early.localSignerConfigured,
|
|
5125
|
-
localMcpConfigured: early.localMcpConfigured,
|
|
5126
|
-
credentialFilesWritten: true,
|
|
5127
|
-
signerAcknowledged: early.signerAcknowledged,
|
|
5128
|
-
localMcpAcknowledged: early.localMcpAcknowledged,
|
|
5129
|
-
restartRequired: early.restartRequired,
|
|
5130
|
-
nextUserAction: early.nextUserAction,
|
|
5131
|
-
errorCode: early.errorCode ?? null,
|
|
5132
|
-
environmentLabel: options.environmentLabel ?? "Local workspace"
|
|
5133
|
-
});
|
|
5134
|
-
if (!early.errorCode || early.errorCode === "manual_runtime_setup_required") {
|
|
5135
|
-
log(approveBudgetCta(setup, registration.approval_url));
|
|
5136
|
-
}
|
|
5137
|
-
} catch {
|
|
5138
|
-
}
|
|
5139
|
-
}
|
|
5140
|
-
});
|
|
5141
|
-
printRuntimeInstall(runtimeInstall, log);
|
|
5142
|
-
if (runtimeInstall.errorCode) {
|
|
5143
|
-
log("Haven setup needs a couple more steps on this machine \u2014 see the notes above.");
|
|
5144
|
-
} else {
|
|
5145
|
-
log("Haven setup on this machine is complete.");
|
|
5062
|
+
const mcpInstalled = await readMcpSidecarOverride(directory);
|
|
5063
|
+
if (mcpInstalled) {
|
|
5064
|
+
facts.push(
|
|
5065
|
+
`local MCP runtime installed under ${describeRuntimeSpecOverride(mcpInstalled.specs)} (resolved: ${mcpInstalled.resolved_specs.join(" ")}; directory key ${mcpInstalled.directory_key})`
|
|
5066
|
+
);
|
|
5146
5067
|
}
|
|
5147
|
-
let
|
|
5148
|
-
|
|
5149
|
-
|
|
5150
|
-
|
|
5151
|
-
|
|
5152
|
-
|
|
5153
|
-
log(
|
|
5154
|
-
`Previous agent(s) ${supersededIds(replacing)} were NOT retired: the runtime install did not complete, so their wiring may still be the only working one. Resolve the install, then retire them with ${RERUN_HINT} --unwire <dir>.`
|
|
5155
|
-
);
|
|
5156
|
-
} else {
|
|
5157
|
-
supersededAgentsRetiredLocally = true;
|
|
5158
|
-
for (const entry of replacing.superseded) {
|
|
5159
|
-
try {
|
|
5160
|
-
const { mirrorError } = await tombstoneDirectoryIfAbsent({
|
|
5161
|
-
directory: entry.directory,
|
|
5162
|
-
agentId: entry.agentId,
|
|
5163
|
-
reason: "replaced by a new setup (--replace)",
|
|
5164
|
-
replacedBy: registration.agent_id,
|
|
5165
|
-
// #3251: the ledger follows this run's credential root (default
|
|
5166
|
-
// root → ~/.haven/tombstones, as before; any other → <root>/.tombstones).
|
|
5167
|
-
tombstonesDir: tombstonesDirForCredentialRoot(options.credentialsDir)
|
|
5168
|
-
});
|
|
5169
|
-
if (mirrorError !== void 0) {
|
|
5170
|
-
retirementMirrorErrors[entry.agentId] = mirrorError;
|
|
5171
|
-
log(
|
|
5172
|
-
`Warning: the surviving tombstone record for ${entry.agentId} could not be written to ${tombstonesDirForCredentialRoot(options.credentialsDir)} (${mirrorError}). The in-place TOMBSTONE.json stands; --doctor will not list this retirement once the directory is deleted.`
|
|
5173
|
-
);
|
|
5174
|
-
}
|
|
5175
|
-
await teardownLocalKeyMaterial(entry.directory, await readIdentityFile(entry.directory));
|
|
5176
|
-
await clearMcpServerBinding(entry.directory);
|
|
5177
|
-
retiredAgentIds.push(entry.agentId);
|
|
5178
|
-
log(`Retired previous agent ${entry.agentId} locally: tombstoned, local key files removed.`);
|
|
5179
|
-
} catch (err) {
|
|
5180
|
-
supersededAgentsRetiredLocally = false;
|
|
5181
|
-
log(`Could not retire previous agent ${entry.agentId} locally: ${err instanceof Error ? err.message : String(err)}`);
|
|
5182
|
-
}
|
|
5183
|
-
}
|
|
5184
|
-
}
|
|
5068
|
+
let shell;
|
|
5069
|
+
try {
|
|
5070
|
+
const active = resolveRuntimeSpecOverride(env);
|
|
5071
|
+
if (active) shell = `set in this shell: ${describeRuntimeSpecOverride(active)} \u2014 a --repair from here installs these, not the pin`;
|
|
5072
|
+
} catch (err) {
|
|
5073
|
+
shell = err instanceof RuntimeSpecOverrideError ? `set in this shell but REFUSED: ${err.message}` : `set in this shell but unreadable: ${err instanceof Error ? err.message : String(err)}`;
|
|
5185
5074
|
}
|
|
5186
|
-
|
|
5187
|
-
|
|
5075
|
+
if (shell) facts.push(shell);
|
|
5076
|
+
if (facts.length === 0) return void 0;
|
|
5077
|
+
const variables = Object.values(RUNTIME_SPEC_ENV).join(" / ");
|
|
5078
|
+
return finalizeCheck({
|
|
5079
|
+
id: "runtime_spec_override",
|
|
5080
|
+
label: "Runtime spec override",
|
|
5081
|
+
level: "failed",
|
|
5082
|
+
detail: `runtime spec overridden \u2014 not the pinned manifest (${exports.MCP_RUNTIME_MANIFEST.signerPackage}@${exports.MCP_RUNTIME_MANIFEST.signerVersion}, ${exports.MCP_RUNTIME_MANIFEST.sdkPackage}@${exports.MCP_RUNTIME_MANIFEST.sdkVersion}). ${facts.join(". ")}.`,
|
|
5083
|
+
repair: `Developer override (#2424). To return to the pinned manifest: unset ${variables}, then run ${RERUN} --doctor --repair --runtime <runtime>. If the override is intentional, this finding is the record of it.`
|
|
5084
|
+
});
|
|
5085
|
+
}
|
|
5086
|
+
async function readMcpSidecarOverride(directory) {
|
|
5188
5087
|
try {
|
|
5189
|
-
|
|
5190
|
-
|
|
5191
|
-
if (supersededAgentsRetiredLocally === true) {
|
|
5192
|
-
log("");
|
|
5193
|
-
log(
|
|
5194
|
-
`Replaced: previous agent(s) ${supersededIds(replacing)} are retired on this machine but NOT revoked \u2014 revoke them on the Haven agent page, then restart EVERY long-lived host (gateways, TUI workers, editors): each holds the MCP wiring snapshot from its own start time, and the tombstone speaks only when a stale host next probes the old path.`
|
|
5195
|
-
);
|
|
5196
|
-
} else if (supersededAgentIds.length > 0) {
|
|
5197
|
-
log("");
|
|
5198
|
-
log(
|
|
5199
|
-
`Heads-up: this setup created a NEW agent. Your previous agent(s) \u2014 ${supersededAgentIds.join(", ")} \u2014 still exist with their own keys, and any host that was already running keeps acting as them.`
|
|
5200
|
-
);
|
|
5201
|
-
log(
|
|
5202
|
-
`If you meant to replace them: revoke them on the Haven agent page, then restart EVERY long-lived host (gateways, TUI workers, editors) \u2014 each holds the MCP wiring snapshot from its own start time, so after repeated setups each can be stuck on a DIFFERENT old agent. Then remove their directories under ~/.haven/agents (or ${RERUN_HINT} --tombstone <dir> to leave a diagnostic in their place). Run ${RERUN_HINT} --doctor to check whether their keys are still live.`
|
|
5203
|
-
);
|
|
5204
|
-
}
|
|
5088
|
+
const parsed = JSON.parse(await promises.readFile(path.join(directory, "mcp-runtime.json"), "utf8"));
|
|
5089
|
+
return parsed.runtime_spec_override;
|
|
5205
5090
|
} catch {
|
|
5091
|
+
return void 0;
|
|
5206
5092
|
}
|
|
5093
|
+
}
|
|
5094
|
+
async function readIdentity(directory) {
|
|
5207
5095
|
try {
|
|
5208
|
-
await
|
|
5209
|
-
|
|
5210
|
-
|
|
5211
|
-
runtimeMcpMode: runtimeInstall.runtimeMcpMode,
|
|
5212
|
-
hostedMcpConfigured: runtimeInstall.hostedMcpConfigured,
|
|
5213
|
-
localSignerConfigured: runtimeInstall.localSignerConfigured,
|
|
5214
|
-
localMcpConfigured: runtimeInstall.localMcpConfigured,
|
|
5215
|
-
credentialFilesWritten: true,
|
|
5216
|
-
signerAcknowledged: runtimeInstall.signerAcknowledged,
|
|
5217
|
-
localMcpAcknowledged: runtimeInstall.localMcpAcknowledged,
|
|
5218
|
-
activationCommandAvailable: Boolean(runtimeInstall.activationCommand),
|
|
5219
|
-
skillInstalled: runtimeInstall.skillInstalled,
|
|
5220
|
-
probeResult: runtimeInstall.probeResult,
|
|
5221
|
-
restartRequired: runtimeInstall.restartRequired,
|
|
5222
|
-
nextUserAction: runtimeInstall.nextUserAction,
|
|
5223
|
-
errorCode: runtimeInstall.errorCode,
|
|
5224
|
-
environmentLabel: options.environmentLabel ?? "Local workspace",
|
|
5225
|
-
// The raw scan result, `null` and all — NOT the flattened
|
|
5226
|
-
// `supersededAgentIds` the outcome carries. Flattening here would hand
|
|
5227
|
-
// the dashboard the same ambiguity this field exists to remove (#2561).
|
|
5228
|
-
supersededAgentIds: supersededScan
|
|
5229
|
-
});
|
|
5230
|
-
} catch (err) {
|
|
5231
|
-
log(`Could not report install status to Haven: ${err instanceof Error ? err.message : String(err)}`);
|
|
5232
|
-
}
|
|
5233
|
-
let approval;
|
|
5234
|
-
const narrateApprovalWait = options.waitForApproval === true || options.waitForApproval === void 0 && (deps.isStdoutTty ?? Boolean(process.stdout.isTTY));
|
|
5235
|
-
if (narrateApprovalWait && !runtimeInstall.errorCode) {
|
|
5236
|
-
approval = await waitForBudgetApproval(api, registration.setup_id, localApiKey, log, options.approvalWait);
|
|
5096
|
+
return JSON.parse(await promises.readFile(path.join(directory, "identity.json"), "utf8"));
|
|
5097
|
+
} catch {
|
|
5098
|
+
return void 0;
|
|
5237
5099
|
}
|
|
5238
|
-
|
|
5239
|
-
|
|
5240
|
-
|
|
5241
|
-
|
|
5242
|
-
|
|
5243
|
-
|
|
5244
|
-
|
|
5245
|
-
...replacing ? { retiredAgentIds } : {},
|
|
5246
|
-
...Object.keys(retirementMirrorErrors).length > 0 ? { retirementMirrorErrors } : {},
|
|
5247
|
-
existingAgentsBeforeWrite: existingAgents.map((a) => ({ agent_id: a.agentId, account_address: a.accountAddress })),
|
|
5248
|
-
...reboundFrom ? { serverNameReboundFrom: reboundFrom } : {},
|
|
5249
|
-
setupChallengeExpiresAt: setup.challenge.expires_at,
|
|
5250
|
-
approvalRequired: registration.agent_status === "pending_approval",
|
|
5251
|
-
approvalUrl: registration.approval_url
|
|
5252
|
-
});
|
|
5253
|
-
if (await recordConnectOutcome(deps, credentialPaths.directory, outcome)) {
|
|
5254
|
-
log(`Saved this run's outcome to ${exports.CONNECT_OUTCOME_FILENAME} in the agent's credential directory.`);
|
|
5100
|
+
}
|
|
5101
|
+
function describeAccountAddressKey(identity, signerFile) {
|
|
5102
|
+
const files = [identity, signerFile];
|
|
5103
|
+
const has = (key) => files.some((f) => typeof f?.[key] === "string" && f[key].trim() !== "");
|
|
5104
|
+
if (has("account_address")) return "account address stored as account_address";
|
|
5105
|
+
if (has("safe_address")) {
|
|
5106
|
+
return "account address stored under the pre-#2908 name safe_address \u2014 still read; the next --rekey or setup rewrites it as account_address";
|
|
5255
5107
|
}
|
|
5256
|
-
return
|
|
5257
|
-
setupId: registration.setup_id,
|
|
5258
|
-
agentId: registration.agent_id,
|
|
5259
|
-
delegateAddress: registration.delegate_address,
|
|
5260
|
-
credentialPaths,
|
|
5261
|
-
outcome
|
|
5262
|
-
};
|
|
5108
|
+
return "no account address stored";
|
|
5263
5109
|
}
|
|
5264
|
-
function
|
|
5265
|
-
const
|
|
5266
|
-
|
|
5267
|
-
|
|
5268
|
-
|
|
5269
|
-
schema_version: CONNECT_OUTCOME_SCHEMA_VERSION,
|
|
5270
|
-
outcome: runtimeInstall.errorCode ? "action_required" : "complete",
|
|
5271
|
-
runtime: runtimeInstall.runtime,
|
|
5272
|
-
topology: runtimeInstall.runtimeMcpMode,
|
|
5273
|
-
configuration: {
|
|
5274
|
-
hosted_mcp: runtimeInstall.hostedMcpConfigured,
|
|
5275
|
-
local_signer: runtimeInstall.localSignerConfigured,
|
|
5276
|
-
local_mcp: runtimeInstall.localMcpConfigured
|
|
5277
|
-
},
|
|
5278
|
-
probe: { result: runtimeInstall.probeResult },
|
|
5279
|
-
activation: {
|
|
5280
|
-
restart_required: runtimeInstall.restartRequired,
|
|
5281
|
-
instruction: manualSetup ? "Finish the manual MCP setup using the secret-free references shown in normal Connect output, then start a fresh session." : runtimeProfile(runtimeInstall.runtime).activationInstruction
|
|
5282
|
-
},
|
|
5283
|
-
next_action: nextAction2,
|
|
5284
|
-
approval: {
|
|
5285
|
-
required: input.approvalRequired,
|
|
5286
|
-
expires_at: null,
|
|
5287
|
-
// Only when there is something to approve AND the backend supplied a
|
|
5288
|
-
// link. Never synthesised here: the connector does not know the
|
|
5289
|
-
// dashboard's origin, and a guessed URL is worse than none — it is the
|
|
5290
|
-
// "do not invent one" rule the agent runbook states, applied to the
|
|
5291
|
-
// tool rather than the agent.
|
|
5292
|
-
...input.approvalRequired && input.approvalUrl ? { url: input.approvalUrl } : {}
|
|
5293
|
-
},
|
|
5294
|
-
verification: {
|
|
5295
|
-
tools: ["haven_get_agent", "haven_get_allowances"],
|
|
5296
|
-
instruction: runtimeVerificationInstruction(runtimeInstall.runtime)
|
|
5297
|
-
},
|
|
5298
|
-
// The backend contract supplies a 20-byte address. If an unexpected
|
|
5299
|
-
// malformed value arrives, do not echo it into an automation-facing
|
|
5300
|
-
// record; the human log has already been redacted separately.
|
|
5301
|
-
delegate_address: /^0x[0-9a-fA-F]{40}$/.test(input.delegateAddress) ? shortAddress(input.delegateAddress) : "[delegate-address-redacted]",
|
|
5302
|
-
// The endpoint Connect wrote into the runtime's MCP config, verbatim — the
|
|
5303
|
-
// same string that already sits in the user's own config file. Passed
|
|
5304
|
-
// through the secret filter anyway: this is the automation contract, the
|
|
5305
|
-
// value is server-supplied, and belts are cheap (the #1589 stance).
|
|
5306
|
-
...input.hostedMcpUrl ? { hosted_mcp_url: redactSecrets(input.hostedMcpUrl) } : {},
|
|
5307
|
-
// Always emitted on a completed run, empty list included: "no superseded
|
|
5308
|
-
// agents" is a fact a caller needs, and an omitted key would be
|
|
5309
|
-
// indistinguishable from an older connector that never reported it.
|
|
5310
|
-
superseded_agent_ids: input.supersededAgentIds ?? [],
|
|
5311
|
-
...input.supersededAgentsRetiredLocally !== void 0 ? { superseded_agents_retired_locally: input.supersededAgentsRetiredLocally } : {},
|
|
5312
|
-
...input.retiredAgentIds ? { retired_agent_ids: input.retiredAgentIds } : {},
|
|
5313
|
-
...input.retirementMirrorErrors ? { retirement_mirror_errors: input.retirementMirrorErrors } : {},
|
|
5314
|
-
// #3122: always emitted on a completed run (empty list included), for the
|
|
5315
|
-
// same reason as superseded_agent_ids above.
|
|
5316
|
-
existing_agents_before_write: input.existingAgentsBeforeWrite ?? [],
|
|
5317
|
-
...input.serverNameReboundFrom ? { server_name_rebound_from: input.serverNameReboundFrom } : {},
|
|
5318
|
-
...input.setupChallengeExpiresAt ? { setup_challenge_expires_at: input.setupChallengeExpiresAt } : {},
|
|
5319
|
-
...runtimeInstall.errorCode ? { error: { code: runtimeInstall.errorCode, next_action: nextAction2 } } : {}
|
|
5110
|
+
async function checksForAgent(entry, input, deps) {
|
|
5111
|
+
const verdicts = await verdictsForAgent(entry, input, deps);
|
|
5112
|
+
return {
|
|
5113
|
+
checks: verdicts.checks.map(finalizeCheck),
|
|
5114
|
+
...verdicts.signerCapabilities ? { signerCapabilities: verdicts.signerCapabilities } : {}
|
|
5320
5115
|
};
|
|
5321
|
-
return outcome;
|
|
5322
5116
|
}
|
|
5323
|
-
async function
|
|
5117
|
+
async function verdictsForAgent(entry, input, deps) {
|
|
5118
|
+
const { directory, identity, sidecar } = entry;
|
|
5119
|
+
const checks = [];
|
|
5120
|
+
let signerCapabilities;
|
|
5121
|
+
let signerFile;
|
|
5324
5122
|
try {
|
|
5325
|
-
const
|
|
5326
|
-
|
|
5327
|
-
return hint.installedClients.length > 0 ? hint : {};
|
|
5123
|
+
const parsed = JSON.parse(await promises.readFile(path.join(directory, "signer.json"), "utf8"));
|
|
5124
|
+
signerFile = typeof parsed === "object" && parsed !== null ? parsed : void 0;
|
|
5328
5125
|
} catch {
|
|
5329
|
-
|
|
5126
|
+
signerFile = void 0;
|
|
5330
5127
|
}
|
|
5331
|
-
|
|
5332
|
-
|
|
5333
|
-
|
|
5334
|
-
|
|
5335
|
-
|
|
5336
|
-
|
|
5337
|
-
}
|
|
5338
|
-
|
|
5339
|
-
if (!
|
|
5340
|
-
|
|
5341
|
-
|
|
5342
|
-
|
|
5343
|
-
|
|
5344
|
-
|
|
5345
|
-
|
|
5346
|
-
|
|
5347
|
-
|
|
5348
|
-
|
|
5349
|
-
|
|
5350
|
-
|
|
5351
|
-
|
|
5352
|
-
|
|
5353
|
-
|
|
5354
|
-
|
|
5355
|
-
|
|
5356
|
-
|
|
5357
|
-
|
|
5358
|
-
|
|
5359
|
-
|
|
5128
|
+
const credentialsOk = Boolean(identity?.api_key) && signerFile !== void 0;
|
|
5129
|
+
checks.push({
|
|
5130
|
+
id: "credentials",
|
|
5131
|
+
label: "Agent credentials",
|
|
5132
|
+
level: credentialsOk ? "ok" : "failed",
|
|
5133
|
+
detail: credentialsOk ? `identity.json and signer.json parse (agent ${identity?.agent_id ?? "unknown"}; ${describeAccountAddressKey(identity, signerFile)})` : "identity.json or signer.json is missing or unparseable.",
|
|
5134
|
+
...credentialsOk ? {} : { repair: `Re-run the full setup with a fresh token: ${RERUN} --setup <token>.` }
|
|
5135
|
+
});
|
|
5136
|
+
if (!sidecar) {
|
|
5137
|
+
checks.push({
|
|
5138
|
+
id: "signer_runtime",
|
|
5139
|
+
label: "Signer runtime (preinstalled wrapper)",
|
|
5140
|
+
level: "failed",
|
|
5141
|
+
detail: "No signer-runtime.json sidecar \u2014 the pinned signer runtime was never prepared (or a pre-#1586 npx config).",
|
|
5142
|
+
repair: repairCommandFor(input.runtime)
|
|
5143
|
+
});
|
|
5144
|
+
} else if (sidecar.runtime_spec_override) {
|
|
5145
|
+
const matches = await installedRuntimeMatchesVersions(sidecar.runtime_directory, sidecar.cli_path, {
|
|
5146
|
+
signerVersion: sidecar.signer_version,
|
|
5147
|
+
sdkVersion: sidecar.sdk_version
|
|
5148
|
+
});
|
|
5149
|
+
checks.push({
|
|
5150
|
+
id: "signer_runtime",
|
|
5151
|
+
label: "Signer runtime (preinstalled wrapper)",
|
|
5152
|
+
level: matches ? "ok" : "failed",
|
|
5153
|
+
detail: matches ? `Installed ${sidecar.signer_package}@${sidecar.signer_version} at ${sidecar.runtime_directory} (override install \u2014 see runtime_spec_override)` : `Override runtime directory is stale or empty (${sidecar.runtime_directory}) \u2014 the CLI or package versions are missing.`,
|
|
5154
|
+
...matches ? {} : { repair: repairCommandFor(input.runtime, " with the same HAVEN_*_SPEC variables set.") }
|
|
5155
|
+
});
|
|
5156
|
+
} else {
|
|
5157
|
+
const intact = await installedRuntimeMatchesVersions(sidecar.runtime_directory, sidecar.cli_path, {
|
|
5158
|
+
signerVersion: sidecar.signer_version,
|
|
5159
|
+
sdkVersion: sidecar.sdk_version
|
|
5160
|
+
});
|
|
5161
|
+
const versionOk = sidecar.signer_version === exports.MCP_RUNTIME_MANIFEST.signerVersion;
|
|
5162
|
+
const ok = intact && versionOk;
|
|
5163
|
+
checks.push({
|
|
5164
|
+
id: "signer_runtime",
|
|
5165
|
+
label: "Signer runtime (preinstalled wrapper)",
|
|
5166
|
+
level: ok ? "ok" : intact ? "advisory" : "failed",
|
|
5167
|
+
detail: ok ? `Installed ${sidecar.signer_package}@${sidecar.signer_version} at ${sidecar.runtime_directory}` : intact ? `Installed version ${sidecar.signer_version} does not match the connector's pinned ${exports.MCP_RUNTIME_MANIFEST.signerVersion} \u2014 intact, but outdated.` : `Runtime directory is stale or empty (${sidecar.runtime_directory}) \u2014 the CLI or package versions are missing.`,
|
|
5168
|
+
...ok ? {} : { repair: repairCommandFor(input.runtime) }
|
|
5169
|
+
});
|
|
5170
|
+
}
|
|
5171
|
+
const overrideCheck = await runtimeSpecOverrideCheck(directory, sidecar, deps.env ?? process.env);
|
|
5172
|
+
if (overrideCheck) checks.push(overrideCheck);
|
|
5173
|
+
const hostedUrl = identity?.hosted_mcp_url ?? (identity?.api_url ? `${identity.api_url}/mcp` : void 0);
|
|
5174
|
+
if (identity?.api_key && hostedUrl) {
|
|
5175
|
+
const probe = await (deps.probeHosted ?? probeHostedMcpTools)(identity.api_key, hostedUrl, deps.fetch);
|
|
5176
|
+
checks.push({
|
|
5177
|
+
id: "hosted_mcp",
|
|
5178
|
+
label: "Hosted Haven MCP",
|
|
5179
|
+
level: probe.status === "ok" ? "ok" : "failed",
|
|
5180
|
+
detail: probe.status === "ok" ? `MCP tools endpoint is reachable (${hostedUrl}).` : `MCP tools endpoint probe failed: ${probe.status} (${hostedUrl}).`,
|
|
5181
|
+
...probe.status === "ok" ? {} : {
|
|
5182
|
+
repair: "Check network access and runtime configuration for the hosted MCP URL, then re-run --doctor."
|
|
5183
|
+
}
|
|
5184
|
+
});
|
|
5185
|
+
} else {
|
|
5186
|
+
checks.push({
|
|
5187
|
+
id: "hosted_mcp",
|
|
5188
|
+
label: "Hosted Haven MCP",
|
|
5189
|
+
level: "failed",
|
|
5190
|
+
detail: "No stored API key / hosted MCP URL to probe with.",
|
|
5191
|
+
repair: `Re-run the full setup: ${RERUN} --setup <token>.`
|
|
5192
|
+
});
|
|
5193
|
+
}
|
|
5194
|
+
const localDelegate = typeof signerFile?.delegate_address === "string" ? signerFile.delegate_address : void 0;
|
|
5195
|
+
let hostedDelegateAddress;
|
|
5196
|
+
if (identity?.api_key && identity.api_url) {
|
|
5197
|
+
const probe = await (deps.probeHostedIdentity ?? probeHostedAgentIdentity)(
|
|
5198
|
+
identity.api_key,
|
|
5199
|
+
identity.api_url,
|
|
5200
|
+
deps.fetch
|
|
5201
|
+
);
|
|
5202
|
+
if (probe.status === "ok") hostedDelegateAddress = probe.delegateAddress;
|
|
5203
|
+
if (probe.status !== "ok") {
|
|
5204
|
+
checks.push({
|
|
5205
|
+
id: "identity_match",
|
|
5206
|
+
label: "Hosted identity matches the local signing key",
|
|
5207
|
+
level: "failed",
|
|
5208
|
+
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.`,
|
|
5209
|
+
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${runtimeFlagFor(input.runtime)}`
|
|
5210
|
+
});
|
|
5211
|
+
} else if (!localDelegate) {
|
|
5212
|
+
checks.push({
|
|
5213
|
+
id: "identity_match",
|
|
5214
|
+
label: "Hosted identity matches the local signing key",
|
|
5215
|
+
level: "failed",
|
|
5216
|
+
detail: "signer.json holds no delegate_address to compare against the hosted identity.",
|
|
5217
|
+
repair: `Re-run the full setup with a fresh token: ${RERUN} --setup <token>.`
|
|
5218
|
+
});
|
|
5219
|
+
} else {
|
|
5220
|
+
const same = probe.delegateAddress?.toLowerCase() === localDelegate.toLowerCase();
|
|
5221
|
+
checks.push({
|
|
5222
|
+
id: "identity_match",
|
|
5223
|
+
label: "Hosted identity matches the local signing key",
|
|
5224
|
+
level: same ? "ok" : "failed",
|
|
5225
|
+
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.`,
|
|
5226
|
+
...same ? {} : {
|
|
5227
|
+
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.`
|
|
5228
|
+
}
|
|
5229
|
+
});
|
|
5230
|
+
}
|
|
5231
|
+
}
|
|
5232
|
+
const pending = await inspectRekeyPending(directory, deps.now?.() ?? Date.now());
|
|
5233
|
+
if (pending) {
|
|
5234
|
+
checks.push(rekeyPendingCheck(pending, hostedDelegateAddress, input.runtime, sidecar?.server_name));
|
|
5235
|
+
}
|
|
5236
|
+
if (sidecar) {
|
|
5237
|
+
const consent = await getLocalSignerConsentStatus(path.join(directory, "signer.json"));
|
|
5238
|
+
if (!consent.acknowledged) {
|
|
5239
|
+
checks.push({
|
|
5240
|
+
id: "signer_process",
|
|
5241
|
+
label: "Signer stdio handshake",
|
|
5242
|
+
level: "failed",
|
|
5243
|
+
detail: "The local-tools consent is not acknowledged, so the signer refuses to start (by design).",
|
|
5244
|
+
repair: `Run: ${RERUN} --ack-local-tools --setup <token> (or re-run your original connector command with --ack-local-tools).`
|
|
5245
|
+
});
|
|
5246
|
+
} else {
|
|
5247
|
+
const probe = await (deps.probeSignerTools ?? probeLocalMcpTools)(
|
|
5248
|
+
sidecar.wrapper_path,
|
|
5249
|
+
[],
|
|
5250
|
+
exports.MCP_RUNTIME_MANIFEST.requiredSignerTools
|
|
5360
5251
|
);
|
|
5252
|
+
const experimental = probe.capabilities?.experimental ?? probe.capabilities;
|
|
5253
|
+
const compat = experimental?.["haven/signer-compatibility"];
|
|
5254
|
+
signerCapabilities = compat ? { "haven/signer-compatibility": compat } : void 0;
|
|
5255
|
+
const compatDetail = compat ? ` Compat: x402 expected-context v${JSON.stringify(compat.x402_expected_context_versions ?? "?")}.` : "";
|
|
5256
|
+
checks.push({
|
|
5257
|
+
id: "signer_process",
|
|
5258
|
+
label: "Signer stdio handshake",
|
|
5259
|
+
level: probe.status === "ok" ? "ok" : "failed",
|
|
5260
|
+
detail: probe.status === "ok" ? `Signer started, listed ${probe.toolNames?.length ?? 0} tools${probe.serverInfo?.version ? ` (v${probe.serverInfo.version})` : ""}.${compatDetail}` : `Handshake failed: ${probe.status}.`,
|
|
5261
|
+
...probe.status === "ok" ? {} : { repair: repairCommandFor(input.runtime) }
|
|
5262
|
+
});
|
|
5361
5263
|
}
|
|
5362
|
-
|
|
5264
|
+
} else {
|
|
5265
|
+
checks.push({
|
|
5266
|
+
id: "signer_process",
|
|
5267
|
+
label: "Signer stdio handshake",
|
|
5268
|
+
level: "failed",
|
|
5269
|
+
detail: "Skipped \u2014 no prepared signer runtime to probe.",
|
|
5270
|
+
repair: repairCommandFor(input.runtime)
|
|
5271
|
+
});
|
|
5363
5272
|
}
|
|
5364
|
-
|
|
5365
|
-
"wiring_collision",
|
|
5366
|
-
`This machine is already wired to a Haven agent with a live key (${supersededIds(collision)}), and setting up "${agentName}" on the bare haven / haven-signer pair would replace that wiring. Nothing was written and the Haven setup token is still unused. If you are an AI agent running this command: do NOT add a flag yourself \u2014 relay this to your user and stop. Your user decides: REPLACE the existing wiring (re-run the same command with --replace added, which re-points the pair at the new agent and retires the previous directory locally \u2014 they still revoke the old agent on the Haven agent page), or install ALONGSIDE it (re-run with --name <slug> added, e.g. --name ${collision.suggestedServerName}, which gives the new agent its own haven-<slug> / haven-signer-<slug> pair). Re-run only with the flag your user chooses.`,
|
|
5367
|
-
"relay_wiring_collision_to_user",
|
|
5368
|
-
{ supersededAgentIds: collision.superseded.map((e) => e.agentId), suggestedServerName: collision.suggestedServerName }
|
|
5369
|
-
);
|
|
5273
|
+
return { checks, ...signerCapabilities ? { signerCapabilities } : {} };
|
|
5370
5274
|
}
|
|
5371
|
-
function
|
|
5372
|
-
const
|
|
5373
|
-
const
|
|
5374
|
-
|
|
5375
|
-
const
|
|
5376
|
-
|
|
5377
|
-
|
|
5378
|
-
|
|
5379
|
-
|
|
5380
|
-
|
|
5381
|
-
|
|
5382
|
-
|
|
5383
|
-
|
|
5384
|
-
|
|
5385
|
-
|
|
5386
|
-
|
|
5387
|
-
tools: ["haven_get_agent", "haven_get_allowances"],
|
|
5388
|
-
instruction: "After a successful setup and activation, verify only with haven_get_agent and haven_get_allowances."
|
|
5389
|
-
},
|
|
5390
|
-
error: {
|
|
5391
|
-
code,
|
|
5392
|
-
next_action: nextAction2,
|
|
5393
|
-
// Only a ConnectError's message enters the JSON record: the vocabulary's
|
|
5394
|
-
// prose is connector-authored and safe to serialize, while a plain
|
|
5395
|
-
// Error can carry arbitrary server or filesystem detail (that stance is
|
|
5396
|
-
// pinned by test). Redaction stays on as belt-and-braces; plain-Error
|
|
5397
|
-
// runs still get their redacted message on stderr via the CLI mirror.
|
|
5398
|
-
...error instanceof exports.ConnectError && message ? { message: redactForAutomation(message) } : {},
|
|
5399
|
-
...error instanceof exports.ConnectError && error.details.allowedRuntimes ? { allowed_runtimes: error.details.allowedRuntimes } : {},
|
|
5400
|
-
...error instanceof exports.ConnectError && error.details.installedClients?.length ? { installed_clients: error.details.installedClients } : {},
|
|
5401
|
-
...error instanceof exports.ConnectError && error.details.suggestedRuntime ? { suggested_runtime: error.details.suggestedRuntime } : {},
|
|
5402
|
-
...error instanceof exports.ConnectError && error.details.supersededAgentIds ? { superseded_agent_ids: error.details.supersededAgentIds } : {},
|
|
5403
|
-
...error instanceof exports.ConnectError && error.details.suggestedServerName ? { suggested_name: error.details.suggestedServerName } : {}
|
|
5275
|
+
async function runDoctor(input, deps = {}) {
|
|
5276
|
+
const homeDir = deps.homeDir ?? os.homedir();
|
|
5277
|
+
const checks = [];
|
|
5278
|
+
let signerCapabilities;
|
|
5279
|
+
const { directory, others, parkedOnly } = await discoverCredentialDirectory(homeDir, input.credentialsDir);
|
|
5280
|
+
const resolution = await resolveDoctorRuntime(input, directory);
|
|
5281
|
+
const runtime = resolution.runtime;
|
|
5282
|
+
const input2 = { ...input, runtime };
|
|
5283
|
+
const normalizedRuntime = normalizeRuntimeName(input2.runtime);
|
|
5284
|
+
const configPath = runtimeConfigPathFor(normalizedRuntime ?? input2.runtime, homeDir);
|
|
5285
|
+
let configText = null;
|
|
5286
|
+
if (configPath !== null) {
|
|
5287
|
+
try {
|
|
5288
|
+
configText = await promises.readFile(configPath, "utf8");
|
|
5289
|
+
} catch {
|
|
5290
|
+
configText = null;
|
|
5404
5291
|
}
|
|
5405
|
-
}
|
|
5406
|
-
|
|
5407
|
-
|
|
5408
|
-
|
|
5409
|
-
|
|
5410
|
-
|
|
5411
|
-
|
|
5412
|
-
|
|
5413
|
-
|
|
5414
|
-
|
|
5292
|
+
}
|
|
5293
|
+
const allDirectories = directory ? [directory, ...others] : others;
|
|
5294
|
+
let bareOwnerExists = false;
|
|
5295
|
+
for (const dir of allDirectories) {
|
|
5296
|
+
const sidecar = await readRuntimeSidecar(dir);
|
|
5297
|
+
if (!sidecar?.server_name && sidecar?.wrapper_path && configText?.includes(sidecar.wrapper_path)) {
|
|
5298
|
+
bareOwnerExists = true;
|
|
5299
|
+
break;
|
|
5300
|
+
}
|
|
5301
|
+
}
|
|
5302
|
+
const inventory = [];
|
|
5303
|
+
const capabilitiesByDirectory = /* @__PURE__ */ new Map();
|
|
5304
|
+
const primaryChecksById = /* @__PURE__ */ new Map();
|
|
5305
|
+
for (const dir of allDirectories) {
|
|
5306
|
+
const identity = await readIdentity(dir);
|
|
5307
|
+
const sidecar = await readRuntimeSidecar(dir);
|
|
5308
|
+
const tombstone = await readAgentTombstone(dir);
|
|
5309
|
+
const slug = sidecar?.server_name;
|
|
5310
|
+
const names = serverNamesFor(slug);
|
|
5311
|
+
const rekeyPending = await inspectRekeyPending(dir, deps.now?.() ?? Date.now());
|
|
5312
|
+
if (!identity?.api_key) {
|
|
5313
|
+
const agentId = tombstone?.agent_id ?? rekeyPending?.agentId;
|
|
5314
|
+
inventory.push({
|
|
5315
|
+
...slug ? { slug } : {},
|
|
5316
|
+
...agentId ? { agentId } : {},
|
|
5317
|
+
directory: dir,
|
|
5318
|
+
// A tombstone is a deliberate record and outranks the discovery tell:
|
|
5319
|
+
// a retired directory that also holds a parked key stays `retired`.
|
|
5320
|
+
classification: tombstone ? "retired" : parkedOnly.has(dir) ? "parked" : "orphaned",
|
|
5321
|
+
checks: rekeyPending ? [rekeyPendingCheck(rekeyPending, void 0, input2.runtime, slug)] : [],
|
|
5322
|
+
...rekeyPending ? { rekeyPending } : {}
|
|
5323
|
+
});
|
|
5324
|
+
continue;
|
|
5325
|
+
}
|
|
5326
|
+
const wired = agentIsWired(configText, names, slug, identity, sidecar, dir === directory, bareOwnerExists);
|
|
5327
|
+
const entry = {
|
|
5328
|
+
...slug ? { slug } : {},
|
|
5329
|
+
...identity.agent_id ? { agentId: identity.agent_id } : {},
|
|
5330
|
+
directory: dir,
|
|
5331
|
+
classification: wired ? "wired" : "superseded",
|
|
5332
|
+
checks: [],
|
|
5333
|
+
...rekeyPending ? { rekeyPending } : {}
|
|
5334
|
+
};
|
|
5335
|
+
if (wired) {
|
|
5336
|
+
const result = await checksForAgent({ directory: dir, identity, sidecar }, input2, deps);
|
|
5337
|
+
entry.checks = result.checks;
|
|
5338
|
+
capabilitiesByDirectory.set(dir, result.signerCapabilities);
|
|
5339
|
+
} else if (rekeyPending) {
|
|
5340
|
+
entry.checks = [rekeyPendingCheck(rekeyPending, void 0, input2.runtime, slug)];
|
|
5415
5341
|
}
|
|
5342
|
+
inventory.push(entry);
|
|
5416
5343
|
}
|
|
5417
|
-
|
|
5418
|
-
|
|
5419
|
-
|
|
5420
|
-
|
|
5421
|
-
|
|
5422
|
-
|
|
5423
|
-
return `\u2192 Action needed: approve this agent's budget \u2014 ${budgetPhrase} from ${setup.haven_wallet.name} on ${setup.haven_wallet.network} \u2014 ${where}. The approval button is live now; setup continues here in the meantime.`;
|
|
5344
|
+
const wiredDirectories = inventory.filter((entry) => entry.classification === "wired").map((entry) => entry.directory);
|
|
5345
|
+
const primaryDirectory = input.credentialsDir ? directory : wiredDirectories.includes(directory ?? "") ? directory : wiredDirectories[0] ?? directory;
|
|
5346
|
+
if (primaryDirectory) {
|
|
5347
|
+
const primaryEntry = inventory.find((entry) => entry.directory === primaryDirectory);
|
|
5348
|
+
signerCapabilities = capabilitiesByDirectory.get(primaryDirectory);
|
|
5349
|
+
for (const check of primaryEntry?.checks ?? []) primaryChecksById.set(check.id, check);
|
|
5424
5350
|
}
|
|
5425
|
-
|
|
5426
|
-
|
|
5427
|
-
|
|
5428
|
-
|
|
5429
|
-
|
|
5430
|
-
|
|
5431
|
-
|
|
5432
|
-
|
|
5433
|
-
});
|
|
5434
|
-
}
|
|
5435
|
-
function assertSetupChallengeIsUsable(expiresAt) {
|
|
5436
|
-
const expiresAtMs = Date.parse(expiresAt);
|
|
5437
|
-
if (!Number.isNaN(expiresAtMs) && expiresAtMs > Date.now()) return;
|
|
5438
|
-
throw new Error(
|
|
5439
|
-
"This Haven setup challenge is expired or invalid. Return to Haven, start a fresh connection, and rerun Connect. No local credentials were written."
|
|
5440
|
-
);
|
|
5441
|
-
}
|
|
5442
|
-
function deadSetupTokenError(err) {
|
|
5443
|
-
if (!(err instanceof ConnectRequestError) || err.status !== 410 && err.status !== 401) return null;
|
|
5444
|
-
return new exports.ConnectError(
|
|
5445
|
-
"setup_challenge_expired_or_invalid",
|
|
5446
|
-
"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 connector command. No local credentials were written.",
|
|
5447
|
-
"return_to_haven_for_fresh_setup"
|
|
5448
|
-
);
|
|
5449
|
-
}
|
|
5450
|
-
function isExpiredSetupChallenge(err) {
|
|
5451
|
-
return err instanceof Error && /(?:setup )?challenge.*expir|expir.*(?:setup )?challenge/i.test(err.message);
|
|
5452
|
-
}
|
|
5453
|
-
function secureLogger(log, redactPaths = false) {
|
|
5454
|
-
return (message) => {
|
|
5455
|
-
log(redactPaths ? redactForAutomation(message) : redactSecrets(message));
|
|
5456
|
-
};
|
|
5457
|
-
}
|
|
5458
|
-
function printRuntimeInstall(result, log) {
|
|
5459
|
-
for (const message of result.messages) log(message);
|
|
5460
|
-
if (result.localMcpConfigured) {
|
|
5461
|
-
log("Configured local Haven MCP tools.");
|
|
5462
|
-
} else if (result.hostedMcpConfigured) {
|
|
5463
|
-
log("Configured hosted Haven MCP identity.");
|
|
5351
|
+
if (!primaryDirectory) {
|
|
5352
|
+
checks.push({
|
|
5353
|
+
id: "credentials",
|
|
5354
|
+
label: "Agent credentials",
|
|
5355
|
+
level: "failed",
|
|
5356
|
+
detail: "No agent credential directory with an identity.json under ~/.haven/agents.",
|
|
5357
|
+
repair: `Run the full setup once: ${RERUN} --setup <token from the Haven dashboard>.`
|
|
5358
|
+
});
|
|
5464
5359
|
} else {
|
|
5465
|
-
|
|
5360
|
+
const primaryIdentity = await readIdentity(primaryDirectory);
|
|
5361
|
+
const primarySidecar = await readRuntimeSidecar(primaryDirectory);
|
|
5362
|
+
if (!primaryChecksById.has("credentials")) {
|
|
5363
|
+
const result = await checksForAgent(
|
|
5364
|
+
{ directory: primaryDirectory, identity: primaryIdentity, sidecar: primarySidecar },
|
|
5365
|
+
input2,
|
|
5366
|
+
deps
|
|
5367
|
+
);
|
|
5368
|
+
signerCapabilities = result.signerCapabilities;
|
|
5369
|
+
for (const check of result.checks) primaryChecksById.set(check.id, check);
|
|
5370
|
+
}
|
|
5371
|
+
for (const id of ["credentials", "signer_runtime", "runtime_spec_override"]) {
|
|
5372
|
+
const check = primaryChecksById.get(id);
|
|
5373
|
+
if (check) checks.push(check);
|
|
5374
|
+
}
|
|
5466
5375
|
}
|
|
5467
|
-
|
|
5468
|
-
|
|
5376
|
+
const runtimeOwnsNoConfig = normalizedRuntime !== null && configPath === null;
|
|
5377
|
+
if (configPath === null && input2.runtime !== "" && normalizedRuntime === null) {
|
|
5378
|
+
checks.push({
|
|
5379
|
+
id: "runtime_config",
|
|
5380
|
+
label: "Runtime MCP config",
|
|
5381
|
+
level: "failed",
|
|
5382
|
+
detail: `Runtime '${input2.runtime}' is not one the connector recognises. The runtime config was NOT checked. Re-run the doctor naming the runtime \u2014 one of: ${RUNTIME_FLAG_VALUE_LIST.join(", ")}.`,
|
|
5383
|
+
repair: `Re-run the doctor naming the runtime \u2014 one of: ${RUNTIME_FLAG_VALUE_LIST.join(", ")}.`
|
|
5384
|
+
});
|
|
5385
|
+
} else if (configPath === null && input2.runtime === "") {
|
|
5386
|
+
checks.push({
|
|
5387
|
+
id: "runtime_config",
|
|
5388
|
+
label: "Runtime MCP config",
|
|
5389
|
+
level: "failed",
|
|
5390
|
+
detail: `Runtime is unknown \u2014 no runtime flag was given and the connector's record in ${primaryDirectory ?? input.credentialsDir ?? "~/.haven/agents"} carries no resolvable ${exports.CONNECT_OUTCOME_FILENAME} runtime. The runtime config was NOT checked. Re-run the doctor naming the runtime \u2014 one of: ${RUNTIME_FLAG_VALUE_LIST.join(", ")}.`,
|
|
5391
|
+
repair: `Re-run the doctor naming the runtime \u2014 one of: ${RUNTIME_FLAG_VALUE_LIST.join(", ")}.`
|
|
5392
|
+
});
|
|
5393
|
+
} else if (configPath === null) {
|
|
5394
|
+
checks.push({
|
|
5395
|
+
id: "runtime_config",
|
|
5396
|
+
label: "Runtime MCP config",
|
|
5397
|
+
level: "ok",
|
|
5398
|
+
detail: `Runtime '${input2.runtime}' is configured through its own CLI or by hand (${input2.runtime === "other" ? "manual runtime" : "CLI-managed"}) and has no file-based config the connector owns \u2014 skipping the file check.`
|
|
5399
|
+
});
|
|
5400
|
+
} else if (configText === null) {
|
|
5401
|
+
checks.push({
|
|
5402
|
+
id: "runtime_config",
|
|
5403
|
+
label: "Runtime MCP config",
|
|
5404
|
+
level: "failed",
|
|
5405
|
+
detail: `No runtime config at ${configPath}.`,
|
|
5406
|
+
repair: repairCommandFor(input2.runtime)
|
|
5407
|
+
});
|
|
5469
5408
|
} else {
|
|
5470
|
-
|
|
5409
|
+
const primaryIdentity = await readIdentity(primaryDirectory ?? "");
|
|
5410
|
+
const primarySidecar = primaryDirectory ? await readRuntimeSidecar(primaryDirectory) : null;
|
|
5411
|
+
const hasHaven = primaryIdentity?.hosted_mcp_url ? configText.includes(primaryIdentity.hosted_mcp_url) : configText.includes("haven");
|
|
5412
|
+
const signerViaNpx = configText.includes("@haven_ai/signer");
|
|
5413
|
+
const wrapperReferenced = primarySidecar ? configText.includes(primarySidecar.wrapper_path) : false;
|
|
5414
|
+
const ok = hasHaven && !signerViaNpx && (primarySidecar ? wrapperReferenced : true);
|
|
5415
|
+
checks.push({
|
|
5416
|
+
id: "runtime_config",
|
|
5417
|
+
label: "Runtime MCP config",
|
|
5418
|
+
level: ok ? "ok" : "failed",
|
|
5419
|
+
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)" : ""}.`,
|
|
5420
|
+
...ok ? {} : { repair: repairCommandFor(input2.runtime) }
|
|
5421
|
+
});
|
|
5471
5422
|
}
|
|
5472
|
-
|
|
5473
|
-
|
|
5474
|
-
|
|
5475
|
-
const intPart = s.slice(0, s.length - decimals) || "0";
|
|
5476
|
-
const fracPart = s.slice(s.length - decimals).replace(/0+$/, "");
|
|
5477
|
-
return fracPart ? `${intPart}.${fracPart}` : intPart;
|
|
5478
|
-
}
|
|
5479
|
-
function describeResetPeriod(resetPeriodMin) {
|
|
5480
|
-
if (resetPeriodMin === 1440) return "per day";
|
|
5481
|
-
if (resetPeriodMin === 10080) return "per week";
|
|
5482
|
-
if (resetPeriodMin === 43200) return "per month";
|
|
5483
|
-
if (resetPeriodMin === 60) return "per hour";
|
|
5484
|
-
if (resetPeriodMin === 0) return "in total";
|
|
5485
|
-
return `every ${resetPeriodMin} minutes`;
|
|
5486
|
-
}
|
|
5487
|
-
function describeApprovedBudget(budget) {
|
|
5488
|
-
const token = sdk.resolveTokenFromAddress(budget.token_address);
|
|
5489
|
-
const amount = token ? `${formatAtomicAmount(BigInt(budget.amount), token.decimals)} ${budget.token_symbol}` : `${budget.amount} ${budget.token_symbol} (atomic units)`;
|
|
5490
|
-
return `${amount} ${describeResetPeriod(budget.reset_period_min)}`;
|
|
5491
|
-
}
|
|
5492
|
-
function describeWaitBound(timeoutMs) {
|
|
5493
|
-
if (timeoutMs >= 12e4) {
|
|
5494
|
-
const minutes = Math.round(timeoutMs / 6e4);
|
|
5495
|
-
return `${minutes} minutes`;
|
|
5423
|
+
for (const id of ["hosted_mcp", "identity_match", "rekey_pending"]) {
|
|
5424
|
+
const check = primaryChecksById.get(id);
|
|
5425
|
+
if (check) checks.push(check);
|
|
5496
5426
|
}
|
|
5497
|
-
|
|
5498
|
-
|
|
5499
|
-
|
|
5500
|
-
|
|
5501
|
-
|
|
5502
|
-
|
|
5503
|
-
|
|
5504
|
-
|
|
5505
|
-
|
|
5506
|
-
|
|
5507
|
-
|
|
5508
|
-
|
|
5509
|
-
|
|
5510
|
-
|
|
5511
|
-
for (let i = 0; i < maxPolls; i++) {
|
|
5512
|
-
if (i > 0) await sleep(intervalMs);
|
|
5513
|
-
let status;
|
|
5514
|
-
try {
|
|
5515
|
-
status = await api.getConnectorStatus(setupId, apiKey);
|
|
5516
|
-
} catch (err) {
|
|
5517
|
-
if (err instanceof ConnectRequestError && (err.status === 401 || err.status === 404)) {
|
|
5518
|
-
log("This setup ended in Haven \u2014 start a fresh connection from the dashboard when ready.");
|
|
5519
|
-
return "ended";
|
|
5427
|
+
const otherEntries = inventory.filter((entry) => entry.directory !== primaryDirectory);
|
|
5428
|
+
if (otherEntries.length > 0) {
|
|
5429
|
+
const live = [];
|
|
5430
|
+
const revoked = [];
|
|
5431
|
+
const unverifiable = [];
|
|
5432
|
+
const retired = [];
|
|
5433
|
+
for (const entry of otherEntries) {
|
|
5434
|
+
const identity = await readIdentity(entry.directory);
|
|
5435
|
+
const tombstone = await readAgentTombstone(entry.directory);
|
|
5436
|
+
const otherAgent = entry.agentId ?? path.basename(entry.directory);
|
|
5437
|
+
if (!identity?.api_key || !identity.api_url) {
|
|
5438
|
+
if (tombstone) retired.push(`${otherAgent} (retired ${tombstone.retired_at})`);
|
|
5439
|
+
else unverifiable.push(`${otherAgent} (no stored key/API URL to probe)`);
|
|
5440
|
+
continue;
|
|
5520
5441
|
}
|
|
5521
|
-
|
|
5522
|
-
|
|
5523
|
-
|
|
5524
|
-
|
|
5525
|
-
|
|
5526
|
-
status.approved_budget ? `Budget approved \u{1F389} \u2014 I can now spend up to ${describeApprovedBudget(status.approved_budget)} from your Haven wallet.` : "Budget approved \u{1F389} \u2014 the agent can now spend within its Haven rules."
|
|
5442
|
+
const suffix = tombstone ? " [tombstoned \u2014 key material still present]" : "";
|
|
5443
|
+
const probe = await (deps.probeHostedIdentity ?? probeHostedAgentIdentity)(
|
|
5444
|
+
identity.api_key,
|
|
5445
|
+
identity.api_url,
|
|
5446
|
+
deps.fetch
|
|
5527
5447
|
);
|
|
5528
|
-
|
|
5529
|
-
|
|
5530
|
-
|
|
5531
|
-
log(`This setup ended in Haven (${status.status}) \u2014 start a fresh connection from the dashboard when ready.`);
|
|
5532
|
-
return "ended";
|
|
5448
|
+
if (probe.status === "ok") live.push({ label: `${otherAgent}${suffix}`, entry });
|
|
5449
|
+
else if (probe.status === "unauthorized") revoked.push(`${otherAgent}${suffix}`);
|
|
5450
|
+
else unverifiable.push(`${otherAgent} (${probe.status})${suffix}`);
|
|
5533
5451
|
}
|
|
5534
|
-
|
|
5535
|
-
if (
|
|
5536
|
-
|
|
5537
|
-
|
|
5538
|
-
|
|
5452
|
+
const parts = [];
|
|
5453
|
+
if (live.length > 0) parts.push(`STILL SPEND-CAPABLE: ${live.map((item) => item.label).join(", ")}`);
|
|
5454
|
+
if (revoked.length > 0) parts.push(`already revoked: ${revoked.join(", ")}`);
|
|
5455
|
+
if (retired.length > 0) parts.push(`tombstoned (keys removed): ${retired.join(", ")}`);
|
|
5456
|
+
if (unverifiable.length > 0) parts.push(`could not verify: ${unverifiable.join(", ")}`);
|
|
5457
|
+
const knownIds = new Set([...inventory].map((e) => e.agentId ?? path.basename(e.directory)));
|
|
5458
|
+
const ledgerDir = input.credentialsDir ? tombstonesDirForAgentDirectory(input.credentialsDir, homeDir) : path.join(homeDir, ".haven", "tombstones");
|
|
5459
|
+
const ghostRecords = (await readTombstoneRecords(ledgerDir)).filter(
|
|
5460
|
+
(rec) => !knownIds.has(rec.agent_id)
|
|
5461
|
+
);
|
|
5462
|
+
if (ghostRecords.length > 0) {
|
|
5463
|
+
parts.push(
|
|
5464
|
+
`retired records (dir removed): ${ghostRecords.map((rec) => `${rec.agent_id} (${rec.reason})`).join(", ")}`
|
|
5539
5465
|
);
|
|
5540
5466
|
}
|
|
5467
|
+
const supersededLive = live.filter((item) => item.entry.classification !== "wired").map((item) => item.label);
|
|
5468
|
+
const classificationUnreliable = configText === null && runtimeOwnsNoConfig;
|
|
5469
|
+
const supersededLevel = supersededLive.length === 0 ? "ok" : classificationUnreliable ? "advisory" : "failed";
|
|
5470
|
+
checks.push({
|
|
5471
|
+
id: "superseded_agents",
|
|
5472
|
+
label: "Superseded agent credentials",
|
|
5473
|
+
level: supersededLevel,
|
|
5474
|
+
detail: supersededLevel === "failed" ? `${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.` : supersededLevel === "advisory" ? `${otherEntries.length} other credential dir(s) found \u2014 ${parts.join("; ")}. Runtime '${input2.runtime}' has no config file the connector can read, so which of these agents are wired cannot be verified from this machine: a live key here may be an agent you use deliberately, or one a host started before your latest setup is still spending as.` : `${otherEntries.length} other credential dir(s) found \u2014 ${parts.join("; ")}.`,
|
|
5475
|
+
...supersededLevel === "failed" ? {
|
|
5476
|
+
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.`
|
|
5477
|
+
} : supersededLevel === "advisory" ? {
|
|
5478
|
+
repair: `Check ${supersededLive.join(", ")} on the Haven agent page: revoke the ones you no longer use, then remove their director(y/ies) under ~/.haven/agents. Connect never revokes or deletes for you.`
|
|
5479
|
+
} : {}
|
|
5480
|
+
});
|
|
5541
5481
|
}
|
|
5542
|
-
|
|
5543
|
-
|
|
5544
|
-
);
|
|
5545
|
-
|
|
5546
|
-
|
|
5547
|
-
|
|
5548
|
-
|
|
5549
|
-
|
|
5550
|
-
return [
|
|
5551
|
-
"Next steps:",
|
|
5552
|
-
`1. ${approveStep}`,
|
|
5553
|
-
"2. Finish the manual MCP setup using the secret-free file references printed above, then start a fresh session in your runtime.",
|
|
5554
|
-
`3. ${runtimeVerificationInstruction(result.runtime)}`
|
|
5555
|
-
];
|
|
5482
|
+
const bindings = (await Promise.all(
|
|
5483
|
+
inventory.filter((entry) => entry.classification !== "retired").map(async (entry) => ({ entry, binding: await readMcpServerBinding(entry.directory) }))
|
|
5484
|
+
)).filter((item) => item.binding !== null);
|
|
5485
|
+
const byName = /* @__PURE__ */ new Map();
|
|
5486
|
+
for (const item of bindings) {
|
|
5487
|
+
const list = byName.get(item.binding.server_name) ?? [];
|
|
5488
|
+
list.push(item);
|
|
5489
|
+
byName.set(item.binding.server_name, list);
|
|
5556
5490
|
}
|
|
5557
|
-
|
|
5558
|
-
|
|
5559
|
-
|
|
5560
|
-
|
|
5491
|
+
const rebound = [...byName.entries()].filter(([, items]) => items.length > 1);
|
|
5492
|
+
if (rebound.length > 0) {
|
|
5493
|
+
const parts = rebound.map(([name, items]) => {
|
|
5494
|
+
const ordered = [...items].sort((a, b) => a.binding.bound_at < b.binding.bound_at ? -1 : a.binding.bound_at > b.binding.bound_at ? 1 : 0);
|
|
5495
|
+
const backends = new Set(ordered.map((i) => withoutUserinfo(i.binding.api_url)));
|
|
5496
|
+
return `'${name}': ` + ordered.map((i) => `${i.binding.agent_id} on ${withoutUserinfo(i.binding.api_url)} at ${i.binding.bound_at} [${i.entry.classification}]`).join(" \u2192 ") + (backends.size > 1 ? " (BACKEND CHANGED)" : "");
|
|
5497
|
+
});
|
|
5498
|
+
checks.push({
|
|
5499
|
+
id: "mcp_server_name_rebound",
|
|
5500
|
+
label: "MCP server names bound more than once",
|
|
5501
|
+
level: "advisory",
|
|
5502
|
+
detail: `${rebound.length} MCP server name${rebound.length === 1 ? "" : "s"} changed hands on this machine (locally recorded bindings; the backend's own record is the authority for the same backend): ${parts.join("; ")}. A saved session, script or document naming the server may still mean the earlier agent.`,
|
|
5503
|
+
repair: `Retire the earlier director(y/ies) with ${RERUN} --unwire <dir> to release the name, or keep both and address them by --name.`
|
|
5504
|
+
});
|
|
5561
5505
|
}
|
|
5562
|
-
|
|
5563
|
-
|
|
5564
|
-
|
|
5565
|
-
|
|
5506
|
+
const parkedElsewhere = inventory.filter((entry) => entry.directory !== primaryDirectory && entry.rekeyPending).map((entry) => ({ entry, pending: entry.rekeyPending }));
|
|
5507
|
+
if (parkedElsewhere.length > 0) {
|
|
5508
|
+
const abandoned = parkedElsewhere.filter((item) => item.pending.state !== "pending");
|
|
5509
|
+
const describe = (item) => `${item.entry.slug ?? item.entry.agentId ?? path.basename(item.entry.directory)} (${item.pending.state}, ${item.pending.path})`;
|
|
5510
|
+
checks.push({
|
|
5511
|
+
id: "rekey_pending_elsewhere",
|
|
5512
|
+
label: "Parked re-keys in other credential directories",
|
|
5513
|
+
level: abandoned.length === 0 ? "ok" : "failed",
|
|
5514
|
+
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(", ")}.`,
|
|
5515
|
+
...abandoned.length > 0 ? {
|
|
5516
|
+
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."
|
|
5517
|
+
} : {}
|
|
5518
|
+
});
|
|
5566
5519
|
}
|
|
5567
|
-
const
|
|
5568
|
-
|
|
5569
|
-
|
|
5570
|
-
|
|
5571
|
-
|
|
5572
|
-
|
|
5573
|
-
|
|
5574
|
-
|
|
5520
|
+
const signerProcess = primaryChecksById.get("signer_process");
|
|
5521
|
+
if (signerProcess) checks.push(signerProcess);
|
|
5522
|
+
const prune = await (deps.pruneSignerRuntimes ?? pruneSignerRuntimes)({ dryRun: true, measure: false }, { homeDir, credentialsDir: input.credentialsDir });
|
|
5523
|
+
const unused = prune.entries.filter((entry) => entry.action === "would_remove");
|
|
5524
|
+
if (unused.length > 0) {
|
|
5525
|
+
checks.push({
|
|
5526
|
+
id: "signer_runtime_unused",
|
|
5527
|
+
label: "Unused signer-runtime directories",
|
|
5528
|
+
level: "advisory",
|
|
5529
|
+
detail: `${unused.length} signer-runtime director${unused.length === 1 ? "y" : "ies"} under ${prune.root} that no credential directory names: ${unused.map((entry) => entry.key).join(", ")}. Nothing is broken; they are left over from earlier pins or overrides (sizes: --prune-signer-runtimes --dry-run).`,
|
|
5530
|
+
repair: `Run: ${RERUN} --prune-signer-runtimes (add --dry-run to list only).`
|
|
5531
|
+
});
|
|
5575
5532
|
}
|
|
5576
|
-
|
|
5577
|
-
|
|
5578
|
-
|
|
5579
|
-
|
|
5580
|
-
|
|
5581
|
-
|
|
5533
|
+
if (resolution.origin === "record") {
|
|
5534
|
+
const rc = checks.find((check) => check.id === "runtime_config");
|
|
5535
|
+
if (rc) {
|
|
5536
|
+
rc.detail += ` (Resolved '${resolution.runtime}' from ${path.join(directory ?? "", exports.CONNECT_OUTCOME_FILENAME)}; pass --runtime to check a different one.)`;
|
|
5537
|
+
}
|
|
5538
|
+
}
|
|
5539
|
+
const restart = normalizedRuntime === null ? false : restartRequiredForRuntime(input2.runtime, deps.env);
|
|
5540
|
+
checks.push({
|
|
5541
|
+
id: "restart",
|
|
5542
|
+
label: "Runtime restart",
|
|
5543
|
+
level: "ok",
|
|
5544
|
+
detail: restart ? "This runtime loads MCP config at startup \u2014 restart it after any repair before expecting the tools to appear." : input2.runtime === "" ? "Runtime is unknown \u2014 whether a restart is needed cannot be determined. Re-run the doctor naming the runtime for a definitive answer." : "No restart requirement known for this runtime."
|
|
5545
|
+
});
|
|
5546
|
+
const wiredChecks = inventory.filter((entry) => entry.classification === "wired").flatMap((entry) => entry.checks);
|
|
5547
|
+
const finalChecks = checks.map(finalizeCheck);
|
|
5548
|
+
const level = rollUpLevel([...finalChecks, ...wiredChecks]);
|
|
5549
|
+
return {
|
|
5550
|
+
version: 1,
|
|
5551
|
+
ok: level !== "failed",
|
|
5552
|
+
level,
|
|
5553
|
+
runtime: input2.runtime,
|
|
5554
|
+
credentialDirectory: primaryDirectory,
|
|
5555
|
+
checks: finalChecks,
|
|
5556
|
+
agents: inventory,
|
|
5557
|
+
...signerCapabilities ? { signerCapabilities } : {}
|
|
5558
|
+
};
|
|
5582
5559
|
}
|
|
5583
|
-
function
|
|
5584
|
-
|
|
5585
|
-
|
|
5560
|
+
async function runRepair(input, deps = {}) {
|
|
5561
|
+
const homeDir = deps.homeDir ?? os.homedir();
|
|
5562
|
+
const messages = [];
|
|
5563
|
+
const { directory, others } = await discoverCredentialDirectory(homeDir, input.credentialsDir);
|
|
5564
|
+
if (others.length > 0) {
|
|
5565
|
+
messages.push(`Note: ${others.length} other agent credential dir(s) exist \u2014 run --doctor for their status.`);
|
|
5586
5566
|
}
|
|
5587
|
-
if (
|
|
5588
|
-
return
|
|
5567
|
+
if (!directory) {
|
|
5568
|
+
return {
|
|
5569
|
+
ok: false,
|
|
5570
|
+
messages: [`No agent credentials found to repair \u2014 run the full setup: ${RERUN} --setup <token>.`]
|
|
5571
|
+
};
|
|
5589
5572
|
}
|
|
5590
|
-
|
|
5591
|
-
|
|
5592
|
-
|
|
5593
|
-
async function listExistingKeyedAgents(baseDir) {
|
|
5594
|
-
const root = defaultCredentialRoot(baseDir);
|
|
5595
|
-
let entries = [];
|
|
5596
|
-
try {
|
|
5597
|
-
entries = await promises.readdir(root);
|
|
5598
|
-
} catch {
|
|
5599
|
-
return [];
|
|
5573
|
+
const resolution = await resolveDoctorRuntime(input, directory);
|
|
5574
|
+
if (resolution.origin === "record") {
|
|
5575
|
+
messages.push(`Runtime not given \u2014 resolved '${resolution.runtime}' from ${path.join(directory, exports.CONNECT_OUTCOME_FILENAME)}.`);
|
|
5600
5576
|
}
|
|
5601
|
-
const
|
|
5602
|
-
|
|
5603
|
-
|
|
5604
|
-
|
|
5605
|
-
|
|
5606
|
-
|
|
5607
|
-
|
|
5608
|
-
|
|
5609
|
-
|
|
5610
|
-
|
|
5611
|
-
}
|
|
5612
|
-
const { accountAddress } = readStoredAccountAddress(identity, agent);
|
|
5613
|
-
out.push({ agentId: typeof identity.agent_id === "string" ? identity.agent_id : entry, directory, accountAddress: accountAddress ?? null });
|
|
5614
|
-
} catch {
|
|
5615
|
-
}
|
|
5577
|
+
const runtime = resolution.runtime;
|
|
5578
|
+
const input2 = { ...input, runtime };
|
|
5579
|
+
if (runtime === "") {
|
|
5580
|
+
return {
|
|
5581
|
+
ok: false,
|
|
5582
|
+
messages: [
|
|
5583
|
+
"Runtime is unknown \u2014 no runtime flag was given and the connector record carries no resolvable runtime.",
|
|
5584
|
+
`Repair rewrites the runtime config, so it will not guess. Re-run repair naming the runtime \u2014 one of: ${RUNTIME_FLAG_VALUE_LIST.join(", ")}.`
|
|
5585
|
+
]
|
|
5586
|
+
};
|
|
5616
5587
|
}
|
|
5617
|
-
|
|
5618
|
-
}
|
|
5619
|
-
async function listOtherAgentIds(baseDir, currentDirectory) {
|
|
5620
|
-
const root = defaultCredentialRoot(baseDir);
|
|
5621
|
-
let entries = [];
|
|
5588
|
+
let identity;
|
|
5622
5589
|
try {
|
|
5623
|
-
|
|
5590
|
+
identity = JSON.parse(await promises.readFile(path.join(directory, "identity.json"), "utf8"));
|
|
5624
5591
|
} catch {
|
|
5625
|
-
return
|
|
5592
|
+
return { ok: false, messages: ["identity.json is unreadable \u2014 re-run the full setup with a fresh token."] };
|
|
5626
5593
|
}
|
|
5627
|
-
|
|
5628
|
-
|
|
5629
|
-
|
|
5630
|
-
|
|
5631
|
-
|
|
5632
|
-
await promises.stat(identityPath);
|
|
5633
|
-
} catch {
|
|
5634
|
-
continue;
|
|
5635
|
-
}
|
|
5594
|
+
if (!identity.api_key || !(identity.hosted_mcp_url || identity.api_url)) {
|
|
5595
|
+
return { ok: false, messages: ["identity.json lacks the stored API key / hosted URL \u2014 re-run the full setup."] };
|
|
5596
|
+
}
|
|
5597
|
+
const configPath = runtimeConfigPathFor(normalizeRuntimeName(input2.runtime) ?? input2.runtime, homeDir);
|
|
5598
|
+
if (configPath) {
|
|
5636
5599
|
try {
|
|
5637
|
-
const
|
|
5638
|
-
|
|
5600
|
+
const existing = await promises.readFile(configPath, "utf8");
|
|
5601
|
+
if (existing.includes("bin/haven-mcp") || existing.includes(".haven/mcp-runtime")) {
|
|
5602
|
+
return {
|
|
5603
|
+
ok: false,
|
|
5604
|
+
messages: [
|
|
5605
|
+
`The config at ${configPath} is the LOCAL-stdio topology (--local). Repair currently rewrites only the hosted+signer shape and will not touch it.`,
|
|
5606
|
+
"Re-run your original connector command (with --local) to repair a local-stdio install."
|
|
5607
|
+
]
|
|
5608
|
+
};
|
|
5609
|
+
}
|
|
5639
5610
|
} catch {
|
|
5640
|
-
ids.push(entry);
|
|
5641
5611
|
}
|
|
5642
5612
|
}
|
|
5643
|
-
|
|
5644
|
-
|
|
5645
|
-
|
|
5646
|
-
|
|
5613
|
+
const existingSidecar = await readRuntimeSidecar(directory);
|
|
5614
|
+
const serverName = existingSidecar?.server_name;
|
|
5615
|
+
const signerPath = path.join(directory, "signer.json");
|
|
5616
|
+
const prepared = await prepareSignerRuntime(
|
|
5617
|
+
{ credentialDirectory: directory, signerPath, homeDir, serverName },
|
|
5618
|
+
{ runCommand: deps.runCommand, env: deps.env }
|
|
5619
|
+
);
|
|
5620
|
+
messages.push(...prepared.messages);
|
|
5621
|
+
const names = serverNamesFor(serverName);
|
|
5622
|
+
messages.push(`Rewriting MCP entries ${names.hosted} / ${names.signer}${serverName ? ` (agent "${serverName}")` : " (unnamed pair)"} \u2014 no other pair is touched.`);
|
|
5623
|
+
const configResult = await writeRuntimeConfig({
|
|
5624
|
+
// Normalized for the WRITE too (#3145 review round 3): `writeRuntimeConfig`
|
|
5625
|
+
// switches on the id, and the raw alias fell to its "manual runtime" arm
|
|
5626
|
+
// — a repair that reported success while writing nothing.
|
|
5627
|
+
runtime: normalizeRuntimeName(input2.runtime) ?? input2.runtime,
|
|
5628
|
+
hostedMcpUrl: identity.hosted_mcp_url ?? `${identity.api_url}/mcp`,
|
|
5629
|
+
apiKey: identity.api_key,
|
|
5630
|
+
identityPath: path.join(directory, "identity.json"),
|
|
5631
|
+
signerPath,
|
|
5632
|
+
credentialDirectory: directory,
|
|
5633
|
+
signerCommand: { command: prepared.command, args: prepared.args },
|
|
5634
|
+
homeDir,
|
|
5635
|
+
mode: "hosted",
|
|
5636
|
+
serverName
|
|
5637
|
+
});
|
|
5638
|
+
messages.push(...configResult.messages);
|
|
5639
|
+
messages.push("Repair complete \u2014 restart the runtime, then verify with --doctor.");
|
|
5640
|
+
return { ok: true, messages };
|
|
5647
5641
|
}
|
|
5642
|
+
var RERUN;
|
|
5643
|
+
var init_doctor = __esm({
|
|
5644
|
+
"src/doctor.ts"() {
|
|
5645
|
+
init_prune_runtimes();
|
|
5646
|
+
init_runtime_manifest();
|
|
5647
|
+
init_probes();
|
|
5648
|
+
init_signer_runtime();
|
|
5649
|
+
init_runtime_spec_override();
|
|
5650
|
+
init_config_writers();
|
|
5651
|
+
init_runtime_registry();
|
|
5652
|
+
init_signer_consent();
|
|
5653
|
+
init_tombstone();
|
|
5654
|
+
init_server_names();
|
|
5655
|
+
init_storage();
|
|
5656
|
+
init_redact();
|
|
5657
|
+
RERUN = sdk.connectorRerunCommand();
|
|
5658
|
+
}
|
|
5659
|
+
});
|
|
5648
5660
|
|
|
5649
5661
|
// src/args.ts
|
|
5662
|
+
init_runtime();
|
|
5650
5663
|
init_server_names();
|
|
5651
5664
|
init_rekey_messages();
|
|
5652
5665
|
function parseArgs(argv, env = process.env) {
|
|
5653
5666
|
const options = {
|
|
5654
5667
|
apiBaseUrl: env.HAVEN_API_URL ?? "http://localhost:3001",
|
|
5655
|
-
connectorVersion: CONNECTOR_VERSION
|
|
5668
|
+
connectorVersion: exports.CONNECTOR_VERSION
|
|
5656
5669
|
};
|
|
5657
5670
|
let help = false;
|
|
5658
5671
|
let json = false;
|
|
@@ -5729,7 +5742,7 @@ function parseArgs(argv, env = process.env) {
|
|
|
5729
5742
|
} else if (arg === "--local" || arg === "--local-mcp") {
|
|
5730
5743
|
options.localMcp = true;
|
|
5731
5744
|
} else if (arg === "--version") {
|
|
5732
|
-
process.stdout.write(`${CONNECTOR_VERSION}
|
|
5745
|
+
process.stdout.write(`${exports.CONNECTOR_VERSION}
|
|
5733
5746
|
`);
|
|
5734
5747
|
process.exit(0);
|
|
5735
5748
|
} else {
|
|
@@ -5919,6 +5932,8 @@ function requireValue(argv, index, option) {
|
|
|
5919
5932
|
init_api();
|
|
5920
5933
|
init_key();
|
|
5921
5934
|
init_redact();
|
|
5935
|
+
init_runtime();
|
|
5936
|
+
init_runtime();
|
|
5922
5937
|
init_redact();
|
|
5923
5938
|
init_connect_error();
|
|
5924
5939
|
function failSubcommand(io, json, err, envelope, fallback) {
|
|
@@ -6351,11 +6366,10 @@ init_runtime_install();
|
|
|
6351
6366
|
init_signer_runtime();
|
|
6352
6367
|
init_runtime_registry();
|
|
6353
6368
|
init_connect_error();
|
|
6369
|
+
init_installed_clients();
|
|
6354
6370
|
init_storage();
|
|
6355
6371
|
init_runtime_manifest();
|
|
6356
6372
|
|
|
6357
|
-
exports.CONNECTOR_VERSION = CONNECTOR_VERSION;
|
|
6358
|
-
exports.CONNECT_OUTCOME_SCHEMA_VERSION = CONNECT_OUTCOME_SCHEMA_VERSION;
|
|
6359
6373
|
exports.completionOutcome = completionOutcome;
|
|
6360
6374
|
exports.createConnectApiClient = createConnectApiClient;
|
|
6361
6375
|
exports.defaultAgentDirectory = defaultAgentDirectory;
|