n2n-nexus 0.8.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/CONTRIBUTING.md +49 -0
  3. package/README.md +157 -77
  4. package/SECURITY.md +37 -0
  5. package/build/cli/client-command.js +58 -0
  6. package/build/cli/doctor.js +55 -57
  7. package/build/cli/entry.js +5 -0
  8. package/build/cli/hook.js +104 -16
  9. package/build/cli/install.js +72 -21
  10. package/build/cli/mcp-config.js +66 -0
  11. package/build/client/discovery.js +115 -0
  12. package/build/client/nexus-client.js +8 -2
  13. package/build/contract.js +69 -0
  14. package/build/index.js +12 -18
  15. package/build/server/nexus.js +63 -35
  16. package/contract/errors.json +52 -0
  17. package/contract/hook.json +156 -0
  18. package/contract/tools.json +2812 -0
  19. package/docs/ARCHITECTURE.md +142 -108
  20. package/docs/ARCHITECTURE_zh.md +144 -110
  21. package/docs/ASSISTANT_GUIDE.md +5 -4
  22. package/docs/ASSISTANT_GUIDE_zh.md +134 -0
  23. package/docs/MEETING_MINUTES_2025-12-29.md +166 -0
  24. package/docs/README_zh.md +159 -79
  25. package/docs/TOOLS_REFERENCE.md +404 -0
  26. package/docs/discussion_2025-12-29.md +727 -0
  27. package/llms.txt +16 -5
  28. package/package.json +12 -8
  29. package/build/cli/autostart.js +0 -64
  30. package/build/config/cli.js +0 -8
  31. package/build/config/paths.js +0 -38
  32. package/build/constants.js +0 -18
  33. package/build/daemon/hook-contract.js +0 -68
  34. package/build/daemon/index.js +0 -57
  35. package/build/daemon/rate-limit.js +0 -62
  36. package/build/daemon/server.js +0 -862
  37. package/build/daemon/tool-outputs.js +0 -180
  38. package/build/daemon/tools.js +0 -326
  39. package/build/storage/agents.js +0 -227
  40. package/build/storage/docs.js +0 -81
  41. package/build/storage/events.js +0 -31
  42. package/build/storage/fs-utils.js +0 -42
  43. package/build/storage/global-messages.js +0 -44
  44. package/build/storage/index.js +0 -116
  45. package/build/storage/migrations.js +0 -87
  46. package/build/storage/paths.js +0 -23
  47. package/build/storage/projects.js +0 -53
  48. package/build/storage/registry.js +0 -330
  49. package/build/storage/sqlite-meeting.js +0 -323
  50. package/build/storage/sqlite.js +0 -215
  51. package/build/storage/tasks.js +0 -138
  52. package/build/types.js +0 -1
  53. package/build/utils/async-mutex.js +0 -36
@@ -1,17 +1,20 @@
1
1
  /**
2
2
  * `n2n-nexus doctor [claude|codex]`: check that the Node path and the entry
3
3
  * script in the hook commands and in the MCP server command that `install`
4
- * wrote still exist and run, and say how to fix what does not. Without a
5
- * client both are checked; a client with nothing installed is only reported
6
- * when it was named. Exit code 1 when a check failed.
4
+ * wrote still exist and run, that the host those commands talk to answers
5
+ * GET /health as n2n-nexus-host with this client's contract version, and say
6
+ * how to fix what does not. Without a client both are checked; a client with
7
+ * nothing installed is only reported when it was named. Exit code 1 when a
8
+ * check failed.
7
9
  */
8
10
  import { spawnSync } from "node:child_process";
9
11
  import fs from "node:fs";
10
- import os from "node:os";
11
- import path from "node:path";
12
- import { HOOK_CLIENTS, MCP_SERVER_NAME, isHookClient } from "../daemon/hook-contract.js";
12
+ import { CONTRACT_VERSION, HOOK_CLIENTS, MCP_SERVER_NAME, isHookClient, noDaemonHint } from "../contract.js";
13
+ import { NexusClient, NexusToolError } from "../client/nexus-client.js";
14
+ import { LOCAL_ENDPOINT, resolveEndpoint } from "../client/discovery.js";
13
15
  import { pkg } from "../config/index.js";
14
- import { InstallError, VERSIONED_NODE_DIR, configFile, isOurs, parseVersion, readConfig, satisfiesEngines } from "./install.js";
16
+ import { VERSIONED_NODE_DIR, configFile, isOurs, parseVersion, readConfig, satisfiesEngines } from "./install.js";
17
+ import { mcpConfigFile, readMcpCommand } from "./mcp-config.js";
15
18
  const ok = (text) => ({ ok: true, text });
