agent-coord-mcp 0.26.21 → 0.26.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/dist/capabilities.js +270 -2
  2. package/dist/capabilities.js.map +1 -1
  3. package/dist/closing-line.js +83 -0
  4. package/dist/closing-line.js.map +1 -0
  5. package/dist/commit-cite.js +55 -0
  6. package/dist/commit-cite.js.map +1 -0
  7. package/dist/gated-head.js +67 -20
  8. package/dist/gated-head.js.map +1 -1
  9. package/dist/server-spread.js +195 -0
  10. package/dist/server-spread.js.map +1 -0
  11. package/dist/server.js +2 -2
  12. package/dist/server.js.map +1 -1
  13. package/dist/store.js +32 -0
  14. package/dist/store.js.map +1 -1
  15. package/dist/tools/away.js +67 -7
  16. package/dist/tools/away.js.map +1 -1
  17. package/dist/tools/board-ref.js +44 -4
  18. package/dist/tools/board-ref.js.map +1 -1
  19. package/dist/tools/event-kinds.js +5 -1
  20. package/dist/tools/event-kinds.js.map +1 -1
  21. package/dist/tools/events.js +40 -4
  22. package/dist/tools/events.js.map +1 -1
  23. package/dist/tools/herdr-delivery.js +99 -0
  24. package/dist/tools/herdr-delivery.js.map +1 -0
  25. package/dist/tools/messaging.js +72 -6
  26. package/dist/tools/messaging.js.map +1 -1
  27. package/dist/tools/record-events.js +85 -5
  28. package/dist/tools/record-events.js.map +1 -1
  29. package/dist/tools/records.js +310 -44
  30. package/dist/tools/records.js.map +1 -1
  31. package/dist/tools/registry.js +67 -3
  32. package/dist/tools/registry.js.map +1 -1
  33. package/dist/tools/seat-build.js +182 -0
  34. package/dist/tools/seat-build.js.map +1 -0
  35. package/dist/tools/shared.js.map +1 -1
  36. package/dist/tools/stall.js +1095 -18
  37. package/dist/tools/stall.js.map +1 -1
  38. package/dist/tools/transport.js +71 -3
  39. package/dist/tools/transport.js.map +1 -1
  40. package/dist/tools/worktrees.js +14 -0
  41. package/dist/tools/worktrees.js.map +1 -1
  42. package/dist/transports/herdr.js +297 -0
  43. package/dist/transports/herdr.js.map +1 -0
  44. package/dist/transports/index.js +10 -4
  45. package/dist/transports/index.js.map +1 -1
  46. package/package.json +1 -1
  47. package/scripts/coord-attention-clock.mjs +2 -0
  48. package/scripts/coord-stall-clock.mjs +52 -11
  49. package/src/capabilities.ts +284 -2
  50. package/src/closing-line.ts +85 -0
  51. package/src/commit-cite.ts +58 -0
  52. package/src/gated-head.ts +128 -26
  53. package/src/server-spread.ts +233 -0
  54. package/src/server.ts +2 -2
  55. package/src/store.ts +32 -0
  56. package/src/tools/away.ts +82 -9
  57. package/src/tools/board-ref.ts +70 -3
  58. package/src/tools/event-kinds.ts +19 -2
  59. package/src/tools/events.ts +42 -4
  60. package/src/tools/herdr-delivery.ts +87 -0
  61. package/src/tools/messaging.ts +71 -6
  62. package/src/tools/record-events.ts +78 -5
  63. package/src/tools/records.ts +316 -44
  64. package/src/tools/registry.ts +68 -4
  65. package/src/tools/seat-build.ts +201 -0
  66. package/src/tools/shared.ts +22 -0
  67. package/src/tools/stall.ts +1266 -23
  68. package/src/tools/transport.ts +69 -2
  69. package/src/tools/worktrees.ts +13 -0
  70. package/src/transports/herdr.ts +311 -0
  71. package/src/transports/index.ts +10 -4
