n2n-nexus 0.9.3 → 0.9.4
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/CHANGELOG.md +24 -0
- package/README.md +1 -1
- package/SECURITY.md +1 -1
- package/build/cli/hook.js +43 -17
- package/build/cli/install.js +22 -6
- package/build/cli/title.js +126 -0
- package/build/contract.js +22 -2
- package/build/server/nexus.js +6 -2
- package/contract/errors.json +2 -2
- package/contract/hook.json +18 -1
- package/contract/tools.json +562 -14
- package/docs/ARCHITECTURE.md +9 -8
- package/docs/ARCHITECTURE_zh.md +9 -8
- package/docs/ASSISTANT_GUIDE.md +20 -11
- package/docs/ASSISTANT_GUIDE_zh.md +20 -11
- package/docs/CHANGELOG_zh.md +24 -0
- package/docs/INSTALL.md +1 -0
- package/docs/INSTALL_zh.md +1 -0
- package/docs/README_zh.md +1 -1
- package/docs/SECURITY_zh.md +1 -1
- package/docs/TOOLS_REFERENCE.md +87 -28
- package/docs/TOOLS_REFERENCE_zh.md +87 -28
- package/docs/USER_GUIDE.md +8 -5
- package/docs/USER_GUIDE_zh.md +8 -5
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,30 @@
|
|
|
4
4
|
|
|
5
5
|
All notable changes to this project will be documented in this file.
|
|
6
6
|
|
|
7
|
+
## [0.9.4] - 2026-10-26
|
|
8
|
+
|
|
9
|
+
### Changed
|
|
10
|
+
|
|
11
|
+
- Contract version 2: the npm client and the host must be upgraded together (`n2n-nexus doctor` reports a mismatch).
|
|
12
|
+
- Chat and meetings identify the conversation, not the MCP adapter instance, when the n2n-nexus hooks are installed. Several conversations of one IDE in one workspace share an instance; they now keep their own unread cursors, and their messages, a meeting's `initiator` and `participants` and the `actor` of `meeting.*` events carry their session id (`claude:<id>` / `codex:<id>`), which works with `send`. Clients without the hooks keep using the instance. If an instance has had a conversation identified within the last 30 minutes and a call of it cannot be identified, the call fails with a retry message instead of reading through the shared cursor. Results say which identity was used (`identity`).
|
|
13
|
+
- `read_messages` no longer returns your own messages in unread mode; a conversation's first unread read of global chat starts at the newest message. New history mode: `latest: true` or `afterId` read without moving a cursor and include your own messages. Each message has `senderName`, and `category` is always present (null without one).
|
|
14
|
+
- Meeting messages are numbered per meeting, from 1: `id` in `read_messages`, `messageId` from `send_message` (now returned for meetings too) and `afterId` in a meeting use that number, so a new meeting no longer continues the numbers of earlier ones.
|
|
15
|
+
|
|
16
|
+
- Meetings have members. `join_meeting(meetingId, mode?, approver?, since?)` and `leave_meeting(meetingId)`; the initiator joins its meeting. News of a meeting reaches its members through the hooks as one line per meeting: active members are woken (or their turn continues), async members see it at their next prompt or tool call, and nobody is told about their own messages. Meeting news is not an automatic turn and still arrives past `maxAutoTurns`, so a meeting runs until it is ended; ending it gives each other member one notice. `list_meetings` shows the members and how many wakes the meeting caused.
|
|
17
|
+
- Decisions by consensus. `send_message(..., draft: true)` publishes a meeting's current draft and fixes its required approvers (members that joined as `required` through the hooks); `stance(meetingId, messageId, endorse | object | withdraw, note?)` takes a stance on it, an objection with its reason. When at least two required approvers endorsed the current draft and nobody objects, the meeting closes by itself with the draft as a `DECISION` (`endReason: consensus`; `end_meeting` records `manual`). Ordinary proposals do not reset stances; a leaving or re-joining approver changes the list, which is posted to the meeting. Required approvers that have not taken a stance after a quiet `stanceReminderMinutes` (new `settings.json` field, default 10) are reminded once. `list_meetings` shows each meeting's `endReason` and current draft with its stances.
|
|
18
|
+
- Direct messages say what they ask: `send` and `reply` take `expectsReply` (false: the notification says no reply is needed and does not ask for one) and `wake` (false: the message never wakes the recipient or holds its turn, and waits for its next prompt or tool call). `read` returns `expectsReply`.
|
|
19
|
+
- Sessions have a readable `title`: the conversation's title as Claude Code or Codex shows it, read by the hooks and shown next to the name in `peers`, introductions, notifications and meeting members. `set_profile({ title })` sets your own (`""` returns to the client's). The name stays the handle for `send`.
|
|
20
|
+
- A direct message is listed in full once; while it stays unread, later notifications only count it.
|
|
21
|
+
|
|
22
|
+
### Fixed
|
|
23
|
+
|
|
24
|
+
- A failed `codex queue` no longer loses the wake: the Codex background wait reports the result and the host undoes a wake that was not delivered, and the wait tries again after a delay (1 s, doubling up to 5 minutes), so the same messages and notices wake the conversation again; the failed wake is not counted as an automatic turn. The session no longer stays `working` until it goes stale.
|
|
25
|
+
- A session that goes offline after 30 minutes without activity now tells its `notifyWhenIdle` subscribers, as a session that ends does, also when they only wait in the background.
|
|
26
|
+
- The prompt that starts a woken turn no longer announces again what the wake announced.
|
|
27
|
+
- The Codex SessionEnd hook fits Codex's 3-second limit: `n2n-nexus install codex` writes timeout 3 (run it again to update an existing installation, which removes Codex's "clamping SessionEnd hook timeout" warning), and the SessionEnd request gives up after 1.5 s without a second host lookup.
|
|
28
|
+
- `n2n-nexus uninstall <client>` no longer needs the client on PATH: it removes the hooks from the client's config file anyway. Without the client it skips `<client> mcp remove` and, when the MCP server is still registered, says so and how to remove it (run that command later, or delete the `n2n-nexus` entry from `~/.claude.json` / `config.toml`). `install` still requires the client.
|
|
29
|
+
- Tool calls are rate limited per conversation when the hooks identify it, so conversations that share an adapter instance (one client in one directory) no longer use up each other's budget; without the hooks calls are still limited per instance. The per-address limit is unchanged.
|
|
30
|
+
|
|
7
31
|
## [0.9.3] - 2026-10-24
|
|
8
32
|
|
|
9
33
|
### Changed
|
package/README.md
CHANGED
|
@@ -142,7 +142,7 @@ No. `n2n-memory` is a local memory tool for a single repository. `n2n-nexus` is
|
|
|
142
142
|
|
|
143
143
|
### Does it support Claude Desktop, Cursor, VS Code and other clients?
|
|
144
144
|
|
|
145
|
-
Yes, as long as the client can run a local MCP command server. The IDE starts the adapter, and the adapter reaches the local host through `NEXUS_ENDPOINT`.
|
|
145
|
+
Yes, as long as the client can run a local MCP command server. The IDE starts the adapter, and the adapter reaches the local host through `NEXUS_ENDPOINT`. In the Claude desktop app, register it for Claude Code (`n2n-nexus install claude`) only, not in `claude_desktop_config.json`: the app would bridge it into the Code tab and drop the conversation identity ([User guide, section 2](docs/USER_GUIDE.md#2-claude-desktop-app)).
|
|
146
146
|
|
|
147
147
|
### Can Windows and WSL work together?
|
|
148
148
|
|
package/SECURITY.md
CHANGED
|
@@ -32,7 +32,7 @@ Key boundaries to be aware of:
|
|
|
32
32
|
|
|
33
33
|
- **Host network exposure**: The host binds to `127.0.0.1` by default. LAN access (the tray's **Allow LAN access**, `"host": "0.0.0.0"` in `settings.json`, or `--host 0.0.0.0`) exposes it to your local network, and it then answers LAN discovery on UDP `discoveryPort`. There is no authentication layer in the open-source baseline — only expose the host beyond localhost on networks you control.
|
|
34
34
|
- **Browser requests**: The host has no authentication, so it refuses requests that carry a browser `Origin` header or a cross-site `Sec-Fetch-Site` header (403), requires `Content-Type: application/json` on POST (415) and caps request bodies at 16 MB (413). It also rejects any `Host` header that is not an IP literal, `localhost`, `host.docker.internal` or a name listed in `allowedHosts` in `settings.json`, which closes DNS-rebinding attacks where a page reaches the host as a same-origin request under the attacker's domain. MCP adapters and scripts are unaffected.
|
|
35
|
-
- **Rate limiting**: Tool calls are limited per instance ID (default 20/s, burst 60, set with `rateLimit` / `rateBurst` in `settings.json`) and, because instance IDs are self-declared, per client address at five times that. Tool calls that name
|
|
35
|
+
- **Rate limiting**: Tool calls are limited per conversation, or per instance ID when no conversation is identified (default 20/s, burst 60, set with `rateLimit` / `rateBurst` in `settings.json`) and, because instance and session IDs are self-declared, per client address at five times that. Tool calls that name neither a conversation nor an instance ID are limited only per address. Hooks (`POST /api/hook`) are limited per conversation and per client address in buckets of their own. Over the limit the host answers `429` with `Retry-After`; `/health` and `GET /api/tools` are exempt.
|
|
36
36
|
- **Malformed requests**: Invalid request URLs or Host headers return 400 without terminating the host. Validly formed requests still pass through the browser and Host checks above.
|
|
37
37
|
- **Sensitive content in coordination data**: Project manifests, internal docs, meeting messages, and global documents are stored in plaintext in the host's local database. Do not store secrets, credentials, or customer data in these fields.
|
|
38
38
|
- **Destructive tools**: Destructive tools such as project deletion should be used through explicit review workflows.
|
package/build/cli/hook.js
CHANGED
|
@@ -2,15 +2,19 @@
|
|
|
2
2
|
* `n2n-nexus hook <claude|codex> [--endpoint <url>] [--wait]`: forward one client
|
|
3
3
|
* hook event to the daemon and print its output, or with `--wait` run the
|
|
4
4
|
* background wait that wakes an idle conversation. Runs on every tool call, so
|
|
5
|
-
* it loads only node built-ins (no MCP SDK
|
|
5
|
+
* it loads only node built-ins (no MCP SDK or zod; node:sqlite only to read a
|
|
6
|
+
* Codex conversation's title, see title.ts), and every failure
|
|
6
7
|
* is silent: exit 0 with nothing on stdout, so the client carries on unaffected.
|
|
7
8
|
*/
|
|
8
9
|
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 { BACKGROUND_WAIT_EVENT, WAKE_RESULT_EVENT, HOOK_INPUT_FIELDS, HOOK_REQUEST_TIMEOUT_MS, HOOK_STOP_REQUEST_TIMEOUT_MS, SESSION_END_REQUEST_TIMEOUT_MS, WAIT_HOOK_TIMEOUT_SEC, WAKE_RETRY_FIRST_DELAY_MS, WAKE_RETRY_MAX_DELAY_MS, noDaemonHint, isHookClient } from "../contract.js";
|
|
10
11
|
import { NexusClient, NexusTransportError, REQUEST_TIMEOUT_CODE } from "../client/nexus-client.js";
|
|
11
12
|
import { DISCOVER_ENDPOINT, LOCAL_ENDPOINT, resolveEndpoint } from "../client/discovery.js";
|
|
13
|
+
import { readTitle } from "./title.js";
|
|
12
14
|
/** Errors after which a discovered daemon is looked up again: it was never reached, so resending is safe. */
|
|
13
15
|
const UNREACHABLE_CODES = new Set(["ECONNREFUSED", "EHOSTUNREACH", "ENETUNREACH", "ETIMEDOUT", "EADDRNOTAVAIL"]);
|
|
16
|
+
/** Events whose forwarded input carries the conversation's title. */
|
|
17
|
+
const TITLE_EVENTS = new Set(["SessionStart", "UserPromptSubmit", "Stop"]);
|
|
14
18
|
function isPlainObject(value) {
|
|
15
19
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
16
20
|
}
|
|
@@ -38,7 +42,15 @@ async function forward(argv) {
|
|
|
38
42
|
if (Object.prototype.hasOwnProperty.call(stdin, field))
|
|
39
43
|
input[field] = stdin[field];
|
|
40
44
|
}
|
|
41
|
-
|
|
45
|
+
// The title is read only where the host updates it, not on the frequent tool events.
|
|
46
|
+
if (typeof stdin.hook_event_name === "string" && TITLE_EVENTS.has(stdin.hook_event_name)) {
|
|
47
|
+
const title = await readTitle(client, stdin);
|
|
48
|
+
if (title !== undefined)
|
|
49
|
+
input.title = title;
|
|
50
|
+
}
|
|
51
|
+
// SessionEnd must finish within Codex's 3 s hook limit (discovery included): a short budget and a single attempt.
|
|
52
|
+
const sessionEnd = stdin.hook_event_name === "SessionEnd";
|
|
53
|
+
const timeoutMs = stdin.hook_event_name === "Stop" ? HOOK_STOP_REQUEST_TIMEOUT_MS : sessionEnd ? SESSION_END_REQUEST_TIMEOUT_MS : HOOK_REQUEST_TIMEOUT_MS;
|
|
42
54
|
/** Send to `endpoint`; nothing listening there is reported with what to do about it. */
|
|
43
55
|
const send = async (endpoint) => {
|
|
44
56
|
try {
|
|
@@ -60,7 +72,7 @@ async function forward(argv) {
|
|
|
60
72
|
// A timed-out Stop may have been waiting for messages on purpose, so only other events count a timeout.
|
|
61
73
|
const code = error instanceof NexusTransportError ? error.code ?? "" : "";
|
|
62
74
|
const unreachable = UNREACHABLE_CODES.has(code) || (code === REQUEST_TIMEOUT_CODE && stdin.hook_event_name !== "Stop");
|
|
63
|
-
if (configured !== DISCOVER_ENDPOINT || !unreachable)
|
|
75
|
+
if (configured !== DISCOVER_ENDPOINT || !unreachable || sessionEnd)
|
|
64
76
|
throw error;
|
|
65
77
|
const found = await resolveEndpoint(configured, { fresh: true });
|
|
66
78
|
if (found === endpoint)
|
|
@@ -79,8 +91,8 @@ async function forward(argv) {
|
|
|
79
91
|
/** The background wait ends before the client's hook timeout would kill it during a request. */
|
|
80
92
|
const WAIT_DEADLINE_MS = (WAIT_HOOK_TIMEOUT_SEC - 10) * 1000;
|
|
81
93
|
/**
|
|
82
|
-
* Ask the daemon until something arrives for the session (the
|
|
83
|
-
*
|
|
94
|
+
* Ask the daemon until something arrives for the session (the wake), the
|
|
95
|
+
* session becomes active again or the deadline passes (null).
|
|
84
96
|
*/
|
|
85
97
|
export async function waitForWake(client, sessionId, endpoint, deadlineMs = WAIT_DEADLINE_MS) {
|
|
86
98
|
const nexus = new NexusClient({ endpoint });
|
|
@@ -89,8 +101,8 @@ export async function waitForWake(client, sessionId, endpoint, deadlineMs = WAIT
|
|
|
89
101
|
while (Date.now() < deadline) {
|
|
90
102
|
const response = await nexus.hook({ client, input: { hook_event_name: BACKGROUND_WAIT_EVENT, session_id: sessionId } }, HOOK_STOP_REQUEST_TIMEOUT_MS);
|
|
91
103
|
const output = isPlainObject(response) ? response.output : null;
|
|
92
|
-
if (isPlainObject(output) && typeof output.wake === "string")
|
|
93
|
-
return output.wake;
|
|
104
|
+
if (isPlainObject(output) && typeof output.wake === "string" && typeof output.dispatchId === "string")
|
|
105
|
+
return { text: output.wake, dispatchId: output.dispatchId };
|
|
94
106
|
if (!(isPlainObject(output) && output.timeout === true))
|
|
95
107
|
return null;
|
|
96
108
|
}
|
|
@@ -101,7 +113,11 @@ export async function waitForWake(client, sessionId, endpoint, deadlineMs = WAIT
|
|
|
101
113
|
* asyncRewake hook: exit code 2 with the notification on stderr wakes the
|
|
102
114
|
* conversation. Codex has no such hook, so its Stop hook starts a detached copy
|
|
103
115
|
* (`--session <id>`) and returns at once; the copy hands the notification to
|
|
104
|
-
* `codex queue` (NEXUS_CODEX_COMMAND, default `codex`), which starts a turn
|
|
116
|
+
* `codex queue` (NEXUS_CODEX_COMMAND, default `codex`), which starts a turn,
|
|
117
|
+
* and reports to the host whether it did (WAKE_RESULT_EVENT): after a failed
|
|
118
|
+
* queue the host undoes the wake and the copy waits again after a delay that
|
|
119
|
+
* doubles on each failure, so the same messages wake the session on a later
|
|
120
|
+
* try without retrying a broken `codex` in a loop.
|
|
105
121
|
*/
|
|
106
122
|
async function runWait(argv) {
|
|
107
123
|
const client = argv[0];
|
|
@@ -127,16 +143,26 @@ async function runWait(argv) {
|
|
|
127
143
|
// Load what a wake needs before waiting: the wait lasts up to an hour, and an
|
|
128
144
|
// upgrade or a cleared npx cache may remove the package's files meanwhile.
|
|
129
145
|
const { spawnClientSync } = client === "codex" ? await import("./client-command.js") : { spawnClientSync: undefined };
|
|
130
|
-
const
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
146
|
+
const endpoint = await resolveEndpoint(configured);
|
|
147
|
+
const deadline = Date.now() + WAIT_DEADLINE_MS;
|
|
148
|
+
for (let delay = WAKE_RETRY_FIRST_DELAY_MS;; delay = Math.min(delay * 2, WAKE_RETRY_MAX_DELAY_MS)) {
|
|
149
|
+
const wake = await waitForWake(client, sessionId, endpoint, deadline - Date.now());
|
|
150
|
+
if (wake === null)
|
|
151
|
+
return 0;
|
|
152
|
+
if (!spawnClientSync) {
|
|
153
|
+
await new Promise((resolve) => process.stderr.write(wake.text + "\n", () => resolve()));
|
|
154
|
+
return 2;
|
|
155
|
+
}
|
|
134
156
|
// Never through cmd.exe: the text comes from another session and spans several lines.
|
|
135
|
-
spawnClientSync(process.env.NEXUS_CODEX_COMMAND || "codex", ["queue", "--thread", sessionId, "--message", text], { stdio: "ignore", windowsHide: true });
|
|
136
|
-
|
|
157
|
+
const queued = spawnClientSync(process.env.NEXUS_CODEX_COMMAND || "codex", ["queue", "--thread", sessionId, "--message", wake.text], { stdio: "ignore", windowsHide: true });
|
|
158
|
+
const ok = !queued.error && queued.status === 0;
|
|
159
|
+
const input = { hook_event_name: WAKE_RESULT_EVENT, session_id: sessionId, dispatch_id: wake.dispatchId, ok };
|
|
160
|
+
const reported = await new NexusClient({ endpoint }).hook({ client, input }, HOOK_REQUEST_TIMEOUT_MS).then(() => true, () => false);
|
|
161
|
+
// Unknown result (no report): the host keeps the wake, and waiting again would deliver nothing.
|
|
162
|
+
if (ok || !reported || Date.now() + delay >= deadline)
|
|
163
|
+
return 0;
|
|
164
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
137
165
|
}
|
|
138
|
-
await new Promise((resolve) => process.stderr.write(text + "\n", () => resolve()));
|
|
139
|
-
return 2;
|
|
140
166
|
}
|
|
141
167
|
/** Run the hook command; resolves to exit code 0, or 2 when a background wait wakes a Claude conversation. */
|
|
142
168
|
export async function runHook(argv) {
|
package/build/cli/install.js
CHANGED
|
@@ -17,7 +17,7 @@ import { spawnSync } from "node:child_process";
|
|
|
17
17
|
import fs from "node:fs";
|
|
18
18
|
import os from "node:os";
|
|
19
19
|
import path from "node:path";
|
|
20
|
-
import { CLAUDE_PRE_TOOL_MATCHER, HOOK_STOP_TIMEOUT_SEC, HOOK_TIMEOUT_SEC, MCP_SERVER_NAME, WAIT_HOOK_TIMEOUT_SEC, isHookClient } from "../contract.js";
|
|
20
|
+
import { CLAUDE_PRE_TOOL_MATCHER, CODEX_SESSION_END_TIMEOUT_SEC, HOOK_STOP_TIMEOUT_SEC, HOOK_TIMEOUT_SEC, MCP_SERVER_NAME, WAIT_HOOK_TIMEOUT_SEC, isHookClient } from "../contract.js";
|
|
21
21
|
import { pkg } from "../config/index.js";
|
|
22
22
|
import { spawnClientSync } from "./client-command.js";
|
|
23
23
|
import { entryScript } from "./entry.js";
|
|
@@ -210,7 +210,11 @@ function removeOurEntries(config, client, file) {
|
|
|
210
210
|
function addOurEntries(config, client, command, commandWindows) {
|
|
211
211
|
const hooks = (config.hooks ??= {});
|
|
212
212
|
for (const event of EVENTS[client]) {
|
|
213
|
-
|
|
213
|
+
// Codex clamps a SessionEnd hook timeout above 3 s (and warns in its settings), so ask for 3 s there.
|
|
214
|
+
const timeout = event === "Stop" ? HOOK_STOP_TIMEOUT_SEC
|
|
215
|
+
: client === "codex" && event === "SessionEnd" ? CODEX_SESSION_END_TIMEOUT_SEC
|
|
216
|
+
: HOOK_TIMEOUT_SEC;
|
|
217
|
+
const entry = { type: "command", command, timeout };
|
|
214
218
|
if (commandWindows)
|
|
215
219
|
entry.commandWindows = commandWindows;
|
|
216
220
|
const group = client === "claude" && event === "PreToolUse"
|
|
@@ -289,7 +293,9 @@ function runClient(client, args, stdio) {
|
|
|
289
293
|
/**
|
|
290
294
|
* Run `<client> mcp remove`. A failure is ignored only when `<client> mcp get`
|
|
291
295
|
* shows the server is not registered (never installed, or already removed);
|
|
292
|
-
* otherwise the removal really failed and we stop before `mcp add`.
|
|
296
|
+
* otherwise the removal really failed and we stop before `mcp add`. On
|
|
297
|
+
* uninstall, a client that cannot be run skips the step with a note on how to
|
|
298
|
+
* remove the registration that is still there.
|
|
293
299
|
*/
|
|
294
300
|
function removeMcpServer(client, action, hooksRemoved) {
|
|
295
301
|
const removeArgs = mcpRemoveArgs(client);
|
|
@@ -311,6 +317,13 @@ function removeMcpServer(client, action, hooksRemoved) {
|
|
|
311
317
|
}
|
|
312
318
|
if (!registered)
|
|
313
319
|
return;
|
|
320
|
+
if (action === "uninstall" && error.code === "ENOENT") {
|
|
321
|
+
const file = mcpConfigFile(client);
|
|
322
|
+
const what = client === "claude" ? `the "${MCP_SERVER_NAME}" entry under "mcpServers"` : `the [mcp_servers.${MCP_SERVER_NAME}] table`;
|
|
323
|
+
process.stdout.write(`Skipped "${client} ${removeArgs.join(" ")}": the "${client}" command could not be run (not on PATH, or not runnable without a shell). `
|
|
324
|
+
+ `The MCP server is still registered in ${file}; run that command once ${client} can be run, or delete ${what} from ${file}.\n`);
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
314
327
|
const failure = error;
|
|
315
328
|
const stderr = typeof failure.stderr === "string" ? failure.stderr.trim() : "";
|
|
316
329
|
const detail = stderr || (typeof failure.status === "number" ? `exit code ${failure.status}` : failure.message);
|
|
@@ -328,9 +341,12 @@ export function runInstall(options) {
|
|
|
328
341
|
if (action === "install" && /[/\\]_npx[/\\]/.test(entry)) {
|
|
329
342
|
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 ${MCP_PACKAGE}`);
|
|
330
343
|
}
|
|
331
|
-
|
|
332
|
-
if (
|
|
333
|
-
|
|
344
|
+
// Uninstall does not need the client: our hooks are removed from its config file either way.
|
|
345
|
+
if (action === "install") {
|
|
346
|
+
const probe = spawnClientSync(client, ["--version"], { stdio: "ignore" });
|
|
347
|
+
if (probe.error || probe.status !== 0) {
|
|
348
|
+
throw new InstallError(`The "${client}" command was not found on PATH; install ${client === "claude" ? "Claude Code" : "Codex"} first.`);
|
|
349
|
+
}
|
|
334
350
|
}
|
|
335
351
|
const node = action === "install" ? (options.node ? checkNodePath(options.node) : stableNodePath()) : undefined;
|
|
336
352
|
const npm = node ? npxFor(node) : undefined;
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The conversation's title as its client shows it, which the hook command adds
|
|
3
|
+
* to the input it forwards as `title`. Neither source is documented, so every
|
|
4
|
+
* failure (missing file, unexpected format, locked database, time budget
|
|
5
|
+
* spent) yields undefined and the hook goes on without a title.
|
|
6
|
+
*
|
|
7
|
+
* Claude Code: the transcript (`transcript_path`, JSONL, can be very large)
|
|
8
|
+
* gets `{"type":"custom-title","customTitle":…}` records when the user renames
|
|
9
|
+
* the conversation and `{"type":"ai-title","aiTitle":…}` records for the
|
|
10
|
+
* automatic title, appended again and again; only its last and, failing that,
|
|
11
|
+
* first TRANSCRIPT_CHUNK_BYTES are read. Codex: `threads.name` (set by the
|
|
12
|
+
* user) or else `threads.title` in the newest `$CODEX_HOME/state_<N>.sqlite`.
|
|
13
|
+
*/
|
|
14
|
+
import { open, readdir } from "node:fs/promises";
|
|
15
|
+
import os from "node:os";
|
|
16
|
+
import path from "node:path";
|
|
17
|
+
import { MAX_TITLE_CHARS } from "../contract.js";
|
|
18
|
+
/** How much of the transcript's end, and then of its start, is searched for a title. */
|
|
19
|
+
const TRANSCRIPT_CHUNK_BYTES = 256 * 1024;
|
|
20
|
+
/** Reading the title may not hold up the hook for longer than this. */
|
|
21
|
+
const TITLE_BUDGET_MS = 50;
|
|
22
|
+
/** Trimmed first line, at most MAX_TITLE_CHARS characters; undefined when nothing is left. */
|
|
23
|
+
export function cleanTitle(value) {
|
|
24
|
+
if (typeof value !== "string")
|
|
25
|
+
return undefined;
|
|
26
|
+
const line = value.trim().split(/\r\n|\r|\n/)[0].trim();
|
|
27
|
+
const chars = Array.from(line);
|
|
28
|
+
const title = chars.length > MAX_TITLE_CHARS ? chars.slice(0, MAX_TITLE_CHARS).join("").trimEnd() : line;
|
|
29
|
+
return title || undefined;
|
|
30
|
+
}
|
|
31
|
+
/** The last custom title in `text`, or else the last automatic one. */
|
|
32
|
+
function titleInJsonl(text) {
|
|
33
|
+
let custom;
|
|
34
|
+
let ai;
|
|
35
|
+
for (const line of text.split("\n")) {
|
|
36
|
+
if (!line.includes("-title"))
|
|
37
|
+
continue;
|
|
38
|
+
let record;
|
|
39
|
+
try {
|
|
40
|
+
record = JSON.parse(line);
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
continue; // the chunk's cut-off first or last line
|
|
44
|
+
}
|
|
45
|
+
if (typeof record !== "object" || record === null)
|
|
46
|
+
continue;
|
|
47
|
+
const { type, customTitle, aiTitle } = record;
|
|
48
|
+
if (type === "custom-title")
|
|
49
|
+
custom = cleanTitle(customTitle) ?? custom;
|
|
50
|
+
else if (type === "ai-title")
|
|
51
|
+
ai = cleanTitle(aiTitle) ?? ai;
|
|
52
|
+
}
|
|
53
|
+
return custom ?? ai;
|
|
54
|
+
}
|
|
55
|
+
async function claudeTitle(transcriptPath) {
|
|
56
|
+
if (typeof transcriptPath !== "string" || !transcriptPath)
|
|
57
|
+
return undefined;
|
|
58
|
+
const file = await open(transcriptPath, "r");
|
|
59
|
+
try {
|
|
60
|
+
const { size } = await file.stat();
|
|
61
|
+
const read = async (position, length) => {
|
|
62
|
+
const buffer = Buffer.alloc(length);
|
|
63
|
+
const { bytesRead } = await file.read(buffer, 0, length, position);
|
|
64
|
+
return buffer.toString("utf8", 0, bytesRead);
|
|
65
|
+
};
|
|
66
|
+
const tailStart = Math.max(0, size - TRANSCRIPT_CHUNK_BYTES);
|
|
67
|
+
const title = titleInJsonl(await read(tailStart, size - tailStart));
|
|
68
|
+
if (title !== undefined || tailStart === 0)
|
|
69
|
+
return title;
|
|
70
|
+
return titleInJsonl(await read(0, TRANSCRIPT_CHUNK_BYTES));
|
|
71
|
+
}
|
|
72
|
+
finally {
|
|
73
|
+
await file.close();
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
/** node:sqlite without the ExperimentalWarning older Node versions print on stderr when it loads. */
|
|
77
|
+
async function loadSqlite() {
|
|
78
|
+
const emitWarning = process.emitWarning;
|
|
79
|
+
process.emitWarning = function (warning, ...args) {
|
|
80
|
+
const type = typeof args[0] === "string" ? args[0] : args[0]?.type ?? (warning instanceof Error ? warning.name : undefined);
|
|
81
|
+
const message = warning instanceof Error ? warning.message : String(warning);
|
|
82
|
+
if (type === "ExperimentalWarning" && message.includes("SQLite"))
|
|
83
|
+
return;
|
|
84
|
+
return emitWarning.call(process, warning, ...args);
|
|
85
|
+
};
|
|
86
|
+
try {
|
|
87
|
+
return await import("node:sqlite");
|
|
88
|
+
}
|
|
89
|
+
finally {
|
|
90
|
+
process.emitWarning = emitWarning;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
async function codexTitle(sessionId) {
|
|
94
|
+
if (typeof sessionId !== "string" || !sessionId)
|
|
95
|
+
return undefined;
|
|
96
|
+
const home = process.env.CODEX_HOME || path.join(os.homedir(), ".codex");
|
|
97
|
+
let newest;
|
|
98
|
+
for (const name of await readdir(home)) {
|
|
99
|
+
const match = /^state_(\d+)\.sqlite$/.exec(name);
|
|
100
|
+
if (match && (newest === undefined || Number(match[1]) > newest.n))
|
|
101
|
+
newest = { n: Number(match[1]), name };
|
|
102
|
+
}
|
|
103
|
+
if (!newest)
|
|
104
|
+
return undefined;
|
|
105
|
+
const { DatabaseSync } = await loadSqlite();
|
|
106
|
+
const db = new DatabaseSync(path.join(home, newest.name), { readOnly: true });
|
|
107
|
+
try {
|
|
108
|
+
const row = db.prepare("SELECT name, title FROM threads WHERE id = ?").get(sessionId);
|
|
109
|
+
return row ? cleanTitle(row.name) ?? cleanTitle(row.title) : undefined;
|
|
110
|
+
}
|
|
111
|
+
finally {
|
|
112
|
+
db.close();
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
/** The title of the conversation `input` (the hook's stdin) belongs to, or undefined; never throws. */
|
|
116
|
+
export async function readTitle(client, input) {
|
|
117
|
+
let timer;
|
|
118
|
+
const budget = new Promise((resolve) => { timer = setTimeout(resolve, TITLE_BUDGET_MS, undefined); });
|
|
119
|
+
const read = client === "claude" ? claudeTitle(input.transcript_path) : codexTitle(input.session_id);
|
|
120
|
+
try {
|
|
121
|
+
return await Promise.race([read.catch(() => undefined), budget]);
|
|
122
|
+
}
|
|
123
|
+
finally {
|
|
124
|
+
clearTimeout(timer);
|
|
125
|
+
}
|
|
126
|
+
}
|
package/build/contract.js
CHANGED
|
@@ -24,20 +24,28 @@ export const CLIENT_INFO_NAMES = contract.clientInfoNames;
|
|
|
24
24
|
export const CLAUDE_TOOL_USE_META_KEY = contract.meta.claudeToolUseKey;
|
|
25
25
|
export const CODEX_SESSION_META_KEY = contract.meta.codexSessionKey;
|
|
26
26
|
/**
|
|
27
|
-
* Hook stdin fields the host uses. The hook command forwards only these
|
|
27
|
+
* Hook stdin fields the host uses. The hook command forwards only these (plus
|
|
28
|
+
* `title` on SessionStart, UserPromptSubmit and Stop, see cli/title.ts):
|
|
28
29
|
* PostToolUse stdin also carries the whole tool input and response, which can
|
|
29
30
|
* be large and runs on every tool call.
|
|
30
31
|
*/
|
|
31
32
|
export const HOOK_INPUT_FIELDS = contract.hookInputFields;
|
|
32
33
|
/**
|
|
33
34
|
* Pseudo hook event of the background wait (`n2n-nexus hook <client> --wait`):
|
|
34
|
-
* started when a turn ends, it waits and returns `{ wake: text }` when
|
|
35
|
+
* started when a turn ends, it waits and returns `{ wake: text, dispatchId }` when
|
|
35
36
|
* something new arrives for the session, `{ timeout: true }` when the time
|
|
36
37
|
* runs out (the client asks again), or null when the session became active
|
|
37
38
|
* again (the client stops). Claude delivers the text through an asyncRewake
|
|
38
39
|
* hook, Codex through `codex queue`.
|
|
39
40
|
*/
|
|
40
41
|
export const BACKGROUND_WAIT_EVENT = contract.backgroundWaitEvent;
|
|
42
|
+
/**
|
|
43
|
+
* Pseudo hook event with which the Codex background wait reports whether
|
|
44
|
+
* `codex queue` took a wake: input `{ session_id, dispatch_id, ok }`. On
|
|
45
|
+
* `ok: false` the host undoes the wake, so its messages and notices wake the
|
|
46
|
+
* session again.
|
|
47
|
+
*/
|
|
48
|
+
export const WAKE_RESULT_EVENT = contract.wakeResultEvent;
|
|
41
49
|
/** HTTP timeout of the hook command: a listening Stop may wait long, every other event is quick. */
|
|
42
50
|
export const HOOK_STOP_REQUEST_TIMEOUT_MS = contract.timing.hookStopRequestTimeoutMs;
|
|
43
51
|
export const HOOK_REQUEST_TIMEOUT_MS = contract.timing.hookRequestTimeoutMs;
|
|
@@ -46,6 +54,18 @@ export const HOOK_STOP_TIMEOUT_SEC = contract.timing.hookStopTimeoutSec;
|
|
|
46
54
|
/** `timeout` (seconds) of the background wait hook; a conversation idle for longer is not woken. */
|
|
47
55
|
export const WAIT_HOOK_TIMEOUT_SEC = contract.timing.waitHookTimeoutSec;
|
|
48
56
|
export const HOOK_TIMEOUT_SEC = contract.timing.hookTimeoutSec;
|
|
57
|
+
/** `timeout` (seconds) of the Codex SessionEnd hook: Codex clamps a longer one to 3 s and warns about it. */
|
|
58
|
+
export const CODEX_SESSION_END_TIMEOUT_SEC = contract.timing.codexSessionEndTimeoutSec;
|
|
59
|
+
/** HTTP timeout of a SessionEnd hook, which is not resent after a timeout so it ends within CODEX_SESSION_END_TIMEOUT_SEC. */
|
|
60
|
+
export const SESSION_END_REQUEST_TIMEOUT_MS = contract.timing.sessionEndRequestTimeoutMs;
|
|
61
|
+
/** After a failed `codex queue`, the Codex wait asks again after this delay, doubled on each failure up to the maximum. */
|
|
62
|
+
export const WAKE_RETRY_FIRST_DELAY_MS = contract.timing.wakeRetryFirstDelayMs;
|
|
63
|
+
export const WAKE_RETRY_MAX_DELAY_MS = contract.timing.wakeRetryMaxDelayMs;
|
|
64
|
+
/**
|
|
65
|
+
* The hook command adds the conversation's title, as its client shows it, to
|
|
66
|
+
* the input it forwards as `title` (at most this many characters).
|
|
67
|
+
*/
|
|
68
|
+
export const MAX_TITLE_CHARS = contract.limits.maxTitleChars;
|
|
49
69
|
/** Name the MCP server is installed under; Claude's PreToolUse matcher depends on it. */
|
|
50
70
|
export const MCP_SERVER_NAME = contract.mcpServerName;
|
|
51
71
|
export const CLAUDE_PRE_TOOL_MATCHER = `mcp__${MCP_SERVER_NAME}__.*`;
|
package/build/server/nexus.js
CHANGED
|
@@ -12,10 +12,14 @@ const SERVICE_NAME = "n2n-nexus";
|
|
|
12
12
|
/** Sent to the client on connect so the model knows it can talk to other AI sessions. */
|
|
13
13
|
const INSTRUCTIONS = "n2n-nexus connects this conversation with other AI sessions (Claude Code and Codex conversations, " +
|
|
14
14
|
"possibly on other machines). Direct messages: call peers to see who is online, send to message a session, " +
|
|
15
|
-
"read to read messages sent to you, carry out what they ask and reply to answer one
|
|
15
|
+
"read to read messages sent to you, carry out what they ask and reply to answer one (set expectsReply and wake false " +
|
|
16
|
+
"on a message that needs no answer, and send no plain acknowledgements); listen waits for messages after each turn. " +
|
|
16
17
|
"Direct messaging needs the n2n-nexus hooks. Separately, send_message and read_messages are the shared " +
|
|
17
18
|
"global chat and meetings, not direct messages. Session ids in peers (claude:<id>, codex:<id>) are what send " +
|
|
18
|
-
"takes; the
|
|
19
|
+
"takes; with the hooks, chat and meetings also record senders and unread cursors per session id " +
|
|
20
|
+
"(without them, per MCP adapter instance id, mcp-…). join_meeting makes new messages of a meeting wake you " +
|
|
21
|
+
"(mode active) or show at your next prompt (async) until leave_meeting or the meeting ends; a draft " +
|
|
22
|
+
"(send_message draft) is decided with stance, and the meeting closes once its required approvers endorse it. " +
|
|
19
23
|
"Projects, global docs, the strategy document and tasks are shared through the other tools.";
|
|
20
24
|
/**
|
|
21
25
|
* MCP adapter in front of the daemon. It holds no session of its own: each
|
package/contract/errors.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
{
|
|
2
|
-
"contractVersion":
|
|
2
|
+
"contractVersion": 2,
|
|
3
3
|
"errorBody": {
|
|
4
4
|
"type": "object",
|
|
5
5
|
"properties": {
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
"ok": true,
|
|
22
22
|
"service": "n2n-nexus",
|
|
23
23
|
"version": "<host version>",
|
|
24
|
-
"contractVersion":
|
|
24
|
+
"contractVersion": 2,
|
|
25
25
|
"sessions": {
|
|
26
26
|
"online": "<number of agent sessions not offline>"
|
|
27
27
|
}
|
package/contract/hook.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
{
|
|
2
|
-
"contractVersion":
|
|
2
|
+
"contractVersion": 2,
|
|
3
3
|
"clients": [
|
|
4
4
|
"claude",
|
|
5
5
|
"codex"
|
|
@@ -24,6 +24,7 @@
|
|
|
24
24
|
"reason"
|
|
25
25
|
],
|
|
26
26
|
"backgroundWaitEvent": "BackgroundWait",
|
|
27
|
+
"wakeResultEvent": "WakeResult",
|
|
27
28
|
"agentStatuses": [
|
|
28
29
|
"working",
|
|
29
30
|
"idle",
|
|
@@ -37,6 +38,10 @@
|
|
|
37
38
|
"hookStopTimeoutSec": 600,
|
|
38
39
|
"waitHookTimeoutSec": 3600,
|
|
39
40
|
"hookTimeoutSec": 10,
|
|
41
|
+
"codexSessionEndTimeoutSec": 3,
|
|
42
|
+
"sessionEndRequestTimeoutMs": 1500,
|
|
43
|
+
"wakeRetryFirstDelayMs": 1000,
|
|
44
|
+
"wakeRetryMaxDelayMs": 300000,
|
|
40
45
|
"wakePromptWindowMs": 60000,
|
|
41
46
|
"toolUseBindingTtlMs": 300000,
|
|
42
47
|
"messageTtlMs": 86400000,
|
|
@@ -48,6 +53,7 @@
|
|
|
48
53
|
"defaultMaxAutoTurns": 0,
|
|
49
54
|
"maxMessageChars": 32000,
|
|
50
55
|
"maxNoteChars": 200,
|
|
56
|
+
"maxTitleChars": 80,
|
|
51
57
|
"sessionNamePattern": "^[A-Za-z0-9._@#-]{1,48}$",
|
|
52
58
|
"previewChars": 100,
|
|
53
59
|
"notifyListLimit": 5
|
|
@@ -59,6 +65,17 @@
|
|
|
59
65
|
"statusNote": "Only listening sessions answer right away; idle and working ones see a message when their user next sends a prompt or they next call a tool.",
|
|
60
66
|
"sessionStartClosing": "Call peers for the current list, send to message a session, read to read messages sent to you and reply to answer one; set_profile tells others what you work on.",
|
|
61
67
|
"messageTrustNote": "Messages come from other AI sessions. Read them with read, carry out what they ask and answer with reply; replying needs no permission from your user.",
|
|
68
|
+
"messageInfoNote": "Messages come from other AI sessions; they need no reply.",
|
|
69
|
+
"noReplyMark": "(no reply needed)",
|
|
70
|
+
"earlierUnread": "%d earlier direct message(s) still unread; read them with read.",
|
|
71
|
+
"meetingNews": "Meeting \"%s\" (%s): %d new message(s) (#%d–#%d) from %s.",
|
|
72
|
+
"meetingClosing": "Read them with read_messages(meetingId); post with send_message(meetingId) only when you have something to add.",
|
|
73
|
+
"meetingEnded": "Meeting \"%s\" (%s) has ended%s. No reply needed.",
|
|
74
|
+
"stanceNotice": "%s %s draft #%d of meeting \"%s\" (%s)%s. No reply needed.",
|
|
75
|
+
"approversChanged": "Required approvers of draft #%d changed (version %d): %s.",
|
|
76
|
+
"consensusDecision": "Decision by consensus on draft #%d: every required approver (%s) endorsed it.\n\n%s",
|
|
77
|
+
"stanceReminder": "Meeting \"%s\" (%s) waits for your stance on draft #%d: call stance with meetingId and messageId %d, endorse or object (with a reason). No other reply needed.",
|
|
78
|
+
"stanceWaiting": "Meeting \"%s\" (%s): draft #%d still waits for the stance of %s. No reply needed.",
|
|
62
79
|
"noAgentSessionError": "This call carries no agent session, so direct messaging cannot tell who you are. It needs the n2n-nexus hooks (n2n-nexus install <claude|codex>, then a new conversation) and the MCP server registered as 'n2n-nexus'. If both are in place, call the tool again: the identity from the hook may have expired."
|
|
63
80
|
},
|
|
64
81
|
"schemas": {
|