16
19
  const bad = (text) => ({ ok: false, text });
17
20
  const VERSIONED_NOTE = "in a version directory that an upgrade may remove";
@@ -39,59 +42,46 @@ export function checkNode(node) {
39
42
  return ok(`${text}${VERSIONED_NODE_DIR.test(node) ? `, ${VERSIONED_NOTE}` : ""}`);
40
43
  }
41
44
  const checkEntry = (entry) => fs.existsSync(entry) ? ok("ok") : bad("missing");
42
- /** Where the client keeps the MCP server command. */
43
- export function mcpConfigFile(client) {
44
- if (client === "claude") {
45
- return path.join(process.env.CLAUDE_CONFIG_DIR || os.homedir(), ".claude.json");
46
- }
47
- return path.join(process.env.CODEX_HOME || path.join(os.homedir(), ".codex"), "config.toml");
48
- }
49
- /** The MCP server command the client has for n2n-nexus, or undefined when not registered. */
50
- export function readMcpCommand(client, file) {
51
- let text;
45
+ /** The `--endpoint` a hook command was installed with, if any. */
46
+ const hookEndpoint = (command) => / --endpoint (\S+)/.exec(command)?.[1];
47
+ /** Ask the host at `endpoint` for GET /health: it must be n2n-nexus-host speaking this client's contract version. */
48
+ export async function checkHost(endpoint) {
49
+ let health;
52
50
  try {
53
- text = fs.readFileSync(file, "utf8");
51
+ health = await new NexusClient({ endpoint, timeoutMs: 3000 }).health();
54
52
  }
55
53
  catch (error) {
56
- if (error.code === "ENOENT")
57
- return undefined;
58
- throw error;
59
- }
60
- if (client === "claude") {
61
- let parsed;
62
- try {
63
- parsed = JSON.parse(text);
64
- }
65
- catch (error) {
66
- throw new InstallError(`${file} is not valid JSON (${error.message}).`);
67
- }
68
- const servers = parsed?.mcpServers;
69
- const server = servers?.[MCP_SERVER_NAME];
70
- if (!server || typeof server.command !== "string")
71
- return undefined;
72
- return { command: server.command, args: Array.isArray(server.args) ? server.args.map(String) : [] };
73
- }
74
- // Codex: a TOML table [mcp_servers.n2n-nexus] (the key may be quoted) with command = "..." and args = [...].
75
- const lines = text.split("\n");
76
- const start = lines.findIndex((line) => new RegExp(`^\\s*\\[mcp_servers\\.("?)${MCP_SERVER_NAME}\\1\\]\\s*$`).test(line));
77
- if (start === -1)
78
- return undefined;
79
- let command;
80
- let args = [];
81
- for (const line of lines.slice(start + 1)) {
82
- if (/^\s*\[/.test(line))
83
- break;
84
- const c = /^\s*command\s*=\s*"((?:[^"\\]|\\.)*)"/.exec(line);
85
- if (c)
86
- command = JSON.parse(`"${c[1]}"`);
87
- const a = /^\s*args\s*=\s*\[(.*)\]/.exec(line);
88
- if (a)
89
- args = [...a[1].matchAll(/"((?:[^"\\]|\\.)*)"/g)].map((m) => JSON.parse(`"${m[1]}"`));
54
+ // It answered but refused (e.g. 403 for a Host name not in its allowedHosts): running, not missing.
55
+ if (error instanceof NexusToolError)
56
+ return bad(`answers with HTTP ${error.status}: ${error.message}`);
57
+ return bad(`not reachable (${error.message}). ${noDaemonHint(endpoint)}`);
58
+ }
59
+ if (health.service !== "n2n-nexus")
60
+ return bad("answers, but is not an n2n-nexus host");
61
+ const version = typeof health.version === "string" ? health.version : "unknown version";
62
+ if (health.contractVersion !== CONTRACT_VERSION) {
63
+ return bad(`n2n-nexus-host ${version} speaks contract version ${String(health.contractVersion)}, this client ${CONTRACT_VERSION}: upgrade the older of n2n-nexus-host and n2n-nexus`);
64
+ }
65
+ return ok(`n2n-nexus-host ${version}, contract version ${CONTRACT_VERSION}`);
66
+ }
67
+ /** Check the host at each endpoint; prints the report and returns whether all passed. */
68
+ async function doctorHosts(endpoints) {
69
+ let passed = true;
70
+ for (const configured of endpoints) {
71
+ const endpoint = await resolveEndpoint(configured);
72
+ const check = await checkHost(endpoint);
73
+ if (!check.ok)
74
+ passed = false;
75
+ const label = endpoint === configured ? endpoint : `${endpoint} (${configured})`;
76
+ process.stdout.write(`host ${label}\n ${check.ok ? "ok " : "FAIL"} ${check.text}\n`);
90
77
  }
91
- return command === undefined ? undefined : { command, args };
78
+ return passed;
92
79
  }