@@ -2,6 +2,8 @@ import { loadLiveTransports, isMarkerLive, isPidAlive } from "./registry.js";
2
2
  import {
3
3
  TMUX_PUSH,
4
4
  registerTmuxHost,
5
+ activeTransport,
6
+ HERDR,
5
7
  type TmuxHost,
6
8
  isLocallyProbeable,
7
9
  isTmuxKind,
@@ -33,6 +35,7 @@ import { promises as fsp } from "node:fs";
33
35
  import { spawn, spawnSync } from "node:child_process";
34
36
  import { fileURLToPath } from "node:url";
35
37
  import { z } from "zod";
38
+ import { seatBuildOf, installedFrom, psReader } from "./seat-build.js";
36
39
  import path from "node:path";
37
40
  import {
38
41
  AGENTS_FILE,
@@ -157,12 +160,17 @@ export async function pingTool(args: { from: string; to: string; echo?: boolean
157
160
 
158
161
  let echoSent = false;
159
162
  if (args.echo && alive) {
160
- await sendMessageTool({
163
+ // ⟨q-138f4b78⟩ — the echo is an agent→agent DM, so past the typed-record
164
+ // cutover it MUST carry a record or the send is refused; and `echoSent`
165
+ // reports what the send SAID, never that a call was made — measured on the
166
+ // cutover morning: this reported true while nothing was written.
167
+ const sent = await sendMessageTool({
161
168
  from: args.from,
162
169
  to: args.to,
163
170
  text: `PING: echo requested by ${args.from} — DM back if responsive.`,
171
+ record: { type: "fyi", payload: { summary: `PING echo requested by ${args.from}` } },
164
172
  });
165
- echoSent = true;
173
+ echoSent = sent.ok === true;
166
174
  }
167
175
 
168
176
  return {
@@ -474,6 +482,20 @@ export async function sendCommandTool(args: {
474
482
  // DM: target must itself be tmux-attached.
475
483
  if (args.to) {
476
484
  const marker = liveTmux.get(args.to);
485
+ // Phase 5.4 Task 4 — a herdr seat takes the control IN-PROCESS: no inbox message, no
486
+ // pusher receipt; the transport types it, verifies it left the input, and answers.
487
+ const herdrMarker = marker ? undefined : (await loadLiveTransports()).get(args.to);
488
+ const activeT = activeTransport();
489
+ if (herdrMarker?.transport === HERDR) {
490
+ if (activeT?.kind !== HERDR) {
491
+ return { ok: false, error: `'${args.to}' is attached through herdr but this server's active transport is ${activeT?.kind ?? "none"} — a mixed fleet; the server configured for herdr must send this control` };
492
+ }
493
+ const r = await activeT.sendControl(herdrMarker, cmd as "clear" | "compact" | "reload-skills");
494
+ const reminderMs = cmd === "clear" ? args.reminderMs ?? 3000 : 0;
495
+ if (r.ok && reminderMs > 0) scheduleReminders(args.from, [args.to], reminderMs, args.reminderText);
496
+ const extra = r as { enters?: number; note?: string };
497
+ return { ok: r.ok, command: text, delivered: r.ok ? [args.to] : [], transport: HERDR, delivery: r.ok ? "confirmed" : "refused", ...(r.error ? { error: r.error } : {}), ...(extra.enters !== undefined ? { enters: extra.enters } : {}), ...(extra.note ? { note: extra.note } : {}) };
498
+ }
477
499
  if (!marker) {
478
500
  return {
479
501
  ok: false,
@@ -642,6 +664,32 @@ export async function attachAgentTool(args: {
642
664
  debounceMs?: number;
643
665
  }) {
644
666
  // Resolve target: explicit arg > MCP server's own TMUX_PANE env.
667
+ // Phase 5.4 Task 4 — a fleet configured for herdr attaches through the transport: no
668
+ // pusher is spawned, the marker carries pid 0 and a herdr pane id, and every refusal
669
+ // names herdr (an absent binary is never a silent fall-through to tmux).
670
+ const activeT = activeTransport();
671
+ if (activeT?.kind === HERDR) {
672
+ const existing = await readJson<TransportMarker | null>(transportFile(args.agentId), null);
673
+ if (existing) await deleteFile(transportFile(args.agentId));
674
+ let marker: TransportMarker;
675
+ try {
676
+ marker = await activeT.attach({ agentId: args.agentId, target: args.tmuxTarget, includeRoom: args.includeRoom, allowlist: args.allowlist, debounceMs: args.debounceMs });
677
+ } catch (e) {
678
+ return { ok: false, error: (e as Error).message };
679
+ }
680
+ marker = { ...marker, serverBuildMtime: SERVER_BUILD_MTIME };
681
+ await fsp.mkdir(path.dirname(transportFile(args.agentId)), { recursive: true });
682
+ await updateJson<TransportMarker>(transportFile(args.agentId), marker, () => marker);
683
+ return {
684
+ ok: true,
685
+ agentId: args.agentId,
686
+ transport: HERDR,
687
+ target: marker.target,
688
+ pid: 0,
689
+ rooms: marker.rooms,
690
+ note: "herdr socket transport: no pusher process — delivery is made in-process by this server through herdr's socket API; liveness is herdr's own pane status",
691
+ };
692
+ }
645
693
  const target = args.tmuxTarget ?? process.env.TMUX_PANE;
646
694
  if (!target) {
647
695
  return {
@@ -802,6 +850,12 @@ export async function detachAgentTool(args: { agentId: string }) {
802
850
  const marker = await readJson<TransportMarker | null>(transportFile(args.agentId), null);
803
851
  let killed = false;
804
852
  let unverified = false;
853
+ if (marker?.transport === HERDR) {
854
+ // No pusher to kill: the socket transport has no process of its own. The marker is
855
+ // the whole attachment, and removing it is the detach.
856
+ await deleteFile(transportFile(args.agentId));
857
+ return { ok: true, agentId: args.agentId, killed: false, hadMarker: true, transport: HERDR, note: "herdr socket transport: no pusher process to stop; marker removed" };
858
+ }
805
859
  if (marker && isPidAlive(marker.pid)) {
806
860
  // ALIVE IS NOT ENOUGH — VERIFY IT IS A PUSHER BEFORE SIGNALLING IT.
807
861
  //
@@ -899,9 +953,22 @@ export async function statusTool(args: { agentId: string }) {
899
953
  // is the case every other instrument here reports as if the fleet were one
900
954
  // thing.
901
955
  const capabilities = await capabilitiesTool();
956
+ // ⟨q-8a3f1c05⟩ — THIS SEAT'S BUILD STATE, both halves: the pusher from its marker's
957
+ // pid via ps (keyed by --agent), the server from THIS process — status is called
958
+ // by the seat about itself, which is the one case the server half is knowable.
959
+ const id = resolveServerIdentity();
960
+ const installed = installedFrom(id.path);
961
+ const build = seatBuildOf({
962
+ agentId: args.agentId,
963
+ marker: transport,
964
+ installed,
965
+ ps: psReader,
966
+ server: { pid: process.pid, startedAt: Date.now() - Math.round(process.uptime() * 1000), buildMtime: installed.buildMtime },
967
+ });
902
968
 
903
969
  return {
904
970
  agentId: args.agentId,
971
+ build,
905
972
  registered: !!entry,
906
973
  entry,
907
974
  attached: !!transport,
@@ -215,12 +215,25 @@ async function create(a: {
215
215
  } catch (e) {
216
216
  return { ok: false as const, error: `git worktree add failed: ${String((e as Error).message).split("\n")[0]}` };
217
217
  }
218
+ // ⟨q-7b2f6c04⟩ — THE EMPTY PUSH AT CLAIM. The branch goes to origin at the
219
+ // base's tip, so the lane has a ref on the remote from its first minute: the
220
+ // VCS axis sees it, and the stall clock scores it on the CLAIM axis (a ref
221
+ // sitting on the base has no commits of its own to date). Best-effort and
222
+ // REPORTED, never fatal — a tree cut offline is still a tree.
223
+ let pushed: { ok: true; ref: string } | { ok: false; why: string };
224
+ try {
225
+ execFileSync("git", ["push", "-q", "-u", "origin", `${branch}:refs/heads/${branch}`], { cwd: repo, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 20_000 });
226
+ pushed = { ok: true, ref: `origin/${branch}` };
227
+ } catch (e) {
228
+ pushed = { ok: false, why: `the empty claim-time push did not land: ${String((e as Error).message).split("\n").find((l) => l.trim()) ?? "unknown"} — the lane is observable on the claim axis from the board's history only` };
229
+ }
218
230
  return {
219
231
  ok: true as const,
220
232
  path: target,
221
233
  sha,
222
234
  branch,
223
235
  created: true,
236
+ pushed,
224
237
  base: ref,
225
238
  // Cut from `sha`, which IS origin/<base> — true by construction here, and
226
239
  // stated so callers need not special-case "created" to know it.
@@ -0,0 +1,311 @@
1
+ /**
2
+ * THE HERDR TRANSPORT — the second implementation of the seam (Phase 5.4 Task 4).
3
+ *
4
+ * herdr is a RUST BINARY (brew / herdr.dev / GitHub releases), NOT an npm package:
5
+ * `npm view herdr` answers 0.0.0 "Reserved package name" (spike 1.1). Nothing here is
6
+ * imported; every call is `herdr <subcommand>` over the socket API on this host, through
7
+ * one injectable runner so the transport can be exercised without a herdr server and
8
+ * measured against one when it is there.
9
+ *
10
+ * WHAT IS DIFFERENT FROM TMUX, and why each difference is a stated behaviour rather
11
+ * than a quiet default:
12
+ * · NO PUSHER PROCESS. Delivery is a socket call made by the server itself; a marker
13
+ * carries pid 0. Liveness is therefore never a pid heuristic — `probe` asks herdr
14
+ * for the pane and its OWN `agent_status` (spike 1.4: live / wedged / killed are
15
+ * three distinguishable answers there, which they are not on tmux).
16
+ * · ERRORS ARE JSON, ON EITHER STREAM. `herdr pane get w999:p1` prints
17
+ * {"error":{"code":"pane_not_found",…}} — measured on stdout with exit 0 in one call
18
+ * and on stderr in another (a pane closed moments before read as "could not describe"
19
+ * until the runner parsed stderr too). The runner parses whichever stream carries a
20
+ * JSON body; the exit code alone would call failures successes.
21
+ * · KEY NAMES ARE NOT PORTABLE. `ctrl+u` is accepted, `C-u` / `ctrl-u` are rejected
22
+ * with {"error":{"code":"invalid_key"}} (spike, and measured again here). The seam
23
+ * takes INTENTS; the one place a key name is spelled is `herdrKeyName`, which
24
+ * REFUSES a tmux-vocabulary name rather than translating it by guess.
25
+ * · THE ENTER RACE IS REAL. `send-text` then `send-keys enter` did not submit once in
26
+ * the spike; the line sat in Claude's input box until a second enter. `push` and
27
+ * `sendControl` VERIFY by reading the pane back and retry the enter once, and report
28
+ * how many enters it took — measured per delivery, never assumed away.
29
+ * · THE SLASH IS EATEN DOWNSTREAM OF ANY TRANSPORT (spike 1.3, ⟨q-f14692ca⟩ struck):
30
+ * Claude Code interprets a leading `/` however the characters arrive. This transport
31
+ * delivers bytes verbatim and makes no claim about what the reader does with them.
32
+ * · ABSENT BINARY / STOPPED SERVER → an explicit refusal that NAMES herdr. Never a
33
+ * silent fall-through to tmux: the config layer already refuses unknown kinds for the
34
+ * same reason (identical evidence for a typo and a default).
35
+ */
36
+ import { spawnSync } from "node:child_process";
37
+ import type { ControlCommand, Liveness, Transport, TransportKind, TransportMarker } from "./types.js";
38
+ import { HERDR, targetOf } from "./types.js";
39
+
40
+ export type HerdrError = { code: string; message: string };
41
+ export type HerdrResult = {
42
+ ok: boolean;
43
+ status: number | null;
44
+ stdout: string;
45
+ stderr: string;
46
+ /** Parsed JSON body when herdr printed one. */
47
+ json?: unknown;
48
+ /** herdr's own error object, or a synthetic one for a missing binary. */
49
+ error?: HerdrError;
50
+ /** The binary itself is not on PATH. */
51
+ absent?: boolean;
52
+ };
53
+ export type HerdrRunner = (args: string[]) => HerdrResult;
54
+
55
+ export const HERDR_BINARY = "herdr";
56
+ export const HERDR_ABSENT_MESSAGE =
57
+ `herdr binary not found on PATH — herdr is a Rust binary (brew install herdr, or https://herdr.dev), ` +
58
+ `NOT an npm package (npm's "herdr" is a reserved 0.0.0 name). Install it, or use the tmux-push transport.`;
59
+
60
+ /**
61
+ * Interpret a herdr reply — PURE, so the one rule it holds (a JSON error body on either
62
+ * stream is a refusal, whatever the exit code) is testable without a herdr on the host.
63
+ */
64
+ export function interpretHerdrReply(r: { status: number | null; stdout?: string | null; stderr?: string | null }): HerdrResult {
65
+ const stdout = r.stdout ?? "";
66
+ const stderr = r.stderr ?? "";
67
+ let json: unknown;
68
+ for (const stream of [stdout, stderr]) {
69
+ const trimmed = stream.trim();
70
+ if (!trimmed.startsWith("{")) continue;
71
+ try { json = JSON.parse(trimmed); break; } catch { /* not a JSON body */ }
72
+ }
73
+ const err = (json as { error?: HerdrError } | undefined)?.error;
74
+ if (err && typeof err.code === "string") return { ok: false, status: r.status, stdout, stderr, json, error: err };
75
+ if (r.status !== 0) return { ok: false, status: r.status, stdout, stderr, json, error: { code: "exit", message: (stderr || stdout).trim() || `herdr exited ${r.status}` } };
76
+ return { ok: true, status: r.status, stdout, stderr, json };
77
+ }
78
+
79
+ /** Run `herdr <args>` and interpret the reply. */
80
+ export function defaultHerdrRunner(args: string[]): HerdrResult {
81
+ const r = spawnSync(HERDR_BINARY, args, { encoding: "utf8" });
82
+ if (r.error && (r.error as NodeJS.ErrnoException).code === "ENOENT") {
83
+ return { ok: false, status: null, stdout: "", stderr: "", absent: true, error: { code: "binary_absent", message: HERDR_ABSENT_MESSAGE } };
84
+ }
85
+ return interpretHerdrReply({ status: r.status, stdout: r.stdout, stderr: r.stderr });
86
+ }
87
+
88
+ /**
89
+ * THE KEY VOCABULARY, in one place. Intents on the left, herdr's names on the right.
90
+ * A tmux-vocabulary name (`C-u`, `ctrl-u`, `M-x`) is REFUSED, never translated by guess:
91
+ * herdr would reject it as invalid_key, and a transport that "helpfully" rewrote it could
92
+ * just as easily rewrite it wrong and type garbage into a pane.
93
+ */
94
+ export const HERDR_KEYS: Readonly<Record<string, string>> = Object.freeze({
95
+ enter: "enter",
96
+ escape: "esc",
97
+ "clear-line": "ctrl+u",
98
+ });
99
+ export function herdrKeyName(intentOrName: string): { ok: true; key: string } | { ok: false; error: string } {
100
+ const s = String(intentOrName ?? "").trim();
101
+ if (/^(?:C|M|S)-/i.test(s) || /^(?:ctrl|alt|meta|shift)-/i.test(s)) {
102
+ return { ok: false, error: `key '${s}' is tmux vocabulary and herdr rejects it as invalid_key — the herdr form is '${s.replace(/^(?:C|ctrl)-/i, "ctrl+").replace(/^(?:M|alt|meta)-/i, "alt+")}'; refused rather than guessed` };
103
+ }
104
+ if (HERDR_KEYS[s]) return { ok: true, key: HERDR_KEYS[s] };
105
+ if (/^[a-z0-9]+(?:\+[a-z0-9]+)*$/.test(s)) return { ok: true, key: s };
106
+ return { ok: false, error: `key '${s}' is not a herdr key name (letters, digits and '+', e.g. ctrl+u) and not a known intent (${Object.keys(HERDR_KEYS).join(", ")})` };
107
+ }
108
+
109
+ type PaneInfo = { pane_id?: string; agent_status?: string; agent?: string; workspace_id?: string };
110
+ type ProcessInfo = { foreground_processes?: { argv?: string[]; pid?: number; name?: string }[]; shell_pid?: number };
111
+
112
+ function paneOf(r: HerdrResult): PaneInfo | undefined {
113
+ const j = r.json as { result?: { pane?: PaneInfo; root_pane?: PaneInfo } } | undefined;
114
+ return j?.result?.pane ?? j?.result?.root_pane;
115
+ }
116
+ function processInfoOf(r: HerdrResult): ProcessInfo | undefined {
117
+ return (r.json as { result?: { process_info?: ProcessInfo } } | undefined)?.result?.process_info;
118
+ }
119
+ const LIVE_STATUSES = new Set(["idle", "working", "blocked", "done"]);
120
+
121
+ export type HerdrTransportOptions = {
122
+ run?: HerdrRunner;
123
+ /** Milliseconds to wait before reading a pane back after typing. */
124
+ settleMs?: number;
125
+ /** Sleep, injectable so tests do not wait. */
126
+ sleep?: (ms: number) => void;
127
+ /** Lines of pane to read back when verifying a delivery. */
128
+ readLines?: number;
129
+ };
130
+
131
+ export class HerdrTransport implements Transport {
132
+ readonly kind: TransportKind = HERDR;
133
+ #run: HerdrRunner;
134
+ #settleMs: number;
135
+ #sleep: (ms: number) => void;
136
+ #readLines: number;
137
+
138
+ constructor(opts: HerdrTransportOptions = {}) {
139
+ this.#run = opts.run ?? defaultHerdrRunner;
140
+ // MEASURED on a shell pane in a task-owned workspace: after a single enter the output had
141
+ // rendered by 400 ms and not by 150 ms — below that, render lag reads as an unsubmitted
142
+ // line and the retry fires an empty enter (harmless, but counted). The genuine lost enter
143
+ // the spike measured is Claude's input box; the retry exists for that, bounded to one.
144
+ this.#settleMs = opts.settleMs ?? 400;
145
+ this.#sleep = opts.sleep ?? ((ms) => { const end = Date.now() + ms; while (Date.now() < end) { /* spin: tiny and rare */ } });
146
+ this.#readLines = opts.readLines ?? 12;
147
+ }
148
+
149
+ /** Is herdr on this host AND is its server running? Both, or the reason. */
150
+ availability(): { available: boolean; reason: string } {
151
+ const r = this.#run(["status"]);
152
+ if (r.absent) return { available: false, reason: HERDR_ABSENT_MESSAGE };
153
+ if (!r.ok) return { available: false, reason: `herdr status failed: ${r.error?.message ?? r.stderr}` };
154
+ const running = /server:[\s\S]*status:\s*running/.test(r.stdout);
155
+ return running
156
+ ? { available: true, reason: `herdr server running (${(r.stdout.match(/version:\s*(\S+)/) ?? [])[1] ?? "version unread"})` }
157
+ : { available: false, reason: `herdr binary present but its server is not running (herdr status: ${r.stdout.trim().split("\n").slice(-2).join(" ")}) — start herdr, or use the tmux-push transport` };
158
+ }
159
+ available(): boolean {
160
+ return this.availability().available;
161
+ }
162
+
163
+ /**
164
+ * Attach = verify the pane and return a marker. No process is spawned: the marker's pid
165
+ * is 0 and its `target` is the herdr pane id. Persisting the marker is the tool's job,
166
+ * exactly as for tmux.
167
+ */
168
+ async attach(args: { agentId: string; target?: string; includeRoom?: boolean; allowlist?: string[]; debounceMs?: number }): Promise<TransportMarker> {
169
+ const avail = this.availability();
170
+ if (!avail.available) throw new Error(`herdr transport cannot attach '${args.agentId}': ${avail.reason}`);
171
+ let target = args.target ?? process.env.HERDR_PANE_ID;
172
+ if (!target) {
173
+ const cur = this.#run(["pane", "current"]);
174
+ target = paneOf(cur)?.pane_id;
175
+ }
176
+ if (!target) {
177
+ throw new Error("herdr target not provided and this process is not inside a herdr pane (no HERDR_PANE_ID, `herdr pane current` answered nothing). Pass target explicitly (e.g. 'w2:p1').");
178
+ }
179
+ const got = this.#run(["pane", "get", target]);
180
+ if (!got.ok) throw new Error(`herdr pane '${target}' not found: ${got.error?.message ?? got.stderr}`);
181
+ return {
182
+ agentId: args.agentId,
183
+ transport: HERDR,
184
+ pid: 0,
185
+ target,
186
+ tmuxTarget: target,
187
+ since: Date.now(),
188
+ rooms: args.includeRoom !== false,
189
+ };
190
+ }
191
+
192
+ /** Does the pane exist, per herdr, through THIS transport's runner? null = could not ask. */
193
+ paneExists(target: string): boolean | null {
194
+ return herdrPaneExists(target, this.#run);
195
+ }
196
+
197
+ /** Nothing to kill: there is no pusher. The tool deletes the marker. */
198
+ async detach(_agentId: string): Promise<void> {
199
+ return;
200
+ }
201
+
202
+ /**
203
+ * Type `text` into the pane and press enter; VERIFY by reading the pane back, and if
204
+ * the line is still sitting unsubmitted (the spike's race), press enter once more.
205
+ * Reports the enters it took so the race is measured on every delivery.
206
+ */
207
+ async push(marker: TransportMarker, text: string): Promise<{ delivered: boolean; error?: string; enters?: number; verified?: boolean }> {
208
+ const avail = this.availability();
209
+ if (!avail.available) return { delivered: false, error: avail.reason };
210
+ const target = targetOf(marker);
211
+ if (!target) return { delivered: false, error: "no target recorded on the marker" };
212
+ const typed = this.#run(["pane", "send-text", target, text]);
213
+ if (!typed.ok) return { delivered: false, error: `send-text to ${target} refused: ${typed.error?.message ?? typed.stderr}` };
214
+ const enterKey = herdrKeyName("enter");
215
+ if (!enterKey.ok) return { delivered: false, error: enterKey.error };
216
+ let enters = 0;
217
+ for (let attempt = 0; attempt < 2; attempt++) {
218
+ const pressed = this.#run(["pane", "send-keys", target, enterKey.key]);
219
+ if (!pressed.ok) return { delivered: false, error: `send-keys enter to ${target} refused: ${pressed.error?.message ?? pressed.stderr}`, enters };
220
+ enters++;
221
+ this.#sleep(this.#settleMs);
222
+ const pending = this.#stillPending(target, text);
223
+ if (pending === false) return { delivered: true, enters, verified: true };
224
+ if (pending === null) return { delivered: true, enters, verified: false };
225
+ }
226
+ return { delivered: false, enters, verified: true, error: `text still sitting unsubmitted in ${target}'s input after ${enters} enters` };
227
+ }
228
+
229
+ /**
230
+ * Read the pane back: is the typed text still the LAST non-empty line (unsubmitted)?
231
+ * true = pending · false = submitted · null = could not read (unverified, not failed).
232
+ */
233
+ #stillPending(target: string, text: string): boolean | null {
234
+ const read = this.#run(["pane", "read", target, "--source", "visible", "--lines", String(this.#readLines), "--format", "text"]);
235
+ if (!read.ok) return null;
236
+ const lines = read.stdout.split("\n").map((l) => l.replace(/\s+$/, "")).filter((l) => l.trim().length > 0);
237
+ const last = lines.at(-1) ?? "";
238
+ const firstLine = text.split("\n")[0];
239
+ return last.endsWith(firstLine) && !/^[⏺✔✖]/.test(last);
240
+ }
241
+
242
+ /**
243
+ * THREE ANSWERS FROM HERDR'S OWN STATUS, never a pid heuristic:
244
+ * · not a herdr marker / no target / herdr unavailable → unknown, naming which
245
+ * · pane_not_found → dead
246
+ * · agent_status idle | working | blocked | done → live (blocked IS live: it waits on a person)
247
+ * · agent_status unknown, a foreground process present → unknown, naming the process (the wedged shape)
248
+ * · agent_status unknown, nothing in the foreground → unknown (a shell pane nobody is in)
249
+ */
250
+ async probe(marker: TransportMarker): Promise<Liveness> {
251
+ if (marker.transport !== HERDR) return { state: "unknown", reason: `transport "${marker.transport}" is not herdr` };
252
+ const target = targetOf(marker);
253
+ if (!target) return { state: "unknown", reason: "no target recorded on the marker" };
254
+ const avail = this.availability();
255
+ if (!avail.available) return { state: "unknown", reason: avail.reason };
256
+ const got = this.#run(["pane", "get", target]);
257
+ if (!got.ok) {
258
+ if (got.error?.code === "pane_not_found") return { state: "dead", reason: `herdr reports pane ${target} not found (${got.error.message})` };
259
+ return { state: "unknown", reason: `herdr could not describe pane ${target}: ${got.error?.message ?? got.stderr}` };
260
+ }
261
+ const status = String(paneOf(got)?.agent_status ?? "unknown");
262
+ if (LIVE_STATUSES.has(status)) return { state: "live" };
263
+ const proc = this.#run(["pane", "process-info", "--pane", target]);
264
+ const fg = processInfoOf(proc)?.foreground_processes ?? [];
265
+ if (fg.length) {
266
+ const p = fg[0];
267
+ return { state: "unknown", reason: `herdr reports agent_status "${status}" for pane ${target}; foreground process ${JSON.stringify(p.argv ?? [p.name])} (pid ${p.pid}) — present but not a recognised agent` };
268
+ }
269
+ return { state: "unknown", reason: `herdr reports agent_status "${status}" for pane ${target} and no foreground process` };
270
+ }
271
+
272
+ /**
273
+ * A control command is typed as `/<cmd>` and verified to have LEFT the input, with the
274
+ * same enter-race handling as push. All three commands ride the path the spike measured
275
+ * for /clear; compact and reload-skills are the same delivery path (spike: inferred,
276
+ * not measured) and are said so in the result.
277
+ */
278
+ async sendControl(marker: TransportMarker, cmd: ControlCommand): Promise<{ ok: boolean; error?: string; enters?: number; note?: string }> {
279
+ const r = await this.push(marker, `/${cmd}`);
280
+ if (!r.delivered) return { ok: false, error: r.error ?? "control not delivered", enters: r.enters };
281
+ return {
282
+ ok: true,
283
+ enters: r.enters,
284
+ note: cmd === "clear" ? "measured end to end in the spike" : `same delivery path as /clear; ${cmd} itself was inferred, not measured, by the spike`,
285
+ };
286
+ }
287
+
288
+ /**
289
+ * No pusher to kill. A herdr marker whose pane is gone is reaped (the caller deletes
290
+ * the marker); an unknown answer is unprobeable; a live pane is left alone.
291
+ */
292
+ async reapWedged(markers: TransportMarker[]): Promise<{ reaped: string[]; unprobeable: string[] }> {
293
+ const reaped: string[] = [];
294
+ const unprobeable: string[] = [];
295
+ for (const marker of markers) {
296
+ const live = await this.probe(marker);
297
+ if (live.state === "dead") reaped.push(marker.agentId);
298
+ else if (live.state === "unknown") unprobeable.push(marker.agentId);
299
+ }
300
+ return { reaped, unprobeable };
301
+ }
302
+ }
303
+
304
+ /** Synchronous pane-existence read for the registry's liveness path (no pid to check). */
305
+ export function herdrPaneExists(target: string, run: HerdrRunner = defaultHerdrRunner): boolean | null {
306
+ const r = run(["pane", "get", target]);
307
+ if (r.absent) return null;
308
+ if (r.ok) return true;
309
+ if (r.error?.code === "pane_not_found") return false;
310
+ return null;
311
+ }
@@ -6,13 +6,15 @@
6
6
  * fall-through at a call site. Until Task 3, tmux is the only registered
7
7
  * implementation and that is the rollback plan — the seam lands behind no config.
8
8
  */
9
- import { HERDR, TMUX_PUSH, TMUX_PUSH_REMOTE, type Transport, type TransportKind } from "./types.js";
9
+ import { HERDR, TMUX_PUSH, TMUX_PUSH_REMOTE, TRANSPORT_KINDS, type Transport, type TransportKind } from "./types.js";
10
10
  import { TmuxTransport, type TmuxHost } from "./tmux.js";
11
+ import { HerdrTransport } from "./herdr.js";
11
12
  import { configuredTransport } from "./config.js";
12
13
 
13
14
  export * from "./types.js";
14
15
  export * from "./config.js";
15
16
  export { TmuxTransport, tmuxAvailable, paneExists, probePane, tmuxVersion, type TmuxHost } from "./tmux.js";
17
+ export { HerdrTransport, defaultHerdrRunner, interpretHerdrReply, herdrKeyName, herdrPaneExists, HERDR_KEYS, HERDR_ABSENT_MESSAGE, type HerdrRunner, type HerdrResult } from "./herdr.js";
16
18
 
17
19
  let host: TmuxHost | undefined;
18
20
 
@@ -33,9 +35,13 @@ export function resolveTransport(kind: TransportKind): Transport {
33
35
  case TMUX_PUSH_REMOTE:
34
36
  return new TmuxTransport(host, kind);
35
37
  case HERDR:
36
- // Task 4. Named so the union stays total and the gap is a stated absence
37
- // rather than a default that silently behaves like tmux.
38
- throw new Error('transport "herdr" is not implemented yet (Phase 5.4 Task 4)');
38
+ // Task 4: the socket transport. No host object there is no pusher process to
39
+ // inject; every call is `herdr <subcommand>` through the transport's own runner.
40
+ return new HerdrTransport();
41
+ default:
42
+ // Unreachable for a TransportKind; reachable from JS with a string. A designed
43
+ // refusal, never a default that behaves like tmux.
44
+ throw new Error(`unknown transport kind ${JSON.stringify(kind)} — valid: ${TRANSPORT_KINDS.join(", ")}`);
39
45
  }
40
46
  }
41
47