agent-coord-mcp 0.14.0 → 0.16.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.
@@ -0,0 +1,1003 @@
1
+ import { loadLiveTransports, isMarkerLive, isPidAlive } from "./registry.js";
2
+ import { registerTool } from "./registry.js";
3
+ import { sendMessageTool, readMessagesTool } from "./messaging.js";
4
+ import { randomUUID } from "node:crypto";
5
+ import { existsSync, openSync } from "node:fs";
6
+ import { promises as fsp } from "node:fs";
7
+ import { spawn, spawnSync } from "node:child_process";
8
+ import { fileURLToPath } from "node:url";
9
+ import { z } from "zod";
10
+ import path from "node:path";
11
+ import { AGENTS_FILE, CURSOR_DIR, DEFAULT_ROOM, INBOX_DIR, ROOT, ROOM_FILE, ROOMS_DIR, ROOMS_FILE, STATUS_FILE, appendJsonl, cursorFile, deleteFile, ensureRoom, fileSize, getRooms, inboxFile, listCursorFiles, listInboxFiles, listTransportFiles, logFile, normalizeRoom, pidFile, readJson, readJsonl, receiptFile, rewriteJsonl, roomFile, transportFile, TRANSPORT_DIR, updateJson, } from "../store.js";
12
+ import { STALE_MS, EVICT_MS, } from "./shared.js";
13
+ // ---------- ping ----------
14
+ export const pingSchema = {
15
+ from: z.string().min(1),
16
+ to: z.string().min(1),
17
+ echo: z.boolean().optional(),
18
+ };
19
+ // Liveness probe answered entirely from server-side state — registry entry,
20
+ // transport marker, pusher pid, tmux pane. It never touches the target's
21
+ // session, so a fleet-wide sweep costs zero model tokens on the targets.
22
+ // Distinct from `heartbeat` (the target refreshing its own activity
23
+ // timestamp): ping is a third party asking "would a DM land right now?".
24
+ // echo=true is the one exception — it drops a PING DM into the target's inbox
25
+ // (normal delivery, so the target's model DOES wake); opt-in, default off.
26
+ export async function pingTool(args) {
27
+ const t0 = process.hrtime.bigint();
28
+ const now = Date.now();
29
+ const latencyMs = () => Math.round(Number(process.hrtime.bigint() - t0) / 1e3) / 1e3;
30
+ const reg = await readJson(AGENTS_FILE, {});
31
+ const entry = reg[args.to];
32
+ if (!entry) {
33
+ return { ok: true, to: args.to, alive: false, reachable: false, reason: "unregistered", latencyMs: latencyMs() };
34
+ }
35
+ const marker = await readJson(transportFile(args.to), null);
36
+ const heartbeatAgeSec = Math.floor((now - entry.lastHeartbeat) / 1000);
37
+ const heartbeatFresh = now - entry.lastHeartbeat < STALE_MS;
38
+ let transportLive = false;
39
+ let paneAlive;
40
+ if (marker) {
41
+ transportLive = isMarkerLive(marker, reg, now);
42
+ if (transportLive && marker.transport === "tmux-push" && marker.tmuxTarget) {
43
+ // The pusher can outlive its pane (agent window closed) — probe the pane.
44
+ const probe = spawnSync("tmux", ["display-message", "-p", "-t", marker.tmuxTarget, "ok"]);
45
+ paneAlive = probe.status === 0;
46
+ }
47
+ }
48
+ const reachable = transportLive && paneAlive !== false;
49
+ const alive = reachable || heartbeatFresh;
50
+ let echoSent = false;
51
+ if (args.echo && alive) {
52
+ await sendMessageTool({
53
+ from: args.from,
54
+ to: args.to,
55
+ text: `PING: echo requested by ${args.from} — DM back if responsive.`,
56
+ });
57
+ echoSent = true;
58
+ }
59
+ return {
60
+ ok: true,
61
+ to: args.to,
62
+ alive,
63
+ reachable,
64
+ ...(alive ? {} : { reason: marker ? "transport-dead" : "heartbeat-stale" }),
65
+ checks: {
66
+ registered: true,
67
+ heartbeatFresh,
68
+ heartbeatAgeSec,
69
+ transport: marker?.transport ?? null,
70
+ transportLive,
71
+ ...(paneAlive !== undefined ? { paneAlive, tmuxTarget: marker?.tmuxTarget } : {}),
72
+ },
73
+ ...(args.echo ? { echoSent } : {}),
74
+ latencyMs: latencyMs(),
75
+ };
76
+ }
77
+ // ---------- send_command (context-management control commands) ----------
78
+ // The only slash commands a lead may inject into a sub-agent's CLI. Locked on
79
+ // purpose: these wipe/compact context (cheap, reversible-by-the-agent), nothing
80
+ // that mutates the repo or the bus. Stored WITHOUT the leading slash; the wire
81
+ // text is `/${cmd}`.
82
+ export const CONTROL_COMMANDS = ["clear", "compact"];
83
+ // Transports whose pusher can actually TYPE a slash command into a live CLI.
84
+ // A control command is meaningless to a plain MCP poller, so send_command is
85
+ // gated to agents currently attached over one of these.
86
+ const TMUX_TRANSPORTS = new Set(["tmux-push", "tmux-push-remote"]);
87
+ // Normalize "clear" / "/clear" / " /Clear " → "clear"; null if not allowlisted.
88
+ function normalizeControlCommand(raw) {
89
+ const c = raw.trim().replace(/^\/+/, "").toLowerCase();
90
+ return CONTROL_COMMANDS.includes(c) ? c : null;
91
+ }
92
+ // Live transports filtered to the tmux-push family (local + remote).
93
+ async function liveTmuxTargets() {
94
+ const all = await loadLiveTransports();
95
+ const out = new Map();
96
+ for (const [id, m] of all)
97
+ if (TMUX_TRANSPORTS.has(m.transport))
98
+ out.set(id, m);
99
+ return out;
100
+ }
101
+ export const sendCommandSchema = {
102
+ from: z.string().min(1),
103
+ to: z.string().optional(),
104
+ room: z.string().optional(),
105
+ command: z.string().min(1),
106
+ // Default 3000ms. After /clear, schedules an identity-reminder DM to each
107
+ // recipient so a freshly-wiped worker re-anchors on its agentId and bus
108
+ // attach state. Set 0 to opt out. Ignored for non-/clear commands.
109
+ reminderMs: z.number().int().min(0).max(60_000).optional(),
110
+ // Override the auto-generated reminder body if you want something specific.
111
+ reminderText: z.string().optional(),
112
+ // Block until the receiving pusher confirms it actually typed the command
113
+ // into the pane (out-of-band receipt poll — zero added agent context).
114
+ // Default true: a control command you can't confirm is the bug this fixes.
115
+ // Set false for fire-and-forget. The wait is bounded by deliveryTimeoutMs.
116
+ waitForDelivery: z.boolean().optional(),
117
+ deliveryTimeoutMs: z.number().int().min(0).max(30_000).optional(),
118
+ };
119
+ // Poll an agent's receipt log until a receipt for `msgId` appears or the
120
+ // deadline passes. Returns the delivery timestamp, or null on timeout. The
121
+ // receipt is written by the receiver's pusher AFTER send-keys, so a hit is
122
+ // genuine proof the keystrokes reached the pane. File-only — no agent context.
123
+ async function waitForReceipt(agentId, msgId, timeoutMs) {
124
+ const file = receiptFile(agentId);
125
+ const deadline = Date.now() + timeoutMs;
126
+ // First check is immediate; then poll on a short interval.
127
+ for (;;) {
128
+ const receipts = await readJsonl(file);
129
+ const hit = receipts.find((r) => r.id === msgId);
130
+ if (hit)
131
+ return hit.ts ?? Date.now();
132
+ if (Date.now() >= deadline)
133
+ return null;
134
+ await new Promise((res) => setTimeout(res, 150));
135
+ }
136
+ }
137
+ function defaultReminderText(agentId) {
138
+ return (`[agent-coord] context reset by /clear. ` +
139
+ `Your bus identity is '${agentId}'. You remain registered and attached — call ` +
140
+ `status({agentId:"${agentId}"}) to re-orient (role, transport, unread) and ` +
141
+ `list_rooms() for the channels you're in. Any DM or channel post you receive ` +
142
+ `next is your new task context.`);
143
+ }
144
+ function scheduleReminders(from, recipients, delayMs, override) {
145
+ const t = setTimeout(async () => {
146
+ for (const r of recipients) {
147
+ try {
148
+ const reminder = {
149
+ id: randomUUID(),
150
+ ts: Date.now(),
151
+ from,
152
+ to: r,
153
+ text: override ?? defaultReminderText(r),
154
+ // A just-cleared agent is contextless until this lands — it must
155
+ // push immediately, never queue behind the routine tier.
156
+ urgent: true,
157
+ };
158
+ await appendJsonl(inboxFile(r), reminder);
159
+ }
160
+ catch (e) {
161
+ process.stderr.write(`[send_command] post-/clear reminder to '${r}' failed: ${e?.message ?? e}\n`);
162
+ }
163
+ }
164
+ }, delayMs);
165
+ // Don't keep the event loop alive solely for the reminder — the MCP server's
166
+ // transport already holds it open as long as it's connected.
167
+ if (typeof t.unref === "function")
168
+ t.unref();
169
+ }
170
+ // Inject a context-management slash command into a sub-agent's live tmux
171
+ // session. Writes a control-flagged message the pushers deliver RAW (no banner,
172
+ // no `[DM …]` prefix) so the receiving CLI runs it as a real slash command.
173
+ // Hard-gated to tmux: refuses unless the target(s) have a live tmux-push(-remote)
174
+ // transport, so a command never rots unexecuted in an offline inbox.
175
+ export async function sendCommandTool(args) {
176
+ const cmd = normalizeControlCommand(args.command);
177
+ if (!cmd) {
178
+ return {
179
+ ok: false,
180
+ error: `unsupported command '${args.command}'. Allowed: ${CONTROL_COMMANDS.map((c) => "/" + c).join(", ")}`,
181
+ };
182
+ }
183
+ if (!args.to && !args.room) {
184
+ return { ok: false, error: "specify 'to' (a single agent) or 'room' (a channel's tmux-attached members)" };
185
+ }
186
+ if (args.to && args.room) {
187
+ return { ok: false, error: "specify only one of 'to' or 'room'" };
188
+ }
189
+ const text = `/${cmd}`;
190
+ const liveTmux = await liveTmuxTargets();
191
+ // DM: target must itself be tmux-attached.
192
+ if (args.to) {
193
+ const marker = liveTmux.get(args.to);
194
+ if (!marker) {
195
+ return {
196
+ ok: false,
197
+ error: `'${args.to}' has no live tmux-push transport — control commands can only be injected into a tmux session. Attach it (join/attach_agent) or target an attached agent.`,
198
+ };
199
+ }
200
+ const msg = {
201
+ id: randomUUID(),
202
+ ts: Date.now(),
203
+ from: args.from,
204
+ to: args.to,
205
+ text,
206
+ control: true,
207
+ };
208
+ const target = inboxFile(args.to);
209
+ await appendJsonl(target, msg);
210
+ // Confirm the pusher actually typed it into the pane before we report success
211
+ // (unless explicitly fire-and-forget). Out-of-band receipt poll — the
212
+ // confirmation rides back in THIS tool result, costing no extra agent context.
213
+ const wait = args.waitForDelivery ?? true;
214
+ const deliveryTimeoutMs = args.deliveryTimeoutMs ?? 8000;
215
+ const confirmedAt = wait ? await waitForReceipt(args.to, msg.id, deliveryTimeoutMs) : null;
216
+ const confirmed = confirmedAt !== null;
217
+ // After /clear the receiver forgets its identity and that it's bus-attached
218
+ // (the system prompt isn't re-applied because /clear isn't a session
219
+ // start). Schedule a follow-up DM as a re-anchor; opt out with reminderMs:0.
220
+ const reminderMs = cmd === "clear" ? args.reminderMs ?? 3000 : 0;
221
+ if (reminderMs > 0)
222
+ scheduleReminders(args.from, [args.to], reminderMs, args.reminderText);
223
+ return {
224
+ ok: true,
225
+ id: msg.id,
226
+ command: text,
227
+ target,
228
+ delivered: [args.to],
229
+ transport: marker.transport,
230
+ // delivery: confirmed = pusher typed it into the pane; pending = written but
231
+ // unconfirmed within the timeout (stale/wedged pusher — run doctor). Absent
232
+ // when waitForDelivery:false.
233
+ ...(wait
234
+ ? {
235
+ delivery: confirmed ? "confirmed" : "pending",
236
+ confirmed,
237
+ ...(confirmedAt !== null ? { deliveredAt: confirmedAt } : {}),
238
+ ...(confirmed
239
+ ? {}
240
+ : {
241
+ warning: `no delivery receipt from '${args.to}' within ${deliveryTimeoutMs}ms — the command was written but may not have reached the pane (stale/wedged pusher). Run doctor or re-attach the agent.`,
242
+ }),
243
+ }
244
+ : {}),
245
+ ...(reminderMs > 0 ? { reminderScheduled: { delayMs: reminderMs, recipients: [args.to] } } : {}),
246
+ };
247
+ }
248
+ // Room: broadcast to every tmux-attached member (never the sender itself).
249
+ const chan = normalizeRoom(args.room);
250
+ const rooms = await getRooms();
251
+ const members = rooms[chan]?.members ?? [];
252
+ const delivered = members.filter((m) => m !== args.from && liveTmux.has(m));
253
+ if (delivered.length === 0) {
254
+ return {
255
+ ok: false,
256
+ error: `no tmux-attached members in #${chan} to receive '${text}' (${members.length} member(s) total). Control commands only fire in a live tmux session.`,
257
+ };
258
+ }
259
+ const skipped = members.filter((m) => m !== args.from && !liveTmux.has(m));
260
+ const msg = {
261
+ id: randomUUID(),
262
+ ts: Date.now(),
263
+ from: args.from,
264
+ room: chan,
265
+ text,
266
+ control: true,
267
+ };
268
+ const target = roomFile(chan);
269
+ await appendJsonl(target, msg);
270
+ // Confirm each member's pusher typed it in (same msg.id lands in every
271
+ // member's own receipt file). Poll all in parallel within one timeout.
272
+ const wait = args.waitForDelivery ?? true;
273
+ const deliveryTimeoutMs = args.deliveryTimeoutMs ?? 8000;
274
+ let confirmed = [];
275
+ let pending = [];
276
+ if (wait) {
277
+ const results = await Promise.all(delivered.map(async (m) => ({ m, at: await waitForReceipt(m, msg.id, deliveryTimeoutMs) })));
278
+ confirmed = results.filter((r) => r.at !== null).map((r) => r.m);
279
+ pending = results.filter((r) => r.at === null).map((r) => r.m);
280
+ }
281
+ // Same post-/clear re-anchor as the DM path — one reminder per delivered
282
+ // member, in their own inbox, with their own agentId in the body.
283
+ const reminderMs = cmd === "clear" ? args.reminderMs ?? 3000 : 0;
284
+ if (reminderMs > 0)
285
+ scheduleReminders(args.from, delivered, reminderMs, args.reminderText);
286
+ return {
287
+ ok: true,
288
+ id: msg.id,
289
+ command: text,
290
+ target,
291
+ room: chan,
292
+ delivered,
293
+ skipped: skipped.length ? skipped : undefined,
294
+ ...(wait
295
+ ? {
296
+ delivery: pending.length === 0 ? "confirmed" : "partial",
297
+ confirmed,
298
+ ...(pending.length
299
+ ? {
300
+ pending,
301
+ warning: `no delivery receipt within ${deliveryTimeoutMs}ms from: ${pending.join(", ")} — written but may not have reached their panes (stale/wedged pusher). Run doctor.`,
302
+ }
303
+ : {}),
304
+ }
305
+ : {}),
306
+ ...(reminderMs > 0 ? { reminderScheduled: { delayMs: reminderMs, recipients: delivered } } : {}),
307
+ };
308
+ }
309
+ // ---------- attach_agent / detach_agent (tmux push transport) ----------
310
+ export const attachAgentSchema = {
311
+ agentId: z.string().min(1),
312
+ tmuxTarget: z.string().optional(),
313
+ includeRoom: z.boolean().optional(),
314
+ allowlist: z.array(z.string()).optional(),
315
+ debounceMs: z.number().int().positive().max(60_000).optional(),
316
+ };
317
+ export async function attachAgentTool(args) {
318
+ // Resolve target: explicit arg > MCP server's own TMUX_PANE env.
319
+ const target = args.tmuxTarget ?? process.env.TMUX_PANE;
320
+ if (!target) {
321
+ return {
322
+ ok: false,
323
+ error: "tmuxTarget not provided and the MCP server is not running inside tmux (no $TMUX_PANE). Pass tmuxTarget explicitly (e.g. '%42' or 'session:window.pane').",
324
+ };
325
+ }
326
+ // Validate target exists.
327
+ const probe = spawnSync("tmux", ["display-message", "-p", "-t", target, "ok"]);
328
+ if (probe.status !== 0) {
329
+ return {
330
+ ok: false,
331
+ error: `tmux target '${target}' not found: ${(probe.stderr ?? "").toString().trim()}`,
332
+ };
333
+ }
334
+ // If something's already attached, refuse rather than spawn a second pusher.
335
+ const existing = await readJson(transportFile(args.agentId), null);
336
+ if (existing && isPidAlive(existing.pid)) {
337
+ return {
338
+ ok: false,
339
+ error: `agent '${args.agentId}' already has a live ${existing.transport} attached (pid ${existing.pid}). Call detach_agent first.`,
340
+ existing,
341
+ };
342
+ }
343
+ // Clean up dead marker, if any.
344
+ if (existing)
345
+ await deleteFile(transportFile(args.agentId));
346
+ const pusher = resolvePusherPath();
347
+ if (!existsSync(pusher)) {
348
+ return { ok: false, error: `tmux-pusher not found at ${pusher}` };
349
+ }
350
+ // Detached spawn so the pusher outlives this MCP request/process.
351
+ const log = logFile(args.agentId, "pusher");
352
+ await fsp.mkdir(path.dirname(log), { recursive: true });
353
+ await fsp.mkdir(path.dirname(pidFile(args.agentId, "pusher")), { recursive: true });
354
+ await fsp.mkdir(path.dirname(transportFile(args.agentId)), { recursive: true });
355
+ const logFd = openSync(log, "a");
356
+ // Default: deliver room broadcasts too. The bus is chat-first — silence on
357
+ // a room post is a worse failure mode than a slightly noisier pane. Callers
358
+ // who want DM-only can pass includeRoom:false explicitly.
359
+ const includeRoom = args.includeRoom !== false;
360
+ // Use the exact node binary running this server, not bare "node" — the MCP
361
+ // server is often launched via an absolute path (nvm/Homebrew/bundled
362
+ // runtime) that isn't on the spawned child's PATH, which would silently fail
363
+ // the pusher launch ("attached but nothing arrives").
364
+ const child = spawn(process.execPath, [pusher], {
365
+ detached: true,
366
+ stdio: ["ignore", logFd, logFd],
367
+ env: {
368
+ ...process.env,
369
+ AGENT_COORD_ID: args.agentId,
370
+ AGENT_COORD_TMUX_TARGET: target,
371
+ ...(includeRoom ? { AGENT_COORD_INCLUDE_ROOM: "1" } : {}),
372
+ ...(args.allowlist && args.allowlist.length > 0
373
+ ? { AGENT_COORD_ALLOWLIST: args.allowlist.join(",") }
374
+ : {}),
375
+ ...(args.debounceMs ? { AGENT_COORD_DEBOUNCE_MS: String(args.debounceMs) } : {}),
376
+ },
377
+ });
378
+ child.unref();
379
+ const pid = child.pid;
380
+ if (!pid)
381
+ return { ok: false, error: "spawn returned no pid" };
382
+ // Write pid file (for scripts) and transport marker (for list_agents).
383
+ await fsp.writeFile(pidFile(args.agentId, "pusher"), String(pid), "utf8");
384
+ // Stamp the script's mtime so doctor() can flag a stale daemon if it
385
+ // outlives a later upgrade of the on-disk script (see v0.8.1 → v0.8.2 bug
386
+ // report: control commands silently dropped by pre-v0.8 in-memory code).
387
+ let scriptMtime;
388
+ try {
389
+ scriptMtime = (await fsp.stat(pusher)).mtimeMs;
390
+ }
391
+ catch { /* non-fatal */ }
392
+ const marker = {
393
+ agentId: args.agentId,
394
+ transport: "tmux-push",
395
+ pid,
396
+ tmuxTarget: target,
397
+ since: Date.now(),
398
+ scriptMtime,
399
+ };
400
+ // Use updateJson so it lockfile-protects and creates the file atomically.
401
+ await updateJson(transportFile(args.agentId), marker, () => marker);
402
+ // Best-effort scan for a peek-coord.mjs hook wired to the same agentId —
403
+ // both consumers share the cursor file and would race / double-deliver.
404
+ const conflictingHook = await detectPeekCoordHook(args.agentId);
405
+ return {
406
+ ok: true,
407
+ agentId: args.agentId,
408
+ transport: "tmux-push",
409
+ tmuxTarget: target,
410
+ pid,
411
+ log,
412
+ ...(conflictingHook
413
+ ? {
414
+ warnings: [
415
+ `peek-coord.mjs hook for agentId='${args.agentId}' detected in ${conflictingHook}. ` +
416
+ `Running both transports causes double-delivery — disable one. ` +
417
+ `Recommend removing the peek-coord hook entry since tmux-push supersedes it.`,
418
+ ],
419
+ }
420
+ : {}),
421
+ };
422
+ }
423
+ async function detectPeekCoordHook(agentId) {
424
+ const home = process.env.HOME ?? "";
425
+ const cwd = process.cwd();
426
+ const candidates = [
427
+ path.join(home, ".claude", "settings.json"),
428
+ path.join(home, ".claude", "settings.local.json"),
429
+ path.join(cwd, ".claude", "settings.json"),
430
+ path.join(cwd, ".claude", "settings.local.json"),
431
+ ];
432
+ for (const file of candidates) {
433
+ if (!existsSync(file))
434
+ continue;
435
+ try {
436
+ const raw = await fsp.readFile(file, "utf8");
437
+ if (raw.includes("peek-coord.mjs") && raw.includes(`AGENT_COORD_ID=${agentId}`)) {
438
+ return file;
439
+ }
440
+ }
441
+ catch {
442
+ // unreadable, skip
443
+ }
444
+ }
445
+ return undefined;
446
+ }
447
+ export const detachAgentSchema = {
448
+ agentId: z.string().min(1),
449
+ };
450
+ export async function detachAgentTool(args) {
451
+ const marker = await readJson(transportFile(args.agentId), null);
452
+ let killed = false;
453
+ if (marker && isPidAlive(marker.pid)) {
454
+ try {
455
+ process.kill(marker.pid, "SIGTERM");
456
+ killed = true;
457
+ }
458
+ catch {
459
+ // already gone
460
+ }
461
+ }
462
+ await deleteFile(transportFile(args.agentId));
463
+ await deleteFile(pidFile(args.agentId, "pusher"));
464
+ return { ok: true, agentId: args.agentId, killed, hadMarker: marker !== null };
465
+ }
466
+ function resolvePusherPath() {
467
+ // transport.js (compiled) lives in dist/tools/; pusher lives in hooks/ at repo root.
468
+ const here = path.dirname(fileURLToPath(import.meta.url));
469
+ return path.resolve(here, "..", "..", "hooks", "tmux-pusher.mjs");
470
+ }
471
+ // ---------- status / whoami ----------
472
+ export const statusSchema = { agentId: z.string().min(1) };
473
+ export async function statusTool(args) {
474
+ const reg = await readJson(AGENTS_FILE, {});
475
+ const entry = reg[args.agentId];
476
+ const transports = await loadLiveTransports();
477
+ const transport = transports.get(args.agentId);
478
+ const inbox = await readJsonl(inboxFile(args.agentId));
479
+ const cursor = await readJson(cursorFile(args.agentId), {});
480
+ const inboxOffset = cursor.inboxOffset ?? 0;
481
+ const unread = Math.max(0, inbox.length - inboxOffset);
482
+ return {
483
+ agentId: args.agentId,
484
+ registered: !!entry,
485
+ entry,
486
+ attached: !!transport,
487
+ transport,
488
+ inboxDepth: inbox.length,
489
+ inboxUnread: unread,
490
+ inTmux: !!process.env.TMUX_PANE,
491
+ tmuxPane: process.env.TMUX_PANE,
492
+ };
493
+ }
494
+ // ---------- join (combo: register + auto-attach + read inbox) ----------
495
+ const joinAttachOptionsSchema = z.object({
496
+ tmuxTarget: z.string().optional(),
497
+ includeRoom: z.boolean().optional(),
498
+ allowlist: z.array(z.string()).optional(),
499
+ debounceMs: z.number().int().positive().max(60_000).optional(),
500
+ });
501
+ export const joinSchema = {
502
+ agentId: z.string().min(1),
503
+ project: z.string().optional(),
504
+ role: z.string().optional(),
505
+ // attach: undefined → auto-attach if $TMUX_PANE is set; true → always try;
506
+ // false → never; object → attach with overrides.
507
+ attach: z.union([z.boolean(), joinAttachOptionsSchema]).optional(),
508
+ readInbox: z.boolean().optional(),
509
+ };
510
+ export async function joinTool(args) {
511
+ const reg = await registerTool({
512
+ agentId: args.agentId,
513
+ project: args.project,
514
+ role: args.role,
515
+ });
516
+ // Decide attach behavior.
517
+ const wantAttach = args.attach === false
518
+ ? false
519
+ : args.attach === true || typeof args.attach === "object"
520
+ ? true
521
+ : !!process.env.TMUX_PANE; // undefined → auto-detect
522
+ // Always present as object | null so callers can branch on a single key
523
+ // instead of "did I pass attach?" — per agent-pa's API review.
524
+ let attach = null;
525
+ if (wantAttach) {
526
+ const opts = typeof args.attach === "object" ? args.attach : {};
527
+ attach = await attachAgentTool({ agentId: args.agentId, ...opts });
528
+ }
529
+ const readInbox = args.readInbox ?? true;
530
+ let inbox = null;
531
+ if (readInbox) {
532
+ inbox = await readMessagesTool({ agentId: args.agentId, source: "inbox" });
533
+ }
534
+ // Surface the default channel's topic + MOTD (room rules) in the same
535
+ // round-trip, so a connecting agent sees them without a separate call.
536
+ const rooms = await getRooms();
537
+ const def = rooms[DEFAULT_ROOM];
538
+ return {
539
+ ok: true,
540
+ registered: reg.agent,
541
+ attached: !!attach && attach.ok !== false,
542
+ attach,
543
+ inbox,
544
+ defaultRoom: { room: DEFAULT_ROOM, topic: def?.topic, motd: def?.motd },
545
+ inTmux: !!process.env.TMUX_PANE,
546
+ };
547
+ }
548
+ // ---------- transport markers (for remote pushers) ----------
549
+ export const reportTransportSchema = {
550
+ agentId: z.string().min(1),
551
+ transport: z.string().min(1),
552
+ tmuxTarget: z.string().optional(),
553
+ host: z.string().optional(),
554
+ since: z.number().optional(),
555
+ // mtime of the script the remote daemon loaded into memory at spawn time
556
+ // (epoch ms). Lets doctor() flag the remote pusher as stale if its on-disk
557
+ // counterpart has been upgraded since. The remote pusher passes
558
+ // `(await fsp.stat(__filename)).mtimeMs`; absent → doctor skips the check.
559
+ scriptMtime: z.number().optional(),
560
+ };
561
+ // Called by an external push daemon (typically scripts/coord-pusher.mjs on a
562
+ // remote machine) to publish a transport marker so list_agents reflects the
563
+ // attachment. The local tmux-push path writes the marker directly inside
564
+ // attach_agent; this is the wire-callable equivalent for remote pushers.
565
+ export async function reportTransportTool(args) {
566
+ const marker = {
567
+ agentId: args.agentId,
568
+ transport: args.transport,
569
+ pid: 0, // not meaningful for remote; liveness comes from heartbeat
570
+ tmuxTarget: args.tmuxTarget,
571
+ host: args.host,
572
+ since: args.since ?? Date.now(),
573
+ scriptMtime: args.scriptMtime,
574
+ };
575
+ await updateJson(transportFile(args.agentId), marker, () => marker);
576
+ return { ok: true, marker };
577
+ }
578
+ export const clearTransportSchema = {
579
+ agentId: z.string().min(1),
580
+ };
581
+ // Idempotent remote-counterpart to detach_agent: just deletes the marker. Used
582
+ // by the remote pusher on graceful shutdown so list_agents stops showing it
583
+ // attached. (Does NOT try to kill any process — there's nothing local to kill.)
584
+ export async function clearTransportTool(args) {
585
+ const removed = await deleteFile(transportFile(args.agentId));
586
+ return { ok: true, removed };
587
+ }
588
+ // Count non-empty lines vs successfully-parsed entries in a JSONL file.
589
+ // Offsets index the PARSED entries (see readJsonl), so `parsed` is the figure
590
+ // cursor math is compared against; `malformed` is the desync risk.
591
+ async function scanJsonl(file) {
592
+ if (!existsSync(file))
593
+ return { lines: 0, parsed: 0, malformed: 0 };
594
+ const raw = await fsp.readFile(file, "utf8");
595
+ let lines = 0;
596
+ let parsed = 0;
597
+ for (const line of raw.split("\n")) {
598
+ if (!line.trim())
599
+ continue;
600
+ lines++;
601
+ try {
602
+ JSON.parse(line);
603
+ parsed++;
604
+ }
605
+ catch {
606
+ // malformed
607
+ }
608
+ }
609
+ return { lines, parsed, malformed: lines - parsed };
610
+ }
611
+ // Find leftover proper-lockfile lock dirs (`<file>.lock`) across the state
612
+ // dirs. Anything older than the threshold is almost certainly orphaned by a
613
+ // crashed writer (withLock's stale window is 5s).
614
+ async function scanStaleLocks(olderThanMs, now) {
615
+ const out = [];
616
+ const dirs = [ROOT, INBOX_DIR, CURSOR_DIR, ROOMS_DIR, TRANSPORT_DIR];
617
+ for (const dir of dirs) {
618
+ if (!existsSync(dir))
619
+ continue;
620
+ let names;
621
+ try {
622
+ names = await fsp.readdir(dir);
623
+ }
624
+ catch {
625
+ continue;
626
+ }
627
+ for (const name of names) {
628
+ if (!name.endsWith(".lock"))
629
+ continue;
630
+ const p = path.join(dir, name);
631
+ try {
632
+ const st = await fsp.stat(p);
633
+ const ageMs = now - st.mtimeMs;
634
+ if (ageMs > olderThanMs)
635
+ out.push({ path: p, ageMs });
636
+ }
637
+ catch {
638
+ // vanished mid-scan
639
+ }
640
+ }
641
+ }
642
+ return out;
643
+ }
644
+ export const doctorSchema = {
645
+ fix: z.boolean().optional(),
646
+ maxFileBytes: z.number().int().positive().optional(),
647
+ };
648
+ export async function doctorTool(args) {
649
+ const fix = args.fix ?? false;
650
+ const maxBytes = args.maxFileBytes ?? 5 * 1024 * 1024;
651
+ const now = Date.now();
652
+ const findings = [];
653
+ const fixed = [];
654
+ const reg = await readJson(AGENTS_FILE, {});
655
+ const known = new Set(Object.keys(reg));
656
+ const rooms = await getRooms();
657
+ const channels = Object.keys(rooms);
658
+ // 1. Orphan transport markers (dead local pid, or stale remote heartbeat).
659
+ {
660
+ const dead = [];
661
+ for (const fname of await listTransportFiles()) {
662
+ const file = path.join(TRANSPORT_DIR, fname);
663
+ const marker = await readJson(file, null);
664
+ if (!marker || !isMarkerLive(marker, reg, now)) {
665
+ dead.push(file);
666
+ if (fix) {
667
+ await deleteFile(file);
668
+ fixed.push(`deleted stale transport marker ${fname}`);
669
+ }
670
+ }
671
+ }
672
+ findings.push({
673
+ check: "orphan-transport-markers",
674
+ level: dead.length ? "warn" : "ok",
675
+ detail: dead.length ? `${dead.length} stale transport marker(s) (dead pid or expired remote heartbeat)` : "no stale transport markers",
676
+ fixable: true,
677
+ items: dead.length ? dead.map((f) => path.basename(f)) : undefined,
678
+ });
679
+ }
680
+ // 1b. Stale pusher daemons — a long-running pusher loaded its script into
681
+ // memory at spawn time, so when the on-disk script is later upgraded
682
+ // (npm i -g a new version), the still-running pid is on the OLD code.
683
+ // Pre-v0.8.2 pushers had no `control:true` awareness and silently
684
+ // dropped /clear /compact at the slash-guard — ack:true with no
685
+ // keystrokes ever reaching the pane. Comparing the marker's stamped
686
+ // scriptMtime against the on-disk script's current mtime catches it.
687
+ // Local tmux-push only — for tmux-push-remote the script lives on a
688
+ // different host so we can't stat it from here.
689
+ {
690
+ let localPusherMtime;
691
+ try {
692
+ localPusherMtime = (await fsp.stat(resolvePusherPath())).mtimeMs;
693
+ }
694
+ catch { /* not packaged? skip */ }
695
+ const stale = [];
696
+ for (const fname of await listTransportFiles()) {
697
+ const file = path.join(TRANSPORT_DIR, fname);
698
+ const marker = await readJson(file, null);
699
+ if (!marker || !isMarkerLive(marker, reg, now))
700
+ continue;
701
+ if (marker.transport !== "tmux-push")
702
+ continue; // remote = can't verify
703
+ if (marker.scriptMtime === undefined)
704
+ continue; // pre-v0.8.2 marker, no info
705
+ if (localPusherMtime === undefined)
706
+ continue;
707
+ if (marker.scriptMtime < localPusherMtime - 1) { // -1ms slack for fs mtime rounding
708
+ const loaded = new Date(marker.scriptMtime).toISOString();
709
+ const ondisk = new Date(localPusherMtime).toISOString();
710
+ stale.push(`${marker.agentId} (pid ${marker.pid}, loaded ${loaded}, on-disk now ${ondisk})`);
711
+ }
712
+ }
713
+ findings.push({
714
+ check: "stale-pusher-script",
715
+ level: stale.length ? "warn" : "ok",
716
+ detail: stale.length
717
+ ? `${stale.length} attached pusher(s) running pre-upgrade code — control commands (/clear, /compact) may be silently dropped. Run detach_agent + attach_agent for each, or have the agent relaunch.`
718
+ : "all attached pushers are running the current on-disk script",
719
+ fixable: false,
720
+ items: stale.length ? stale : undefined,
721
+ });
722
+ }
723
+ // 2. Orphan room memberships (member not in the registry).
724
+ {
725
+ const orphans = new Set();
726
+ for (const e of Object.values(rooms)) {
727
+ for (const m of e.members ?? [])
728
+ if (!known.has(m))
729
+ orphans.add(m);
730
+ }
731
+ if (fix && orphans.size) {
732
+ await updateJson(ROOMS_FILE, {}, (cur) => {
733
+ for (const e of Object.values(cur)) {
734
+ if (e.members?.length)
735
+ e.members = e.members.filter((m) => known.has(m));
736
+ }
737
+ return cur;
738
+ });
739
+ fixed.push(`dropped ${orphans.size} orphan membership(s): ${[...orphans].join(", ")}`);
740
+ }
741
+ findings.push({
742
+ check: "orphan-room-memberships",
743
+ level: orphans.size ? "warn" : "ok",
744
+ detail: orphans.size ? `${orphans.size} channel member(s) not in the registry` : "all channel members are registered",
745
+ fixable: true,
746
+ items: orphans.size ? [...orphans] : undefined,
747
+ });
748
+ }
749
+ // 3. Orphan inbox / cursor files (owner not registered).
750
+ {
751
+ const orphanInbox = [];
752
+ for (const fname of await listInboxFiles()) {
753
+ const id = fname.replace(/\.jsonl$/, "");
754
+ if (!known.has(id)) {
755
+ orphanInbox.push(id);
756
+ if (fix) {
757
+ await deleteFile(path.join(INBOX_DIR, fname));
758
+ fixed.push(`deleted orphan inbox ${fname}`);
759
+ }
760
+ }
761
+ }
762
+ const orphanCursor = [];
763
+ for (const fname of await listCursorFiles()) {
764
+ const id = fname.replace(/\.json$/, "");
765
+ if (!known.has(id)) {
766
+ orphanCursor.push(id);
767
+ if (fix) {
768
+ await deleteFile(path.join(CURSOR_DIR, fname));
769
+ fixed.push(`deleted orphan cursor ${fname}`);
770
+ }
771
+ }
772
+ }
773
+ const total = orphanInbox.length + orphanCursor.length;
774
+ findings.push({
775
+ check: "orphan-inboxes-cursors",
776
+ level: total ? "warn" : "ok",
777
+ detail: total
778
+ ? `${orphanInbox.length} inbox + ${orphanCursor.length} cursor file(s) for unregistered ids`
779
+ : "no orphan inbox/cursor files",
780
+ fixable: true,
781
+ items: total ? [...new Set([...orphanInbox, ...orphanCursor])] : undefined,
782
+ });
783
+ }
784
+ // Precompute parsed line counts for cursor + malformed checks.
785
+ const counts = new Map();
786
+ const countFor = async (file) => {
787
+ if (!counts.has(file))
788
+ counts.set(file, await scanJsonl(file));
789
+ return counts.get(file);
790
+ };
791
+ // 4. Cursor offsets past end-of-file (would return [] forever).
792
+ {
793
+ const broken = [];
794
+ for (const fname of await listCursorFiles()) {
795
+ const id = fname.replace(/\.json$/, "");
796
+ const cursorPath = path.join(CURSOR_DIR, fname);
797
+ const cursor = await readJson(cursorPath, {});
798
+ const overflow = [];
799
+ const inboxMax = (await countFor(inboxFile(id))).parsed;
800
+ if ((cursor.inboxOffset ?? 0) > inboxMax)
801
+ overflow.push(`inboxOffset ${cursor.inboxOffset}>${inboxMax}`);
802
+ const roomMax = (await countFor(ROOM_FILE)).parsed;
803
+ if ((cursor.roomOffset ?? 0) > roomMax)
804
+ overflow.push(`roomOffset ${cursor.roomOffset}>${roomMax}`);
805
+ const statusMax = (await countFor(STATUS_FILE)).parsed;
806
+ if ((cursor.statusOffset ?? 0) > statusMax)
807
+ overflow.push(`statusOffset ${cursor.statusOffset}>${statusMax}`);
808
+ for (const [chan, off] of Object.entries(cursor.roomOffsets ?? {})) {
809
+ const max = (await countFor(roomFile(chan))).parsed;
810
+ if (off > max)
811
+ overflow.push(`roomOffsets[${chan}] ${off}>${max}`);
812
+ }
813
+ if (overflow.length) {
814
+ broken.push(`${id}: ${overflow.join(", ")}`);
815
+ if (fix) {
816
+ await updateJson(cursorPath, {}, (c) => {
817
+ if ((c.inboxOffset ?? 0) > inboxMax)
818
+ c.inboxOffset = inboxMax;
819
+ if ((c.roomOffset ?? 0) > roomMax)
820
+ c.roomOffset = roomMax;
821
+ if ((c.statusOffset ?? 0) > statusMax)
822
+ c.statusOffset = statusMax;
823
+ if (c.roomOffsets) {
824
+ for (const chan of Object.keys(c.roomOffsets)) {
825
+ const max = counts.get(roomFile(chan))?.parsed ?? 0;
826
+ if (c.roomOffsets[chan] > max)
827
+ c.roomOffsets[chan] = max;
828
+ }
829
+ }
830
+ return c;
831
+ });
832
+ fixed.push(`clamped cursor offsets for ${id}`);
833
+ }
834
+ }
835
+ }
836
+ findings.push({
837
+ check: "cursor-past-eof",
838
+ level: broken.length ? "error" : "ok",
839
+ detail: broken.length ? `${broken.length} cursor(s) with an offset past EOF — delivery stalled` : "all cursor offsets are within bounds",
840
+ fixable: true,
841
+ items: broken.length ? broken : undefined,
842
+ });
843
+ }
844
+ // 5. Malformed JSONL lines (silently desync offset math between server + hooks).
845
+ {
846
+ const jsonlFiles = [
847
+ ROOM_FILE,
848
+ STATUS_FILE,
849
+ ...channels.filter((c) => c !== DEFAULT_ROOM).map((c) => roomFile(c)),
850
+ ...(await listInboxFiles()).map((f) => path.join(INBOX_DIR, f)),
851
+ ];
852
+ const bad = [];
853
+ for (const file of jsonlFiles) {
854
+ const c = await countFor(file);
855
+ if (c.malformed > 0) {
856
+ bad.push(`${path.basename(file)} (${c.malformed})`);
857
+ if (fix) {
858
+ await fsp.copyFile(file, file + ".bak");
859
+ await rewriteJsonl(file, () => true); // drops unparseable lines
860
+ fixed.push(`rewrote ${path.basename(file)} dropping ${c.malformed} malformed line(s) (backup: ${path.basename(file)}.bak)`);
861
+ }
862
+ }
863
+ }
864
+ findings.push({
865
+ check: "malformed-jsonl",
866
+ level: bad.length ? "warn" : "ok",
867
+ detail: bad.length ? `${bad.length} file(s) contain unparseable lines` : "no malformed JSONL lines",
868
+ fixable: true,
869
+ items: bad.length ? bad : undefined,
870
+ });
871
+ }
872
+ // 6. Stale agents (registered, no live transport, heartbeat past EVICT_MS). Report only.
873
+ {
874
+ // Compute liveness WITHOUT deleting dead markers — loadLiveTransports
875
+ // prunes as a side effect, which would make this read-only check mutate
876
+ // state (and pre-empt the orphan-marker fix in check 1).
877
+ const live = new Set();
878
+ for (const fname of await listTransportFiles()) {
879
+ const marker = await readJson(path.join(TRANSPORT_DIR, fname), null);
880
+ if (marker && isMarkerLive(marker, reg, now))
881
+ live.add(marker.agentId);
882
+ }
883
+ const stale = [];
884
+ for (const [id, a] of Object.entries(reg)) {
885
+ if (live.has(id))
886
+ continue;
887
+ if (now - a.lastHeartbeat > EVICT_MS)
888
+ stale.push(`${id} (${Math.floor((now - a.lastHeartbeat) / 3600000)}h)`);
889
+ }
890
+ findings.push({
891
+ check: "stale-agents",
892
+ level: stale.length ? "warn" : "ok",
893
+ detail: stale.length ? `${stale.length} agent(s) past the eviction window — next list_agents will drop them` : "no stale agents",
894
+ fixable: false,
895
+ items: stale.length ? stale : undefined,
896
+ });
897
+ }
898
+ // 7. Oversized JSONL files. Report only (suggest prune).
899
+ {
900
+ const big = [];
901
+ const candidates = [
902
+ ROOM_FILE,
903
+ STATUS_FILE,
904
+ ...channels.filter((c) => c !== DEFAULT_ROOM).map((c) => roomFile(c)),
905
+ ...(await listInboxFiles()).map((f) => path.join(INBOX_DIR, f)),
906
+ ];
907
+ for (const file of candidates) {
908
+ const sz = await fileSize(file);
909
+ if (sz > maxBytes)
910
+ big.push(`${path.basename(file)} (${(sz / 1024 / 1024).toFixed(1)}MB)`);
911
+ }
912
+ findings.push({
913
+ check: "oversized-files",
914
+ level: big.length ? "warn" : "ok",
915
+ detail: big.length ? `${big.length} file(s) over ${(maxBytes / 1024 / 1024).toFixed(0)}MB — consider prune` : "no oversized files",
916
+ fixable: false,
917
+ items: big.length ? big : undefined,
918
+ });
919
+ }
920
+ // 8. Stale lock dirs from crashed writers.
921
+ {
922
+ const locks = await scanStaleLocks(60_000, now);
923
+ for (const l of locks) {
924
+ if (fix) {
925
+ try {
926
+ await fsp.rm(l.path, { recursive: true, force: true });
927
+ fixed.push(`removed stale lock ${path.basename(l.path)}`);
928
+ }
929
+ catch {
930
+ // ignore
931
+ }
932
+ }
933
+ }
934
+ findings.push({
935
+ check: "stale-locks",
936
+ level: locks.length ? "warn" : "ok",
937
+ detail: locks.length ? `${locks.length} lock dir(s) older than 60s — likely from a crashed writer` : "no stale locks",
938
+ fixable: true,
939
+ items: locks.length ? locks.map((l) => `${path.basename(l.path)} (${Math.floor(l.ageMs / 1000)}s)`) : undefined,
940
+ });
941
+ }
942
+ // 9. Channel/registry consistency: rooms/<chan>.jsonl files without a registry entry.
943
+ {
944
+ const orphanFiles = [];
945
+ if (existsSync(ROOMS_DIR)) {
946
+ let names = [];
947
+ try {
948
+ names = await fsp.readdir(ROOMS_DIR);
949
+ }
950
+ catch {
951
+ // ignore
952
+ }
953
+ for (const name of names) {
954
+ if (!name.endsWith(".jsonl"))
955
+ continue;
956
+ const chan = name.replace(/\.jsonl$/, "");
957
+ if (!rooms[chan]) {
958
+ orphanFiles.push(name);
959
+ if (fix) {
960
+ await ensureRoom(chan, "doctor");
961
+ fixed.push(`registered channel '${chan}' (had a JSONL file but no registry entry)`);
962
+ }
963
+ }
964
+ }
965
+ }
966
+ findings.push({
967
+ check: "channel-registry-consistency",
968
+ level: orphanFiles.length ? "warn" : "ok",
969
+ detail: orphanFiles.length ? `${orphanFiles.length} channel file(s) with no registry entry` : "channel files and registry agree",
970
+ fixable: true,
971
+ items: orphanFiles.length ? orphanFiles : undefined,
972
+ });
973
+ }
974
+ // 10. Environment sanity. Report only.
975
+ {
976
+ const tmuxProbe = spawnSync("tmux", ["-V"]);
977
+ const tmuxOk = tmuxProbe.status === 0;
978
+ findings.push({
979
+ check: "environment",
980
+ level: tmuxOk ? "ok" : "warn",
981
+ detail: tmuxOk
982
+ ? `root=${ROOT}; node=${process.execPath}; tmux=${(tmuxProbe.stdout ?? "").toString().trim() || "present"}`
983
+ : `root=${ROOT}; node=${process.execPath}; tmux NOT on PATH — the tmux-push transport will not work`,
984
+ fixable: false,
985
+ items: [`root=${ROOT}`, `execPath=${process.execPath}`, `inTmux=${!!process.env.TMUX_PANE}`],
986
+ });
987
+ }
988
+ const summary = {
989
+ ok: findings.filter((f) => f.level === "ok").length,
990
+ warn: findings.filter((f) => f.level === "warn").length,
991
+ error: findings.filter((f) => f.level === "error").length,
992
+ };
993
+ return {
994
+ ok: true,
995
+ healthy: summary.warn === 0 && summary.error === 0,
996
+ fixApplied: fix,
997
+ root: ROOT,
998
+ findings,
999
+ fixed: fix ? fixed : undefined,
1000
+ summary,
1001
+ };
1002
+ }
1003
+ //# sourceMappingURL=transport.js.map