@durableintel/nenya 0.0.0-stage → 1.2.1

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.
@@ -0,0 +1,752 @@
1
+ // `nenya message`: an agent's message to its swarm through Nenya (agent-loop-1027 DESIGN §2, §4.4;
2
+ // CONTRACT C11), for any agent that can run a shell command, so MCP isn't required. The command
3
+ // sends one `tools/call` of Nenya's `message` tool through Edge's local socket, framed as the
4
+ // installed `nenya-hook` relay frames it (apps/desktop/src/shared/ipc/shim.ts), and prints the
5
+ // tool's answer: whether it went, to whom and on which thread. Edge tells who sends it from the
6
+ // calling process, never from the arguments, so there is no option that names a sender.
7
+ //
8
+ // This file and lib/tools.mjs stand alone (node: built-ins only), so the desktop can ship the two as
9
+ // the `nenya` command on a run's PATH: run directly, this one takes `nenya message …`, `nenya tools …`
10
+ // (agent-loop-1027 C14) or the message's own arguments.
11
+ import { spawn } from "node:child_process";
12
+ import { createHash } from "node:crypto";
13
+ import { existsSync, lstatSync, readFileSync, realpathSync } from "node:fs";
14
+ import { connect } from "node:net";
15
+ import { homedir } from "node:os";
16
+ import { fileURLToPath } from "node:url";
17
+ import { parseArgs } from "node:util";
18
+ // tools.mjs reads this file's link to Edge; neither uses the other's bindings while it loads
19
+ import { toolsMain } from "./tools.mjs";
20
+
21
+ /** The message tool's kinds (plugin-core.json `message`); status is not one of them. */
22
+ export const MESSAGE_KINDS = [
23
+ "notice",
24
+ "ask",
25
+ "reply",
26
+ "handoff",
27
+ "review",
28
+ "help",
29
+ "list",
30
+ ];
31
+ export const VERDICTS = ["ready", "fix", "block"];
32
+ export const HANDOFF_ANSWERS = ["accepted", "declined", "done"];
33
+ /** The most a message says (SwarmSend.text), counted as Edge and the router count it. */
34
+ export const MESSAGE_MAX_CHARS = 1_200;
35
+ /** How long the command waits for Nenya's answer; Edge answers "queued" on its own before this. */
36
+ export const MESSAGE_BUDGET_MS = 20_000;
37
+
38
+ export const NOT_RUNNING = "Nenya isn't running, so the message wasn't sent.";
39
+ // No answer at all within the budget (Edge answers "queued" itself well before it): whether the message went is not
40
+ // known, so the command says so and never claims it (Astra on !1141).
41
+ export const UNANSWERED =
42
+ "Nenya didn't answer in time, so the message may not have gone; run nenya message list to see whether it did.";
43
+ export const ENDED =
44
+ "Nenya stopped before it answered; run nenya message list to see whether the message went.";
45
+ const OLD_NENYA =
46
+ "This copy of Nenya doesn't carry messages between agents yet: update Nenya, then send it again.";
47
+
48
+ // A ref in one of the forms the router reads (services/core brain/base/messages/checks.ts REF).
49
+ const REF =
50
+ /^(?:sha:[0-9a-f]{7,40}|mr:[1-9]\d{0,8}|check:[\w.:@/+-]{1,200}|file:[^\s]{1,300}|pipeline:[1-9]\d{0,11})$/u;
51
+
52
+ export const SHIM_PROTOCOL_VERSION = 1;
53
+ // The event of this command's frames on Edge's socket (apps/desktop mcp/server.ts MESSAGE_CLI_EVENT): Edge tells the
54
+ // sender from the process that runs the command, never from what the frame says.
55
+ export const MESSAGE_CLI_EVENT = "nenya-message";
56
+ const SHIM_MAX_FRAME_BYTES = 4 * 1024 * 1024;
57
+ const RUN_FILE_LIMIT = 4096;
58
+ const SOCKET_PATH_LIMIT = 100;
59
+ const SOCKET_PATH_BYTE_LIMIT = 107;
60
+ const PIPE_PREFIX = "\\\\.\\pipe\\";
61
+ const WSL_RELAY_PREFIX = "wsl-relay:";
62
+ export const WSL_INTEROP = [
63
+ "/proc/sys/fs/binfmt_misc/WSLInterop",
64
+ "/proc/sys/fs/binfmt_misc/WSLInterop-late",
65
+ ];
66
+ // `nenya-hook.exe relay` ends with these when Edge never answered (cmd/nenya-hook wsl_relay.go).
67
+ const RELAY_EXIT_EDGE_DOWN = 3;
68
+ const RELAY_EXIT_EDGE_BUSY = 4;
69
+
70
+ export const MESSAGE_USAGE = `Usage: nenya message <to> <kind> <text…> [options]
71
+ nenya message --to NAME --kind KIND --text TEXT [options]
72
+ nenya message list
73
+
74
+ Message a teammate in your swarm through Nenya. Your swarm is the other top-level agents working on
75
+ this goal with you: not the user, and not subagents. Nenya knows which agent you are, so nothing
76
+ says who sends it.
77
+
78
+ Send one actionable unit per message (an ask, a handoff, a review verdict, a finding for help, or a
79
+ notice a teammate must act on), with refs for what it rests on. Never send status or progress:
80
+ Nenya keeps those.
81
+
82
+ Kinds
83
+ notice A fact a teammate must act on.
84
+ nenya message builder notice "main moved under you: rebase before you push" --ref sha:<commit>
85
+ ask One thing you need, and what done looks like.
86
+ nenya message reviewer ask "Review the retry change" --ref mr:42 --done-when "a verdict on mr:42" --reply-wanted
87
+ reply An answer, on the thread the message came with.
88
+ nenya message lead reply "The flaky test was the clock; fixed" --thread <id> --ref check:unit
89
+ handoff A piece of work for a teammate to take over.
90
+ nenya message builder handoff "Take over the retry fix" --ref file:src/retry.ts --done-when "pipeline green"
91
+ Answer one as a reply on its thread:
92
+ nenya message lead reply "Taking it" --thread <id> --handoff accepted
93
+ review Your verdict: ready, fix or block, with the findings in the text. A finding counts only
94
+ once reproduced: add --reproduced when you ran the failing check yourself and saw it fail.
95
+ nenya message builder review "parse() drops the last line" --verdict fix --reproduced --ref check:unit --ref sha:<commit>
96
+ help A finding you are stuck on, for whoever can unblock it.
97
+ nenya message swarm help "CI can't reach the staging database" --ref pipeline:118
98
+ list Your open threads.
99
+ nenya message list
100
+
101
+ Addresses
102
+ <name> A teammate by name or role, such as builder or reviewer.
103
+ lead The swarm's lead.
104
+ swarm Every teammate. Use it sparingly.
105
+ nenya Nenya itself: the goal's parts, their states and the open threads.
106
+
107
+ Options
108
+ --ref R What it rests on, once per ref: sha:<commit>, mr:<n>, check:<id>,
109
+ file:<path> or pipeline:<n>.
110
+ --thread ID The thread it goes on: the id the message came with. A reply needs it.
111
+ --done-when TEXT For an ask or a handoff: what done looks like.
112
+ --reply-wanted You wait for an answer: Nenya holds the thread open until it comes.
113
+ --verdict V For a review: ready, fix or block.
114
+ --reproduced For a review: you ran the failing check or step yourself and saw it fail.
115
+ --handoff A Answering a handoff (kind reply, on its thread): accepted, declined or done.
116
+ --to, --kind, --text
117
+ The same as the words before the options. Text that starts with - goes
118
+ after -- (nenya message lead ask -- -1 is wrong) or as --text=TEXT.
119
+ --help Show this help.
120
+
121
+ The text is the one thing to act on, at most ${MESSAGE_MAX_CHARS.toLocaleString("en-US")} characters.
122
+
123
+ The result
124
+ Nenya says whether it went, to whom and on which thread ("Sent to builder on thread <id>."), then
125
+ any messages waiting for you. "Not sent" says why; "queued" means Nenya has it and delivers it.
126
+ Exit status 0: Nenya took it; 1: not sent, or not known to have gone (nenya message list shows
127
+ your threads); 2: the command line was wrong.`;
128
+
129
+ // The data folder's parts joined as the platform spells them (shared/ipc/paths.ts).
130
+ const joinFor = (platform, ...parts) =>
131
+ parts.join(platform === "win32" ? "\\" : "/");
132
+
133
+ /**
134
+ * Nenya's data folder, as the desktop names it (apps/desktop/src/shared/ipc/paths.ts nenyaDataDir,
135
+ * edge/core/paths.ts defaultDataDir): NENYA_DATA_DIR when Nenya sets it for a run; else macOS
136
+ * ~/Library/Application Support/Nenya, Windows %LOCALAPPDATA%\Nenya, Linux $XDG_DATA_HOME/nenya
137
+ * (~/.local/share/nenya).
138
+ */
139
+ export function nenyaDataDir(platform, env, home) {
140
+ if (env.NENYA_DATA_DIR) return env.NENYA_DATA_DIR;
141
+ const base = (platform === "win32" ? env.USERPROFILE : env.HOME) || home;
142
+ if (platform === "darwin")
143
+ return joinFor(platform, base, "Library", "Application Support", "Nenya");
144
+ if (platform === "win32")
145
+ return joinFor(
146
+ platform,
147
+ env.LOCALAPPDATA || joinFor(platform, base, "AppData", "Local"),
148
+ "Nenya",
149
+ );
150
+ return joinFor(
151
+ platform,
152
+ env.XDG_DATA_HOME || joinFor(platform, base, ".local", "share"),
153
+ "nenya",
154
+ );
155
+ }
156
+
157
+ // The first line of a file Edge writes in its run folder (edge.addr, edge.token), as the shim reads
158
+ // it (cmd/nenya-hook location.go readRunLine): only a regular file of this account's of at most
159
+ // 4 KiB; anything else reads as none.
160
+ function readRunLine(path, platform, uid) {
161
+ let stat;
162
+ try {
163
+ stat = lstatSync(path);
164
+ } catch {
165
+ return "";
166
+ }
167
+ if (!stat.isFile() || stat.size > RUN_FILE_LIMIT) return "";
168
+ if (platform !== "win32" && uid >= 0 && stat.uid !== uid) return "";
169
+ try {
170
+ return readFileSync(path, "utf8").split("\n")[0].trim();
171
+ } catch {
172
+ return "";
173
+ }
174
+ }
175
+
176
+ // An absolute, clean unix socket path that fits a socket address (location.go socketPath).
177
+ function socketPath(path) {
178
+ return (
179
+ path.startsWith("/") &&
180
+ Buffer.byteLength(path) <= SOCKET_PATH_BYTE_LIMIT &&
181
+ !path.includes("\0") &&
182
+ path
183
+ .slice(1)
184
+ .split("/")
185
+ .every((part) => part !== "" && part !== "." && part !== "..")
186
+ );
187
+ }
188
+
189
+ // A loopback tcp://127.x.y.z:port (Edge's WSL listener), as host and port, or null.
190
+ function loopbackEndpoint(hostPort) {
191
+ const match = /^(localhost|\d{1,3}(?:\.\d{1,3}){3}):(\d{1,5})$/.exec(
192
+ hostPort,
193
+ );
194
+ if (!match) return null;
195
+ const host = match[1] === "localhost" ? "127.0.0.1" : match[1];
196
+ const octets = host.split(".");
197
+ if (
198
+ octets[0] !== "127" ||
199
+ octets.some((part) => Number(part) > 255 || /^0\d/.test(part))
200
+ )
201
+ return null;
202
+ const port = Number(match[2]);
203
+ return port >= 1 && port <= 65535 ? { host, port } : null;
204
+ }
205
+
206
+ // edge.addr as the shim takes it (location.go parseEdgeAddress): a pipe of Nenya's, a clean socket
207
+ // path, a loopback port with its token, or the WSL relay inside WSL; anything else is no address.
208
+ function parseEdgeAddress(line, runDir, context) {
209
+ if (line.startsWith(WSL_RELAY_PREFIX)) {
210
+ const executable = line.slice(WSL_RELAY_PREFIX.length);
211
+ return context.insideWSL &&
212
+ executable.startsWith("/") &&
213
+ !executable.includes("\0")
214
+ ? { network: "wsl-relay", address: executable }
215
+ : null;
216
+ }
217
+ if (line.startsWith(PIPE_PREFIX)) {
218
+ const rest = line.slice(PIPE_PREFIX.length);
219
+ return /^nenya-[A-Za-z0-9_.-]+$/.test(rest) && line.length <= 256
220
+ ? { network: "pipe", address: line }
221
+ : null;
222
+ }
223
+ if (line.startsWith("tcp://")) {
224
+ const endpoint = loopbackEndpoint(line.slice(6).replace(/\/$/, ""));
225
+ if (!endpoint) return null;
226
+ const token = readRunLine(
227
+ joinFor(context.platform, runDir, "edge.token"),
228
+ context.platform,
229
+ context.uid,
230
+ );
231
+ return /^[\x21-\x7e]{1,512}$/.test(token)
232
+ ? { network: "tcp", ...endpoint, token }
233
+ : null;
234
+ }
235
+ const path = line.startsWith("unix:")
236
+ ? line.slice(5).replace(/^\/\//, "")
237
+ : line;
238
+ return socketPath(path) ? { network: "unix", address: path } : null;
239
+ }
240
+
241
+ /**
242
+ * Where Edge listens, found as the installed shim finds it: the one line Edge writes to
243
+ * `<dataDir>/run/edge.addr`; else `<dataDir>/run/edge.sock` (a long data folder's socket in
244
+ * $TMPDIR/nenya-<uid>/edge-<hash>.sock), or on Windows the pipe `\\.\pipe\nenya-edge-<user>`.
245
+ */
246
+ export function edgeEndpoint(context) {
247
+ const { platform, env, uid } = context;
248
+ const dataDir = nenyaDataDir(platform, env, context.home);
249
+ const runDir = joinFor(platform, dataDir, "run");
250
+ const line = readRunLine(
251
+ joinFor(platform, runDir, "edge.addr"),
252
+ platform,
253
+ uid,
254
+ );
255
+ const address = line ? parseEdgeAddress(line, runDir, context) : null;
256
+ if (address) return address;
257
+ if (platform === "win32")
258
+ return {
259
+ network: "pipe",
260
+ address: `${PIPE_PREFIX}nenya-edge-${(env.USERNAME ?? "").replace(/[^A-Za-z0-9_.-]/g, "_")}`,
261
+ };
262
+ const socket = joinFor(platform, runDir, "edge.sock");
263
+ if (Buffer.byteLength(socket) <= SOCKET_PATH_LIMIT)
264
+ return { network: "unix", address: socket };
265
+ // #4728: one fallback socket per data folder, named from its real spelling (location.go fallbackSocketName)
266
+ let key = dataDir.replace(/\/+$/, "") || "/";
267
+ try {
268
+ key = realpathSync(key);
269
+ } catch {
270
+ // a folder that isn't there yet is named as given
271
+ }
272
+ const name = `edge-${createHash("sha256").update(key, "utf8").digest("hex").slice(0, 12)}.sock`;
273
+ return {
274
+ network: "unix",
275
+ address: joinFor(platform, env.TMPDIR || "/tmp", `nenya-${uid}`, name),
276
+ privateParent: true,
277
+ };
278
+ }
279
+
280
+ // The fallback socket's folder is this account's alone (0700, not a link): owner_unix.go privateDirectory.
281
+ function privateFolder(path, uid) {
282
+ try {
283
+ const stat = lstatSync(path);
284
+ return (
285
+ stat.isDirectory() && (stat.mode & 0o777) === 0o700 && stat.uid === uid
286
+ );
287
+ } catch {
288
+ return false;
289
+ }
290
+ }
291
+
292
+ // The relay's environment: WSL_DISTRO_NAME shared into the Windows process through WSLENV, once
293
+ // (wsl_relay.go relayEnvironment), for the preamble the relay writes.
294
+ function relayEnvironment(env) {
295
+ const shared = env.WSLENV ?? "";
296
+ if (
297
+ shared.split(":").some((name) => name.split("/")[0] === "WSL_DISTRO_NAME")
298
+ )
299
+ return { ...env };
300
+ return {
301
+ ...env,
302
+ WSLENV: `${shared ? `${shared}:` : ""}WSL_DISTRO_NAME/u`,
303
+ };
304
+ }
305
+
306
+ function failure(code, message = code) {
307
+ return Object.assign(new Error(message), { code });
308
+ }
309
+
310
+ /**
311
+ * Opens Edge's endpoint. `on.connected()` once frames can be written, `on.data(chunk)` for what
312
+ * Edge writes back, `on.closed(error)` once, when the connection ends (error: why it ended, if it
313
+ * failed; `code` is the system's, or EDGE_DOWN / EDGE_BUSY from the WSL relay). `env` is the
314
+ * environment the WSL relay starts with; `uid` this account's (the fallback socket's folder is
315
+ * checked against it). Returns `{ write(bytes), close() }`.
316
+ */
317
+ export function edgeConnect(endpoint, on, { env, uid }) {
318
+ if (endpoint.network === "wsl-relay") {
319
+ let failed = null;
320
+ let started = false;
321
+ let heard = false;
322
+ const executable = endpoint.address;
323
+ // started in its own folder: the agent's Linux folder may be one Windows can't name (wsl_relay_unix.go)
324
+ const child = spawn(executable, ["relay"], {
325
+ cwd: executable.slice(0, executable.lastIndexOf("/")) || "/",
326
+ env: relayEnvironment(env),
327
+ stdio: ["pipe", "pipe", "ignore"],
328
+ windowsHide: true,
329
+ });
330
+ child.on("spawn", () => {
331
+ started = true;
332
+ on.connected();
333
+ });
334
+ child.on("error", (error) => {
335
+ failed ??= error;
336
+ // a relay that never started (WSL interop off, the exe gone) has no close to wait for
337
+ if (!started) on.closed(error);
338
+ });
339
+ child.stdin.on("error", () => {});
340
+ child.stdout.on("data", (chunk) => {
341
+ heard = true;
342
+ on.data(chunk);
343
+ });
344
+ child.on("close", (code) => {
345
+ if (!failed && !heard && code === RELAY_EXIT_EDGE_DOWN)
346
+ failed = failure("EDGE_DOWN");
347
+ if (!failed && !heard && code === RELAY_EXIT_EDGE_BUSY)
348
+ failed = failure("EDGE_BUSY");
349
+ on.closed(failed);
350
+ });
351
+ return {
352
+ write: (bytes) => child.stdin.write(bytes),
353
+ close: () => {
354
+ if (child.exitCode === null && child.signalCode === null) child.kill();
355
+ },
356
+ };
357
+ }
358
+ if (endpoint.privateParent) {
359
+ const folder = endpoint.address.slice(0, endpoint.address.lastIndexOf("/"));
360
+ if (!privateFolder(folder, uid)) {
361
+ const missing = !existsSync(folder);
362
+ queueMicrotask(() =>
363
+ on.closed(
364
+ missing
365
+ ? failure("ENOENT")
366
+ : failure(
367
+ "EPERM",
368
+ "its socket folder isn't private to this account",
369
+ ),
370
+ ),
371
+ );
372
+ return { write: () => {}, close: () => {} };
373
+ }
374
+ }
375
+ let failed = null;
376
+ const socket =
377
+ endpoint.network === "tcp"
378
+ ? connect({ host: endpoint.host, port: endpoint.port })
379
+ : connect({ path: endpoint.address });
380
+ socket.on("connect", () => {
381
+ // Edge's tcp listener takes its token first (transport.go openEdge)
382
+ if (endpoint.token)
383
+ socket.write(encodeFrame({ v: 1, kind: "auth", token: endpoint.token }));
384
+ on.connected();
385
+ });
386
+ socket.on("data", (chunk) => on.data(chunk));
387
+ socket.on("error", (error) => {
388
+ failed ??= error;
389
+ });
390
+ socket.on("close", () => on.closed(failed));
391
+ return {
392
+ write: (bytes) => socket.write(bytes),
393
+ close: () => socket.destroy(),
394
+ };
395
+ }
396
+
397
+ // u32 big-endian length, then that many bytes of UTF-8 JSON (shim.ts encodeShimFrame).
398
+ function encodeFrame(message) {
399
+ const body = Buffer.from(JSON.stringify(message), "utf8");
400
+ const head = Buffer.alloc(4);
401
+ head.writeUInt32BE(body.length, 0);
402
+ return Buffer.concat([head, body]);
403
+ }
404
+
405
+ // The frames in what has arrived so far (shim.ts ShimFrameDecoder); throws on a frame over 4 MiB.
406
+ function frameDecoder() {
407
+ let buffered = Buffer.alloc(0);
408
+ return (chunk) => {
409
+ buffered = Buffer.concat([buffered, chunk]);
410
+ const frames = [];
411
+ while (buffered.length >= 4) {
412
+ const length = buffered.readUInt32BE(0);
413
+ if (length > SHIM_MAX_FRAME_BYTES)
414
+ throw new Error(`a frame of ${length} bytes`);
415
+ if (buffered.length - 4 < length) break;
416
+ frames.push(
417
+ JSON.parse(buffered.subarray(4, 4 + length).toString("utf8")),
418
+ );
419
+ buffered = buffered.subarray(4 + length);
420
+ }
421
+ return frames;
422
+ };
423
+ }
424
+
425
+ // A ULID, as the shim names its requests: 48 bits of time, 80 random.
426
+ export function ulid(now) {
427
+ const alphabet = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
428
+ let time = "";
429
+ for (let rest = now, i = 0; i < 10; i += 1, rest = Math.floor(rest / 32))
430
+ time = alphabet[rest % 32] + time;
431
+ const random = globalThis.crypto.getRandomValues(new Uint8Array(16));
432
+ return time + Array.from(random, (byte) => alphabet[byte & 31]).join("");
433
+ }
434
+
435
+ // The tool's answer in the JSON-RPC response a ShimResponse carries in stdout, or null for any other
436
+ // frame (a notification Edge sends on the same connection).
437
+ function answerOf(frame) {
438
+ if (!frame || typeof frame !== "object" || typeof frame.stdout !== "string")
439
+ return null;
440
+ let message;
441
+ try {
442
+ message = JSON.parse(frame.stdout);
443
+ } catch {
444
+ return null;
445
+ }
446
+ return message &&
447
+ message.id === 1 &&
448
+ ("result" in message || "error" in message)
449
+ ? message
450
+ : null;
451
+ }
452
+
453
+ // One request on one connection: resolves to { answer }, { unanswered } (connected, no answer within
454
+ // the budget), { ended } (the connection ended after the request went, with no answer) or
455
+ // { failed: error } (the request never reached Edge). The connection is never half-closed before
456
+ // the answer: Edge stops writing to an mcp connection whose peer has ended its side.
457
+ export function exchange(
458
+ connectEdge,
459
+ endpoint,
460
+ request,
461
+ { budgetMs, env, uid },
462
+ ) {
463
+ return new Promise((resolve) => {
464
+ let connected = false;
465
+ let settled = false;
466
+ let link = null;
467
+ const decode = frameDecoder();
468
+ const settle = (outcome) => {
469
+ if (settled) return;
470
+ settled = true;
471
+ clearTimeout(timer);
472
+ link?.close();
473
+ resolve(outcome);
474
+ };
475
+ const timer = setTimeout(
476
+ () =>
477
+ settle(
478
+ connected
479
+ ? { unanswered: true }
480
+ : { failed: failure("ETIMEDOUT", "it didn't answer") },
481
+ ),
482
+ budgetMs,
483
+ );
484
+ const on = {
485
+ connected() {
486
+ connected = true;
487
+ link.write(encodeFrame(request));
488
+ },
489
+ data(chunk) {
490
+ let frames;
491
+ try {
492
+ frames = decode(chunk);
493
+ } catch {
494
+ settle({ ended: true });
495
+ return;
496
+ }
497
+ for (const frame of frames) {
498
+ const answer = answerOf(frame);
499
+ if (answer) settle({ answer });
500
+ }
501
+ },
502
+ closed(error) {
503
+ // the WSL relay started but found no Edge to carry the request to: it never went
504
+ const relayed =
505
+ error?.code === "EDGE_DOWN" || error?.code === "EDGE_BUSY";
506
+ if (connected && !relayed) settle({ ended: true });
507
+ else settle({ failed: error ?? failure("ECONNRESET") });
508
+ },
509
+ };
510
+ try {
511
+ link = connectEdge(endpoint, on, { env, uid });
512
+ } catch (error) {
513
+ settle({ failed: error });
514
+ }
515
+ });
516
+ }
517
+
518
+ // Why the request never reached Edge, as one line.
519
+ function unreachableLine(error) {
520
+ const code = error?.code ?? "";
521
+ if (["ENOENT", "ECONNREFUSED", "EDGE_DOWN"].includes(code))
522
+ return NOT_RUNNING;
523
+ if (code === "EDGE_BUSY")
524
+ return "Nenya stayed busy, so the message wasn't sent. Send it again.";
525
+ if (
526
+ ["ENOEXEC", "EACCES"].includes(code) &&
527
+ String(error?.syscall).startsWith("spawn")
528
+ )
529
+ return "WSL can't start Nenya's Windows relay here, so the message wasn't sent.";
530
+ // a system error says its code; one of this file's says its words
531
+ const why = error?.syscall ? code : (error?.message ?? code);
532
+ return `Nenya couldn't be reached${why ? ` (${why})` : ""}, so the message wasn't sent.`;
533
+ }
534
+
535
+ const either = (choices) =>
536
+ `${choices.slice(0, -1).join(", ")} or ${choices[choices.length - 1]}`;
537
+
538
+ // The message tool's arguments from the command line, or the one line that says what is wrong.
539
+ // Only what Edge or the router would refuse anyway is checked here.
540
+ function messageArguments(values, positionals) {
541
+ const words = [...positionals];
542
+ const listOnly =
543
+ values.to === undefined &&
544
+ values.kind === undefined &&
545
+ words[0]?.toLowerCase() === "list";
546
+ const to = (listOnly ? undefined : (values.to ?? words.shift()))?.trim();
547
+ const kind = (values.kind ?? words.shift())?.trim().toLowerCase();
548
+ if (!kind) return `Say what kind of message it is: ${either(MESSAGE_KINDS)}.`;
549
+ if (!MESSAGE_KINDS.includes(kind))
550
+ return `'${kind}' isn't a message kind: use ${either(MESSAGE_KINDS)}.${/^(status|progress|update)$/.test(kind) ? " Never send status: Nenya keeps it." : ""}`;
551
+ if (values.text !== undefined && words.length > 0)
552
+ return "Give the text once: as words or with --text, not both.";
553
+ const text = (values.text ?? words.join(" ")).trim();
554
+ const list = kind === "list";
555
+ if (!list && !to && kind !== "reply")
556
+ return "Say who it's for: a teammate's name, lead, swarm or nenya.";
557
+ if (!list && !text) return "Say what it's about: the one thing to act on.";
558
+ if (text.length > MESSAGE_MAX_CHARS)
559
+ return `Keep a message to ${MESSAGE_MAX_CHARS.toLocaleString("en-US")} characters (this one is ${text.length.toLocaleString("en-US")}): the one thing to act on, with refs for the rest.`;
560
+ const refs = (values.ref ?? []).map((ref) => ref.trim()).filter(Boolean);
561
+ for (const ref of refs) {
562
+ if (!REF.test(ref.startsWith("sha:") ? ref.toLowerCase() : ref))
563
+ return `'${ref}' isn't a ref Nenya reads: use sha:<commit>, mr:<n>, check:<id>, file:<path> or pipeline:<n>.`;
564
+ }
565
+ const thread = values.thread?.trim();
566
+ if (kind === "reply" && !thread)
567
+ return "A reply goes on its thread: pass --thread with the id the message came with (nenya message list shows them).";
568
+ const verdict = values.verdict?.trim().toLowerCase();
569
+ if (verdict !== undefined && kind !== "review")
570
+ return "--verdict goes with a review: send it as kind review.";
571
+ if (kind === "review" && !VERDICTS.includes(verdict ?? ""))
572
+ return `A review says its verdict: --verdict ${either(VERDICTS)}.`;
573
+ const handoff = values.handoff?.trim().toLowerCase();
574
+ if (handoff !== undefined && !HANDOFF_ANSWERS.includes(handoff))
575
+ return `A handoff is answered ${either(HANDOFF_ANSWERS)}.`;
576
+ if (handoff !== undefined && kind !== "reply")
577
+ return "--handoff answers a handoff: send it as kind reply on the handoff's thread.";
578
+ const args = { kind };
579
+ if (to) args.to = to;
580
+ if (text) args.text = text;
581
+ if (refs.length > 0) args.refs = refs;
582
+ if (thread) args.thread = thread;
583
+ const doneWhen = values["done-when"]?.trim();
584
+ if (doneWhen) args.done_when = doneWhen;
585
+ if (values["reply-wanted"]) args.reply_wanted = true;
586
+ if (verdict) args.verdict = verdict;
587
+ if (values.reproduced) args.reproduced = true;
588
+ if (handoff) args.handoff = handoff;
589
+ return args;
590
+ }
591
+
592
+ // A parseArgs refusal as one line.
593
+ function optionError(error) {
594
+ const named = /'(-[^' ]*)/.exec(error.message)?.[1];
595
+ if (error.code === "ERR_PARSE_ARGS_UNKNOWN_OPTION" && named)
596
+ return `'${named}' isn't an option of nenya message (nenya message --help lists them).`;
597
+ // a value that starts with - (parseArgs won't take it as the option's value on its own)
598
+ if (/ambiguous/.test(error.message) && named)
599
+ return `Join a value that starts with - to its option: ${named}=VALUE.`;
600
+ return `${error.message.split(/\.(?:\s|$)/)[0]}. nenya message --help lists the options.`;
601
+ }
602
+
603
+ /**
604
+ * Runs `nenya message …` (argv without the word `message`); resolves to the exit status: 0 Nenya took
605
+ * it, 1 not sent, 2 a usage error. context: { platform, env, home, cwd, pid, ppid, uid, connect,
606
+ * out, err, budgetMs?, now?, insideWSL? }.
607
+ */
608
+ export async function messageMain(argv, context) {
609
+ const { env, out, err } = context;
610
+ let values;
611
+ let positionals;
612
+ try {
613
+ ({ values, positionals } = parseArgs({
614
+ args: argv,
615
+ allowPositionals: true,
616
+ options: {
617
+ to: { type: "string" },
618
+ kind: { type: "string" },
619
+ text: { type: "string" },
620
+ ref: { type: "string", multiple: true },
621
+ thread: { type: "string" },
622
+ "done-when": { type: "string" },
623
+ "reply-wanted": { type: "boolean" },
624
+ verdict: { type: "string" },
625
+ reproduced: { type: "boolean" },
626
+ handoff: { type: "string" },
627
+ help: { type: "boolean" },
628
+ },
629
+ }));
630
+ } catch (error) {
631
+ err(optionError(error));
632
+ return 2;
633
+ }
634
+ if (values.help) {
635
+ out(MESSAGE_USAGE);
636
+ return 0;
637
+ }
638
+ if (
639
+ positionals.length === 0 &&
640
+ Object.keys(values).every((name) => name === "help")
641
+ ) {
642
+ out(MESSAGE_USAGE);
643
+ return 2;
644
+ }
645
+ const args = messageArguments(values, positionals);
646
+ if (typeof args === "string") {
647
+ err(args);
648
+ return 2;
649
+ }
650
+ const uid = context.uid ?? -1;
651
+ const insideWSL =
652
+ context.insideWSL ??
653
+ (context.platform === "linux" &&
654
+ (Boolean(env.WSL_DISTRO_NAME) ||
655
+ WSL_INTEROP.some((path) => existsSync(path))));
656
+ const endpoint = edgeEndpoint({ ...context, uid, insideWSL });
657
+ const budgetMs = context.budgetMs ?? MESSAGE_BUDGET_MS;
658
+ const sentAt = (context.now ?? Date.now)();
659
+ const request = {
660
+ v: SHIM_PROTOCOL_VERSION,
661
+ id: ulid(sentAt),
662
+ kind: "mcp",
663
+ assistant: env.NENYA_AGENT?.trim() || "unknown",
664
+ event: MESSAGE_CLI_EVENT,
665
+ sent_at_ms: sentAt,
666
+ budget_ms: budgetMs,
667
+ pid: context.pid,
668
+ ppid: context.ppid,
669
+ cwd: context.cwd,
670
+ ...(env.NENYA_RUN_ID ? { run_id: env.NENYA_RUN_ID } : {}),
671
+ ...(env.NENYA_SESSION_ID ? { session_id: env.NENYA_SESSION_ID } : {}),
672
+ payload: {
673
+ jsonrpc: "2.0",
674
+ id: 1,
675
+ method: "tools/call",
676
+ params: { name: "message", arguments: args },
677
+ },
678
+ };
679
+ const outcome = await exchange(
680
+ context.connect ?? edgeConnect,
681
+ endpoint,
682
+ request,
683
+ { budgetMs, env, uid },
684
+ );
685
+ if (outcome.unanswered) {
686
+ err(UNANSWERED);
687
+ return 1;
688
+ }
689
+ if (outcome.ended) {
690
+ err(ENDED);
691
+ return 1;
692
+ }
693
+ if (outcome.failed) {
694
+ err(unreachableLine(outcome.failed));
695
+ return 1;
696
+ }
697
+ const { answer } = outcome;
698
+ if (answer.error) {
699
+ const said = String(answer.error.message ?? "").replace(/\.$/, "");
700
+ err(`Nenya couldn't send the message${said ? `: ${said}` : ""}.`);
701
+ return 1;
702
+ }
703
+ const text = (answer.result?.content ?? [])
704
+ .filter((item) => item?.type === "text" && typeof item.text === "string")
705
+ .map((item) => item.text.trim())
706
+ .filter(Boolean)
707
+ .join("\n");
708
+ if (answer.result?.isError) {
709
+ // an Edge from before the message tool answers its name as unknown (mcp/server.ts callTool)
710
+ if (text === "Unknown tool: message") err(OLD_NENYA);
711
+ else err(text || "Nenya couldn't send the message.");
712
+ return 1;
713
+ }
714
+ out(text || "Nenya took the message.");
715
+ return 0;
716
+ }
717
+
718
+ // Run directly (the desktop's `nenya` on a run's PATH): `nenya message …`, `nenya tools …` (lib/tools.mjs, shipped
719
+ // beside this file), or the message's arguments.
720
+ function runDirectly() {
721
+ try {
722
+ return (
723
+ process.argv[1] !== undefined &&
724
+ realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)
725
+ );
726
+ } catch {
727
+ return false;
728
+ }
729
+ }
730
+
731
+ if (runDirectly()) {
732
+ const argv = process.argv.slice(2);
733
+ const context = {
734
+ platform: process.platform,
735
+ env: process.env,
736
+ home: homedir(),
737
+ cwd: process.cwd(),
738
+ pid: process.pid,
739
+ ppid: process.ppid,
740
+ uid: process.getuid?.() ?? -1,
741
+ connect: edgeConnect,
742
+ out: (line) => console.log(line),
743
+ err: (line) => console.error(line),
744
+ };
745
+ if (argv[0] === "tools")
746
+ process.exitCode = await toolsMain(argv.slice(1), context);
747
+ else
748
+ process.exitCode = await messageMain(
749
+ argv[0] === "message" ? argv.slice(1) : argv,
750
+ context,
751
+ );
752
+ }