93
- /** Check one client; prints the report and returns whether everything passed, or undefined when nothing is installed. */
94
- function doctorClient(client) {
80
+ /**
81
+ * Check one client; prints the report and returns whether everything passed, or undefined when nothing is installed.
82
+ * Adds the endpoints its hook commands use (`defaultEndpoint` for those without --endpoint) to `endpoints`.
83
+ */
84
+ function doctorClient(client, endpoints, defaultEndpoint) {
95
85
  const hooksFile = configFile(client);
96
86
  const mcpFile = mcpConfigFile(client);
97
87
  const lines = [];
@@ -122,6 +112,8 @@ function doctorClient(client) {
122
112
  const mcp = readMcpCommand(client, mcpFile);
123
113
  if (commands.size === 0 && !mcp)
124
114
  return undefined;
115
+ for (const command of commands)
116
+ endpoints.add(hookEndpoint(command) ?? defaultEndpoint);
125
117
  lines.push(`${client}`);
126
118
  if (commands.size === 0)
127
119
  report(`hooks in ${hooksFile}`, bad("not installed"));
@@ -155,7 +147,7 @@ function doctorClient(client) {
155
147
  return !failed;
156
148
  }
157
149
  /** Parse `[claude|codex]`, run the checks and return the exit code. */
158
- export function runDoctor(argv) {
150
+ export async function runDoctor(argv) {
159
151
  const client = argv[0];
160
152
  if (client !== undefined && !isHookClient(client)) {
161
153
  process.stderr.write("Usage: n2n-nexus doctor [claude|codex]\n");
@@ -163,8 +155,10 @@ export function runDoctor(argv) {
163
155
  }
164
156
  try {
165
157
  let failed = false;
158
+ const defaultEndpoint = process.env.NEXUS_ENDPOINT || LOCAL_ENDPOINT;
159
+ const endpoints = new Set();
166
160
  for (const c of client ? [client] : HOOK_CLIENTS) {
167
- const result = doctorClient(c);
161
+ const result = doctorClient(c, endpoints, defaultEndpoint);
168
162
  if (result === undefined) {
169
163
  if (client) {
170
164
  process.stdout.write(`${c}\n FAIL nothing installed: run "n2n-nexus install ${c}".\n`);
@@ -178,6 +172,10 @@ export function runDoctor(argv) {
178
172
  failed = true;
179
173
  }
180
174
  }
175
+ if (endpoints.size === 0)
176
+ endpoints.add(defaultEndpoint);
177
+ if (!await doctorHosts(endpoints))
178
+ failed = true;
181
179
  return failed ? 1 : 0;
182
180
  }
183
181
  catch (error) {
@@ -0,0 +1,5 @@
1
+ import { fileURLToPath } from "node:url";
2
+ /** Absolute path of the package entry script (`build/index.js` next to `build/cli/`). */
3
+ export function entryScript() {
4
+ return fileURLToPath(new URL("../index.js", import.meta.url));
5
+ }
package/build/cli/hook.js CHANGED
@@ -1,12 +1,16 @@
1
1
  /**
2
- * `n2n-nexus hook <claude|codex> [--endpoint <url>]`: forward one client hook
3
- * event to the daemon and print its output. Runs on every tool call, so it
4
- * loads only node built-ins (no MCP SDK, zod or SQLite), and every failure is
5
- * silent: exit 0 with nothing on stdout, so the client carries on unaffected.
2
+ * `n2n-nexus hook <claude|codex> [--endpoint <url>] [--wait]`: forward one client
3
+ * hook event to the daemon and print its output, or with `--wait` run the
4
+ * background wait that wakes an idle conversation. Runs on every tool call, so
5
+ * it loads only node built-ins (no MCP SDK, zod or SQLite), and every failure
6
+ * is silent: exit 0 with nothing on stdout, so the client carries on unaffected.
6
7
  */
7
- import { HOOK_INPUT_FIELDS, HOOK_REQUEST_TIMEOUT_MS, HOOK_STOP_REQUEST_TIMEOUT_MS, isHookClient } from "../daemon/hook-contract.js";
8
- import { NexusClient, NexusTransportError } from "../client/nexus-client.js";
9
- const DEFAULT_ENDPOINT = "http://127.0.0.1:5688";
8
+ import { spawn } from "node:child_process";
9
+ import { BACKGROUND_WAIT_EVENT, HOOK_INPUT_FIELDS, HOOK_REQUEST_TIMEOUT_MS, HOOK_STOP_REQUEST_TIMEOUT_MS, WAIT_HOOK_TIMEOUT_SEC, noDaemonHint, isHookClient } from "../contract.js";
10
+ import { NexusClient, NexusTransportError, REQUEST_TIMEOUT_CODE } from "../client/nexus-client.js";
11
+ import { DISCOVER_ENDPOINT, LOCAL_ENDPOINT, resolveEndpoint } from "../client/discovery.js";
12
+ /** Errors after which a discovered daemon is looked up again: it was never reached, so resending is safe. */
13
+ const UNREACHABLE_CODES = new Set(["ECONNREFUSED", "EHOSTUNREACH", "ENETUNREACH", "ETIMEDOUT", "EADDRNOTAVAIL"]);
10
14
  function isPlainObject(value) {
11
15
  return typeof value === "object" && value !== null && !Array.isArray(value);
12
16
  }
@@ -25,7 +29,7 @@ async function forward(argv) {
25
29
  const client = argv[0];
26
30
  if (!isHookClient(client))
27
31
  throw new Error(`unknown client "${client ?? ""}" (expected claude or codex)`);
28
- const endpoint = argValue(argv, "--endpoint") || process.env.NEXUS_ENDPOINT || DEFAULT_ENDPOINT;
32
+ const configured = argValue(argv, "--endpoint") || process.env.NEXUS_ENDPOINT || LOCAL_ENDPOINT;
29
33
  const stdin = JSON.parse(await readStdin());
30
34
  if (!isPlainObject(stdin))
31
35
  throw new Error("hook input is not a JSON object");
@@ -35,19 +39,33 @@ async function forward(argv) {
35
39
  input[field] = stdin[field];
36
40
  }
37
41
  const timeoutMs = stdin.hook_event_name === "Stop" ? HOOK_STOP_REQUEST_TIMEOUT_MS : HOOK_REQUEST_TIMEOUT_MS;
38
- const nexus = new NexusClient({ endpoint });
39
- const send = () => nexus.hook({ client, input }, timeoutMs);
42
+ /** Send to `endpoint`; nothing listening there is reported with what to do about it. */
43
+ const send = async (endpoint) => {
44
+ try {
45
+ return await new NexusClient({ endpoint }).hook({ client, input }, timeoutMs);
46
+ }
47
+ catch (error) {
48
+ if (!(error instanceof NexusTransportError && error.code === "ECONNREFUSED"))
49
+ throw error;
50
+ throw new NexusTransportError(`No daemon at ${endpoint}. ${noDaemonHint(endpoint)}`, error.code);
51
+ }
52
+ };
53
+ const endpoint = await resolveEndpoint(configured);
40
54
  let response;
41
55
  try {
42
- response = await send();
56
+ response = await send(endpoint);
43
57
  }
44
58
  catch (error) {
45
- if (!(error instanceof NexusTransportError && error.code === "ECONNREFUSED"))
59
+ // The cached daemon is gone: look again, and fall back to the local endpoint if none answers.
60
+ // A timed-out Stop may have been waiting for messages on purpose, so only other events count a timeout.
61
+ const code = error instanceof NexusTransportError ? error.code ?? "" : "";
62
+ const unreachable = UNREACHABLE_CODES.has(code) || (code === REQUEST_TIMEOUT_CODE && stdin.hook_event_name !== "Stop");
63
+ if (configured !== DISCOVER_ENDPOINT || !unreachable)
46
64
  throw error;
47
- const { startLocalDaemon } = await import("./autostart.js");
48
- if (!await startLocalDaemon(endpoint))
65
+ const found = await resolveEndpoint(configured, { fresh: true });
66
+ if (found === endpoint)
49
67
  throw error;
50
- response = await send();
68
+ response = await send(found);
51
69
  }
52
70
  if (!isPlainObject(response) || !("output" in response))
53
71
  throw new Error("invalid response from daemon");
@@ -58,8 +76,78 @@ async function forward(argv) {
58
76
  throw new Error("invalid output from daemon");
59
77
  return JSON.stringify(output) + "\n";
60
78
  }
61
- /** Run the hook command; always resolves to exit code 0. */
79
+ /** The background wait ends before the client's hook timeout would kill it during a request. */
80
+ const WAIT_DEADLINE_MS = (WAIT_HOOK_TIMEOUT_SEC - 10) * 1000;
81
+ /**
82
+ * Ask the daemon until something arrives for the session (the notification
83
+ * text), the session becomes active again or the deadline passes (null).
84
+ */
85
+ export async function waitForWake(client, sessionId, endpoint, deadlineMs = WAIT_DEADLINE_MS) {
86
+ const nexus = new NexusClient({ endpoint });
87
+ // Start a request only if it can run to its own timeout before the deadline.
88
+ const deadline = Date.now() + deadlineMs - HOOK_STOP_REQUEST_TIMEOUT_MS;
89
+ while (Date.now() < deadline) {
90
+ const response = await nexus.hook({ client, input: { hook_event_name: BACKGROUND_WAIT_EVENT, session_id: sessionId } }, HOOK_STOP_REQUEST_TIMEOUT_MS);
91
+ const output = isPlainObject(response) ? response.output : null;
92
+ if (isPlainObject(output) && typeof output.wake === "string")
93
+ return output.wake;
94
+ if (!(isPlainObject(output) && output.timeout === true))
95
+ return null;
96
+ }
97
+ return null;
98
+ }
99
+ /**
100
+ * `--wait`, started by a Stop hook when a turn ends. Claude runs it as an
101
+ * asyncRewake hook: exit code 2 with the notification on stderr wakes the
102
+ * conversation. Codex has no such hook, so its Stop hook starts a detached copy
103
+ * (`--session <id>`) and returns at once; the copy hands the notification to
104
+ * `codex queue` (NEXUS_CODEX_COMMAND, default `codex`), which starts a turn.
105
+ */
106
+ async function runWait(argv) {
107
+ const client = argv[0];
108
+ if (!isHookClient(client))
109
+ throw new Error(`unknown client "${client ?? ""}" (expected claude or codex)`);
110
+ // claude -p (unattended) waits for this hook before it exits, and nobody would see a woken turn.
111
+ if (client === "claude" && process.env.CLAUDE_CODE_SESSION_ATTENDED === "0")
112
+ return 0;
113
+ const configured = argValue(argv, "--endpoint") || process.env.NEXUS_ENDPOINT || LOCAL_ENDPOINT;
114
+ let sessionId = argValue(argv, "--session");
115
+ if (!sessionId) {
116
+ const stdin = JSON.parse(await readStdin());
117
+ if (!isPlainObject(stdin) || typeof stdin.session_id !== "string" || !stdin.session_id)
118
+ return 0;
119
+ sessionId = stdin.session_id;
120
+ if (client === "codex") {
121
+ const { entryScript } = await import("./entry.js");
122
+ const args = [entryScript(), "hook", "codex", "--wait", "--session", sessionId, ...(argValue(argv, "--endpoint") ? ["--endpoint", configured] : [])];
123
+ spawn(process.execPath, args, { detached: true, stdio: "ignore", windowsHide: true }).unref();
124
+ return 0;
125
+ }
126
+ }
127
+ const text = await waitForWake(client, sessionId, await resolveEndpoint(configured));
128
+ if (text === null)
129
+ return 0;
130
+ if (client === "codex") {
131
+ // Never through cmd.exe: the text comes from another session and spans several lines.
132
+ const { spawnClientSync } = await import("./client-command.js");
133
+ spawnClientSync(process.env.NEXUS_CODEX_COMMAND || "codex", ["queue", "--thread", sessionId, "--message", text], { stdio: "ignore", windowsHide: true });
134
+ return 0;
135
+ }
136
+ await new Promise((resolve) => process.stderr.write(text + "\n", () => resolve()));
137
+ return 2;
138
+ }
139
+ /** Run the hook command; resolves to exit code 0, or 2 when a background wait wakes a Claude conversation. */
62
140
  export async function runHook(argv) {
141
+ if (argv.includes("--wait")) {
142
+ try {
143
+ return await runWait(argv);
144
+ }
145
+ catch (error) {
146
+ const message = error instanceof Error ? error.message : String(error);
147
+ process.stderr.write(`[n2n-nexus] hook --wait: ${message.replace(/\s+/g, " ").slice(0, 300)}\n`);
148
+ return 0;
149
+ }
150
+ }
63
151
  let text = "";
64
152
  try {
65
153
  text = await forward(argv);
@@ -10,13 +10,15 @@
10
10
  * is the running binary, because process.execPath is the resolved, versioned
11
11
  * location (nvm, Homebrew Cellar, ...) that disappears when Node is upgraded.
12
12
  */
13
- import { execFileSync, spawnSync } from "node:child_process";
13
+ import { spawnSync } from "node:child_process";
14
14
  import fs from "node:fs";
15
15
  import os from "node:os";
16
16
  import path from "node:path";
17
- import { CLAUDE_PRE_TOOL_MATCHER, HOOK_STOP_TIMEOUT_SEC, HOOK_TIMEOUT_SEC, MCP_SERVER_NAME, isHookClient } from "../daemon/hook-contract.js";
17
+ import { CLAUDE_PRE_TOOL_MATCHER, HOOK_STOP_TIMEOUT_SEC, HOOK_TIMEOUT_SEC, MCP_SERVER_NAME, WAIT_HOOK_TIMEOUT_SEC, isHookClient } from "../contract.js";
18
18
  import { pkg } from "../config/index.js";
19
- import { entryScript } from "./autostart.js";
19
+ import { spawnClientSync } from "./client-command.js";
20
+ import { entryScript } from "./entry.js";
21
+ import { mcpConfigFile, readMcpCommand } from "./mcp-config.js";
20
22
  const EVENTS = {
21
23
  claude: ["SessionStart", "SessionEnd", "UserPromptSubmit", "PreToolUse", "PostToolUse", "Stop"],
22
24
  codex: ["SessionStart", "SessionEnd", "UserPromptSubmit", "PostToolUse", "Stop"]
@@ -24,9 +26,9 @@ const EVENTS = {
24
26
  export class InstallError extends Error {
25
27
  }
26
28
  /** Path segments of Node installs that are replaced on upgrade. */
27
- export const VERSIONED_NODE_DIR = /\/Cellar\/|\/\.nvm\/versions\/|\/node-v\d|\/fnm\/|\/fnm_multishells\/|\/\.volta\/|\/\.asdf\/installs\//;
29
+ export const VERSIONED_NODE_DIR = /[/\\]Cellar[/\\]|[/\\]\.nvm[/\\]versions[/\\]|[/\\]node-v\d|[/\\]fnm[/\\]|[/\\]fnm_multishells[/\\]|[/\\]\.volta[/\\]|[/\\]\.asdf[/\\]installs[/\\]/;
28
30
  /** fnm puts a per-shell symlink directory first on PATH; it is gone when the shell ends. */
29
- const PER_SHELL_NODE_DIR = /\/fnm_multishells\//;
31
+ const PER_SHELL_NODE_DIR = /[/\\]fnm_multishells[/\\]/;
30
32
  function sameFile(a, b) {
31
33
  try {
32
34
  return fs.realpathSync(a) === fs.realpathSync(b);
@@ -44,7 +46,7 @@ export function stableNodePath(env = process.env) {
44
46
  for (const dir of (env.PATH ?? "").split(path.delimiter)) {
45
47
  if (!path.isAbsolute(dir) || PER_SHELL_NODE_DIR.test(dir))
46
48
  continue;
47
- const candidate = path.join(dir, "node");
49
+ const candidate = path.join(dir, process.platform === "win32" ? "node.exe" : "node");
48
50
  if (sameFile(candidate, process.execPath))
49
51
  return candidate;
50
52
  }
@@ -69,7 +71,7 @@ export function satisfiesEngines(version, range = pkg.engines.node) {
69
71
  });
70
72
  }
71
73
  /** Check a `--node` path: it must exist, run, and satisfy engines.node. Returns the absolute path. */
72
- function checkNodePath(given) {
74
+ export function checkNodePath(given) {
73
75
  const node = path.resolve(given);
74
76
  try {
75
77
  fs.accessSync(node, fs.constants.X_OK);
@@ -157,10 +159,12 @@ function removeOurEntries(config, client, file) {
157
159
  }
158
160
  return changed;
159
161
  }
160
- function addOurEntries(config, client, command) {
162
+ function addOurEntries(config, client, command, commandWindows) {
161
163
  const hooks = (config.hooks ??= {});
162
164
  for (const event of EVENTS[client]) {
163
165
  const entry = { type: "command", command, timeout: event === "Stop" ? HOOK_STOP_TIMEOUT_SEC : HOOK_TIMEOUT_SEC };
166
+ if (commandWindows)
167
+ entry.commandWindows = commandWindows;
164
168
  const group = client === "claude" && event === "PreToolUse"
165
169
  ? { matcher: CLAUDE_PRE_TOOL_MATCHER, hooks: [entry] }
166
170
  : { hooks: [entry] };
@@ -170,6 +174,12 @@ function addOurEntries(config, client, command) {
170
174
  else
171
175
  hooks[event] = [group];
172
176
  }
177
+ // The background wait that wakes an idle conversation (hook.ts --wait): Claude runs it as an
178
+ // asyncRewake hook; for Codex it starts a detached wait and returns at once.
179
+ const wait = client === "claude"
180
+ ? { type: "command", command: `${command} --wait`, asyncRewake: true, timeout: WAIT_HOOK_TIMEOUT_SEC }
181
+ : { type: "command", command: `${command} --wait`, ...(commandWindows ? { commandWindows: `${commandWindows} '--wait'` } : {}), timeout: HOOK_TIMEOUT_SEC };
182
+ hooks.Stop.push({ hooks: [wait] });
173
183
  }
174
184
  function writeConfig(file, config) {
175
185
  fs.mkdirSync(path.dirname(file), { recursive: true });
@@ -187,15 +197,61 @@ function mcpAddArgs(client, node, entry, endpoint) {
187
197
  const scope = client === "claude" ? ["--scope", "user"] : [];
188
198
  return ["mcp", "add", ...scope, MCP_SERVER_NAME, ...env, "--", node, entry, "mcp"];
189
199
  }
200
+ /**
201
+ * Run `<client> <args>` and throw like execFileSync when it fails. On Windows
202
+ * spawnClientSync runs the script behind npm's `.cmd` shim, never cmd.exe.
203
+ */
204
+ function runClient(client, args, stdio) {
205
+ const result = spawnClientSync(client, args, { encoding: "utf8", stdio });
206
+ if (result.error)
207
+ throw result.error;
208
+ if (result.status !== 0) {
209
+ throw Object.assign(new Error(`Command failed: ${client} ${args.join(" ")}`), { status: result.status, stderr: result.stderr });
210
+ }
211
+ }
212
+ /**
213
+ * Run `<client> mcp remove`. A failure is ignored only when `<client> mcp get`
214
+ * shows the server is not registered (never installed, or already removed);
215
+ * otherwise the removal really failed and we stop before `mcp add`.
216
+ */
217
+ function removeMcpServer(client, action, hooksRemoved) {
218
+ const removeArgs = mcpRemoveArgs(client);
219
+ try {
220
+ runClient(client, removeArgs, ["ignore", "ignore", "pipe"]);
221
+ if (action === "uninstall")
222
+ process.stdout.write(`Ran: ${client} ${removeArgs.join(" ")}\n`);
223
+ return;
224
+ }
225
+ catch (error) {
226
+ // "Not registered" is the one failure to ignore; the registration is read from the
227
+ // client's configuration file (an unreadable file counts as still registered).
228
+ let registered = true;
229
+ try {
230
+ registered = readMcpCommand(client, mcpConfigFile(client)) !== undefined;
231
+ }
232
+ catch {
233
+ // Keep registered = true: the error below tells the user what to look at.
234
+ }
235
+ if (!registered)
236
+ return;
237
+ const failure = error;
238
+ const stderr = typeof failure.stderr === "string" ? failure.stderr.trim() : "";
239
+ const detail = stderr || (typeof failure.status === "number" ? `exit code ${failure.status}` : failure.message);
240
+ const state = action === "uninstall"
241
+ ? `${hooksRemoved ? "The hooks were removed; t" : "T"}he MCP server is still registered in ${mcpConfigFile(client)}.`
242
+ : "The hooks were written; the existing MCP server registration was left unchanged.";
243
+ throw new InstallError(`"${client} ${removeArgs.join(" ")}" failed: ${detail}\n${state} Fix the error and run "n2n-nexus ${action} ${client}" again.`);
244
+ }
245
+ }
190
246
  /** Install or uninstall; prints what it did and returns the exit code. */
191
247
  export function runInstall(options) {
192
248
  const { action, client, endpoint } = options;
193
249
  const entry = options.entry ?? entryScript();
194
250
  try {
195
- if (action === "install" && entry.includes("/_npx/")) {
251
+ if (action === "install" && /[/\\]_npx[/\\]/.test(entry)) {
196
252
  throw new InstallError(`n2n-nexus is running from an npx cache (${entry}), which can be cleared at any time. Install it first: npm i -g n2n-nexus`);
197
253
  }
198
- const probe = spawnSync(client, ["--version"], { stdio: "ignore" });
254
+ const probe = spawnClientSync(client, ["--version"], { stdio: "ignore" });
199
255
  if (probe.error || probe.status !== 0) {
200
256
  throw new InstallError(`The "${client}" command was not found on PATH; install ${client === "claude" ? "Claude Code" : "Codex"} first.`);
201
257
  }
@@ -205,24 +261,19 @@ export function runInstall(options) {
205
261
  const removed = removeOurEntries(config, client, file);
206
262
  if (action === "install") {
207
263
  const command = `"${node}" "${entry}" hook ${client}${endpoint ? ` --endpoint ${endpoint}` : ""}`;
208
- addOurEntries(config, client, command);
264
+ const commandWindows = client === "codex"
265
+ ? `& ${[node, entry, "hook", client, ...(endpoint ? ["--endpoint", endpoint] : [])].map((arg) => `'${arg.replace(/['\u2018\u2019]/g, "$&$&")}'`).join(" ")}`
266
+ : undefined;
267
+ addOurEntries(config, client, command, commandWindows);
209
268
  }
210
269
  if (action === "install" || removed) {
211
270
  writeConfig(file, config);
212
271
  process.stdout.write(`${action === "install" ? "Wrote hooks to" : "Removed hooks from"} ${file}\n`);
213
272
  }
214
- const removeArgs = mcpRemoveArgs(client);
215
- try {
216
- execFileSync(client, removeArgs, { stdio: "ignore" });
217
- if (action === "uninstall")
218
- process.stdout.write(`Ran: ${client} ${removeArgs.join(" ")}\n`);
219
- }
220
- catch {
221
- // Not registered yet (or already removed): nothing to undo.
222
- }
273
+ removeMcpServer(client, action, removed);
223
274
  if (action === "install" && node) {
224
275
  const addArgs = mcpAddArgs(client, node, entry, endpoint);
225
- execFileSync(client, addArgs, { stdio: ["ignore", "ignore", "inherit"] });
276
+ runClient(client, addArgs, ["ignore", "ignore", "inherit"]);
226
277
  process.stdout.write(`Ran: ${client} ${addArgs.join(" ")}\n`);
227
278
  process.stdout.write(`Node: ${node}\n`);
228
279
  if (VERSIONED_NODE_DIR.test(node)) {
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Where Claude Code and Codex keep their MCP server registrations, and how to
3
+ * read the n2n-nexus entry: `~/.claude.json` (user scope) and
4
+ * `$CODEX_HOME/config.toml`. `claude mcp get` is not used for this because it
5
+ * looks in every scope, not only the user scope that install writes to, and
6
+ * it starts the server for a health check.
7
+ */
8
+ import fs from "node:fs";
9
+ import os from "node:os";
10
+ import path from "node:path";
11
+ import { MCP_SERVER_NAME } from "../contract.js";
12
+ /** Where the client keeps the MCP server command. */
13
+ export function mcpConfigFile(client) {
14
+ if (client === "claude") {
15
+ return path.join(process.env.CLAUDE_CONFIG_DIR || os.homedir(), ".claude.json");
16
+ }
17
+ return path.join(process.env.CODEX_HOME || path.join(os.homedir(), ".codex"), "config.toml");
18
+ }
19
+ /** The MCP server command the client has for n2n-nexus, or undefined when not registered. */
20
+ export function readMcpCommand(client, file) {
21
+ let text;
22
+ try {
23
+ text = fs.readFileSync(file, "utf8");
24
+ }
25
+ catch (error) {
26
+ if (error.code === "ENOENT")
27
+ return undefined;
28
+ throw error;
29
+ }
30
+ if (client === "claude") {
31
+ let parsed;
32
+ try {
33
+ parsed = JSON.parse(text);
34
+ }
35
+ catch (error) {
36
+ throw new Error(`${file} is not valid JSON (${error.message}).`, { cause: error });
37
+ }
38
+ const servers = parsed?.mcpServers;
39
+ const server = servers?.[MCP_SERVER_NAME];
40
+ if (!server || typeof server.command !== "string")
41
+ return undefined;
42
+ return { command: server.command, args: Array.isArray(server.args) ? server.args.map(String) : [] };
43
+ }
44
+ // Codex: a TOML table [mcp_servers.n2n-nexus] (the key may be quoted) with command and args.
45
+ const lines = text.split("\n");
46
+ const start = lines.findIndex((line) => new RegExp(`^\\s*\\[mcp_servers\\.(["']?)${MCP_SERVER_NAME}\\1\\]\\s*(?:#.*)?$`).test(line));
47
+ if (start === -1)
48
+ return undefined;
49
+ const body = [];
50
+ for (const line of lines.slice(start + 1)) {
51
+ if (/^\s*\[/.test(line))
52
+ break;
53
+ body.push(line);
54
+ }
55
+ const table = body.join("\n");
56
+ const value = String.raw `"(?:[^"\\\r\n]|\\.)*"|'[^'\r\n]*'`;
57
+ const decode = (s) => s.startsWith("'") ? s.slice(1, -1) : JSON.parse(s);
58
+ const command = new RegExp(`^\\s*command\\s*=\\s*(${value})`, "m").exec(table);
59
+ if (!command)
60
+ return undefined;
61
+ // Treat strings and comments as whole tokens so brackets and quotes inside them are not syntax.
62
+ const array = new RegExp(`^\\s*args\\s*=\\s*\\[((?:${value}|#[^\\n]*|[^\\]"'#])*)\\]`, "m").exec(table);
63
+ const args = array ? [...array[1].matchAll(new RegExp(`(${value})|#[^\\n]*`, "g"))]
64
+ .filter((m) => m[1] !== undefined).map((m) => decode(m[1])) : [];
65
+ return { command: decode(command[1]), args };
66
+ }