agent-comm-hub 0.2.0 → 0.3.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.
package/lib/cli.js CHANGED
@@ -3,6 +3,417 @@
3
3
  // src/index.ts
4
4
  import { createServer } from "node:http";
5
5
 
6
+ // src/herdr-ctl.ts
7
+ import { execFile } from "node:child_process";
8
+ import net from "node:net";
9
+ import os from "node:os";
10
+ import path from "node:path";
11
+ var AGENT_STATUSES = ["idle", "working", "blocked", "done", "unknown"];
12
+ var HerdrCtl = class {
13
+ constructor(options = {}) {
14
+ this.options = options;
15
+ this.bin = options.bin ?? "herdr";
16
+ this.baseArgs = options.baseArgs ?? [];
17
+ this.defaultTimeoutMs = options.defaultTimeoutMs ?? 3e4;
18
+ this.socketPath = options.socketPath ?? defaultSocketPath();
19
+ this.sendRequest = options.sendRequest ?? ((method, params) => socketSend(this.socketPath, method, params));
20
+ }
21
+ bin;
22
+ baseArgs;
23
+ defaultTimeoutMs;
24
+ sendRequest;
25
+ socketPath;
26
+ // ---- pane-level control (socket API; works for ANY pane, no agent
27
+ // detection required — this is the channel that drives agents herdr does
28
+ // not recognize, e.g. MiniMax Code) --------------------------------
29
+ /** `pane.list` — every pane in the session (ids, titles, agent states). */
30
+ async paneList() {
31
+ const result = await this.sendRequest("pane.list", {});
32
+ const raw = result.panes;
33
+ if (!Array.isArray(raw)) throw new Error(`herdr pane.list: unexpected result shape: ${JSON.stringify(result)}`);
34
+ return raw.map((item) => toPane(item));
35
+ }
36
+ /** `pane.send_input` — type text into a pane's input (physical input; the
37
+ * pane's program receives it as keystrokes). */
38
+ async paneSendText(paneId, text) {
39
+ if (text === "") throw new Error("paneSendText: text must not be empty");
40
+ await this.sendRequest("pane.send_input", { pane_id: paneId, text });
41
+ }
42
+ /** `pane.send_keys` — raw key presses (Enter, esc, ctrl-c, ...). */
43
+ async paneSendKeys(paneId, keys) {
44
+ if (keys.length === 0) throw new Error("paneSendKeys: at least one key is required");
45
+ await this.sendRequest("pane.send_keys", { pane_id: paneId, keys });
46
+ }
47
+ /** `pane.read` — recent terminal output of a pane. */
48
+ async paneRead(paneId, options = {}) {
49
+ const params = { pane_id: paneId, source: options.source ?? "recent", format: "text", strip_ansi: true };
50
+ if (options.lines !== void 0) params.lines = options.lines;
51
+ const result = await this.sendRequest("pane.read", params);
52
+ const raw = result.read ?? result;
53
+ const read = raw;
54
+ return {
55
+ paneId: String(read.pane_id ?? paneId),
56
+ tabId: read.tab_id === void 0 ? "" : String(read.tab_id),
57
+ workspaceId: read.workspace_id === void 0 ? null : String(read.workspace_id),
58
+ source: String(read.source ?? options.source ?? "recent"),
59
+ text: String(read.text ?? ""),
60
+ revision: Number(read.revision ?? 0),
61
+ truncated: read.truncated === true
62
+ };
63
+ }
64
+ /** `pane.wait_for_output` — block until the pane output matches a pattern
65
+ * (substring or regex), or the budget elapses. Returns the matched pane
66
+ * output, or null on timeout. */
67
+ async paneWaitForOutput(paneId, match, options = {}) {
68
+ const params = {
69
+ pane_id: paneId,
70
+ source: options.source ?? "recent",
71
+ match: { type: match.type, value: match.value },
72
+ strip_ansi: true
73
+ };
74
+ if (options.lines !== void 0) params.lines = options.lines;
75
+ if (options.timeoutMs !== void 0) params.timeout_ms = options.timeoutMs;
76
+ let result;
77
+ try {
78
+ result = await this.sendRequest("pane.wait_for_output", params);
79
+ } catch (error) {
80
+ if (/(timeout|timed out)/i.test(error.message)) return null;
81
+ throw error;
82
+ }
83
+ const raw = result.read ?? result;
84
+ if (raw === null || typeof raw !== "object") return null;
85
+ const read = raw;
86
+ return {
87
+ paneId: String(read.pane_id ?? paneId),
88
+ tabId: read.tab_id === void 0 ? "" : String(read.tab_id),
89
+ workspaceId: read.workspace_id === void 0 ? null : String(read.workspace_id),
90
+ source: String(read.source ?? options.source ?? "recent"),
91
+ text: String(read.text ?? ""),
92
+ revision: Number(read.revision ?? 0),
93
+ truncated: read.truncated === true
94
+ };
95
+ }
96
+ // ---- smart control: use herdr's agent features when the target is
97
+ // recognized, transparently fall back to pane-level control otherwise ---
98
+ /** Detect whether herdr recognizes `target` as an agent (i.e. its
99
+ * agent.get succeeds). Unrecognized panes fall back to pane control. */
100
+ async detectTarget(target) {
101
+ try {
102
+ await this.get(target);
103
+ return "agent";
104
+ } catch {
105
+ return "pane";
106
+ }
107
+ }
108
+ /** Prompt with automatic fallback: agent.prompt for recognized agents
109
+ * (state-machine wait), pane.send_input + output-settling wait otherwise. */
110
+ async promptSmart(target, text, options = {}) {
111
+ if (await this.detectTarget(target) === "agent") {
112
+ const settled2 = await this.prompt(target, text, {
113
+ wait: options.wait,
114
+ until: options.until,
115
+ timeoutMs: options.timeoutMs
116
+ });
117
+ return { via: "agent", settled: settled2 };
118
+ }
119
+ await this.paneSendText(target, text);
120
+ if (options.enter !== false) await this.paneSendKeys(target, ["Enter"]);
121
+ if (options.wait !== true) return { via: "pane", settled: null };
122
+ const budget = options.timeoutMs ?? this.defaultTimeoutMs;
123
+ const settled = await this.waitForPaneSettled(target, budget);
124
+ return { via: "pane", settled };
125
+ }
126
+ /** Wait with automatic fallback: agent.wait (state machine) for recognized
127
+ * agents; pane output-settling heuristic otherwise. */
128
+ async waitSmart(target, options = {}) {
129
+ if (await this.detectTarget(target) === "agent") {
130
+ const settled2 = await this.wait(target, options);
131
+ return { via: "agent", settled: settled2 };
132
+ }
133
+ const budget = options.timeoutMs ?? this.defaultTimeoutMs;
134
+ const settled = await this.waitForPaneSettled(target, budget);
135
+ return { via: "pane", settled };
136
+ }
137
+ /** Read terminal output of a target. Uses the socket `pane.read` for both
138
+ * recognized agents and plain panes: the CLI's `agent read --format text`
139
+ * prints RAW text to stdout (no JSON envelope), so it cannot feed the
140
+ * structured result path — the socket request is uniform and carries
141
+ * revision/truncated metadata. */
142
+ async readSmart(target, options = {}) {
143
+ return this.paneRead(target, options);
144
+ }
145
+ /** Key presses with automatic fallback: agent.send_keys for recognized
146
+ * agents, pane.send_keys otherwise. */
147
+ async keysSmart(target, keys) {
148
+ if (keys.length === 0) throw new Error("keysSmart: at least one key is required");
149
+ if (await this.detectTarget(target) === "agent") {
150
+ await this.sendKeys(target, keys);
151
+ return;
152
+ }
153
+ await this.paneSendKeys(target, keys);
154
+ }
155
+ /** Status with automatic fallback: agent.get for recognized agents; a
156
+ * pane-derived summary (status unknown) otherwise. */
157
+ async statusSmart(target) {
158
+ try {
159
+ const agent = await this.get(target);
160
+ return { agent, pane: null };
161
+ } catch {
162
+ try {
163
+ const panes = await this.paneList();
164
+ const pane = panes.find((p) => p.paneId === target);
165
+ return { agent: null, pane: pane ?? null };
166
+ } catch {
167
+ return { agent: null, pane: null };
168
+ }
169
+ }
170
+ }
171
+ /** Heuristic settle for unrecognized panes: poll pane.read revisions until
172
+ * the output stops changing for a short window, or the budget elapses. */
173
+ async waitForPaneSettled(paneId, timeoutMs) {
174
+ const startedAt = Date.now();
175
+ let lastRevision = -1;
176
+ let stableTicks = 0;
177
+ const stableTarget = 2;
178
+ const pollMs = 1500;
179
+ for (; ; ) {
180
+ const elapsed = Date.now() - startedAt;
181
+ if (elapsed >= timeoutMs) return null;
182
+ try {
183
+ const read = await this.paneRead(paneId, { source: "recent" });
184
+ if (read.revision === lastRevision) {
185
+ stableTicks++;
186
+ if (stableTicks >= stableTarget) {
187
+ return { paneId, status: "idle", waitedMs: Date.now() - startedAt };
188
+ }
189
+ } else {
190
+ stableTicks = 0;
191
+ lastRevision = read.revision;
192
+ }
193
+ } catch {
194
+ }
195
+ await new Promise((resolve) => setTimeout(resolve, pollMs));
196
+ }
197
+ }
198
+ // ---- agent-level control (CLI; requires herdr to recognize the agent) ---
199
+ /** `herdr agent list` — every agent pane herdr currently detects. */
200
+ async list() {
201
+ const result = await this.run(["agent", "list"]);
202
+ const raw = result.agents;
203
+ if (!Array.isArray(raw)) throw new Error(`herdr agent list: unexpected result shape: ${JSON.stringify(result)}`);
204
+ return raw.map((item) => toAgent(item));
205
+ }
206
+ /** `herdr agent get <target>` — one agent pane (by paneId or name). */
207
+ async get(target) {
208
+ const result = await this.run(["agent", "get", target]);
209
+ const raw = result.agent;
210
+ if (raw === void 0 || raw === null) throw new Error(`herdr agent get: unexpected result shape: ${JSON.stringify(result)}`);
211
+ return toAgent(raw);
212
+ }
213
+ /** `herdr agent read <target>` — recent terminal output of the pane. */
214
+ async read(target, options = {}) {
215
+ const args = ["agent", "read", target];
216
+ if (options.source !== void 0) args.push("--source", options.source);
217
+ if (options.lines !== void 0) args.push("--lines", String(options.lines));
218
+ args.push("--format", "text");
219
+ const result = await this.run(args);
220
+ const raw = result.read ?? result;
221
+ const read = raw;
222
+ return {
223
+ paneId: String(read.pane_id ?? target),
224
+ tabId: read.tab_id === void 0 ? "" : String(read.tab_id),
225
+ workspaceId: read.workspace_id === void 0 ? null : String(read.workspace_id),
226
+ source: String(read.source ?? options.source ?? "recent"),
227
+ text: String(read.text ?? ""),
228
+ revision: Number(read.revision ?? 0),
229
+ truncated: read.truncated === true
230
+ };
231
+ }
232
+ /** `herdr agent send-keys <target> <KEY>...` — raw key presses (Enter,
233
+ * esc, ctrl-c, arrows; named keys are passed through to herdr). */
234
+ async sendKeys(target, keys) {
235
+ if (keys.length === 0) throw new Error("sendKeys: at least one key is required");
236
+ await this.run(["agent", "send-keys", target, ...keys]);
237
+ }
238
+ /** `herdr agent prompt <target> <text>` — submit text to the agent's
239
+ * input line (a slash command like `/compact` is executed by the agent's
240
+ * TUI, not treated as chat content). With `wait`, blocks until the agent
241
+ * settles (default idle/done/blocked, or the exact `until` states) or
242
+ * `timeoutMs` elapses. */
243
+ async prompt(target, text, options = {}) {
244
+ const args = ["agent", "prompt", target, text];
245
+ if (options.wait === true) args.push("--wait");
246
+ for (const status of options.until ?? []) args.push("--until", status);
247
+ if (options.timeoutMs !== void 0) args.push("--timeout", String(options.timeoutMs));
248
+ const result = await this.run(args, options.timeoutMs);
249
+ return settleFrom(result, target);
250
+ }
251
+ /** `herdr agent wait <target>` — block until the agent reaches one of the
252
+ * requested states (default idle/done/blocked) or `timeoutMs` elapses. */
253
+ async wait(target, options = {}) {
254
+ const args = ["agent", "wait", target];
255
+ for (const status of options.until ?? []) args.push("--until", status);
256
+ if (options.timeoutMs !== void 0) args.push("--timeout", String(options.timeoutMs));
257
+ const result = await this.run(args, options.timeoutMs);
258
+ return settleFrom(result, target);
259
+ }
260
+ /** Run one herdr CLI invocation and parse its JSON envelope. */
261
+ run(args, timeoutMs) {
262
+ return new Promise((resolve, reject) => {
263
+ execFile(
264
+ this.bin,
265
+ [...this.baseArgs, ...args],
266
+ { timeout: timeoutMs ?? this.defaultTimeoutMs, windowsHide: true, maxBuffer: 16 * 1024 * 1024 },
267
+ (error, stdout, stderr) => {
268
+ if (error) {
269
+ const err = error;
270
+ if (err.code === "ENOENT") {
271
+ reject(new Error(`herdr CLI not found ('${this.bin}') \u2014 install herdr (https://herdr.dev) or point --herdr-bin at it`));
272
+ return;
273
+ }
274
+ const payload = stdout || stderr || "";
275
+ let envelope = null;
276
+ try {
277
+ envelope = JSON.parse(payload);
278
+ } catch {
279
+ }
280
+ if (envelope !== null && typeof envelope === "object" && envelope.error !== void 0) {
281
+ reject(new Error(`${envelope.error.code ?? "herdr error"}: ${envelope.error.message ?? "unknown error"}`));
282
+ return;
283
+ }
284
+ const hint = payload.trim() !== "" ? ` \u2014 ${payload.trim().slice(0, 200)}` : "";
285
+ reject(new Error(`herdr ${args.slice(0, 2).join(" ")} failed${hint}`));
286
+ return;
287
+ }
288
+ let parsed = null;
289
+ try {
290
+ parsed = JSON.parse(stdout);
291
+ } catch {
292
+ }
293
+ if (parsed === null || typeof parsed !== "object") {
294
+ reject(new Error(`herdr returned non-JSON output: ${stdout.slice(0, 200)}`));
295
+ return;
296
+ }
297
+ if (parsed.error !== void 0) {
298
+ reject(new Error(`${parsed.error.code ?? "herdr error"}: ${parsed.error.message ?? "unknown error"}`));
299
+ return;
300
+ }
301
+ resolve(parsed.result);
302
+ }
303
+ );
304
+ });
305
+ }
306
+ };
307
+ function toAgent(raw) {
308
+ const status = raw.agent_status;
309
+ return {
310
+ paneId: String(raw.pane_id ?? ""),
311
+ tabId: raw.tab_id === void 0 ? "" : String(raw.tab_id),
312
+ terminalId: raw.terminal_id === void 0 ? "" : String(raw.terminal_id),
313
+ name: raw.name === void 0 ? null : String(raw.name),
314
+ agent: raw.agent === void 0 ? null : String(raw.agent),
315
+ displayAgent: raw.display_agent === void 0 ? null : String(raw.display_agent),
316
+ status: AGENT_STATUSES.includes(status) ? status : "unknown",
317
+ cwd: raw.cwd === void 0 ? null : String(raw.cwd),
318
+ focused: raw.focused === true,
319
+ interactiveReady: raw.interactive_ready === true,
320
+ launchPending: raw.launch_pending === true,
321
+ terminalTitle: raw.terminal_title === void 0 ? null : String(raw.terminal_title),
322
+ revision: Number(raw.revision ?? 0)
323
+ };
324
+ }
325
+ function settleFrom(result, target) {
326
+ if (result === null || typeof result !== "object") return null;
327
+ const obj = result;
328
+ const event = obj.event;
329
+ const status = event?.agent_status ?? obj.agent_status ?? obj.status;
330
+ if (AGENT_STATUSES.includes(status)) {
331
+ return {
332
+ paneId: String(event?.pane_id ?? obj.pane_id ?? target),
333
+ status,
334
+ waitedMs: Number(obj.waited_ms ?? null) || null
335
+ };
336
+ }
337
+ return null;
338
+ }
339
+ function toPane(raw) {
340
+ const status = raw.agent_status;
341
+ return {
342
+ paneId: String(raw.pane_id ?? ""),
343
+ tabId: raw.tab_id === void 0 ? "" : String(raw.tab_id),
344
+ workspaceId: raw.workspace_id === void 0 ? "" : String(raw.workspace_id),
345
+ terminalId: raw.terminal_id === void 0 ? "" : String(raw.terminal_id),
346
+ title: raw.terminal_title_stripped === void 0 ? null : String(raw.terminal_title_stripped),
347
+ agentStatus: AGENT_STATUSES.includes(status) ? status : "unknown",
348
+ cwd: raw.cwd === void 0 ? null : String(raw.cwd),
349
+ focused: raw.focused === true,
350
+ revision: Number(raw.revision ?? 0)
351
+ };
352
+ }
353
+ function defaultSocketPath() {
354
+ if (process.platform === "win32") {
355
+ const base = process.env.APPDATA ?? process.env.USERPROFILE ?? ".";
356
+ return `\\\\.\\pipe\\${path.join(base, "herdr", "herdr.sock")}`;
357
+ }
358
+ return path.join(os.homedir(), ".config", "herdr", "herdr.sock");
359
+ }
360
+ function socketSend(socketPath, method, params) {
361
+ return new Promise((resolve, reject) => {
362
+ const socket = net.createConnection(socketPath);
363
+ let buffer = "";
364
+ let settled = false;
365
+ const fail = (error) => {
366
+ if (settled) return;
367
+ settled = true;
368
+ socket.destroy();
369
+ reject(error);
370
+ };
371
+ const timeout = setTimeout(() => fail(new Error(`herdr socket request timed out: ${method}`)), 15e3);
372
+ socket.on("connect", () => {
373
+ socket.write(JSON.stringify({ id: `dsh-${Date.now()}`, method, params }) + "\n");
374
+ });
375
+ socket.on("data", (chunk) => {
376
+ buffer += chunk.toString("utf8");
377
+ const lines = buffer.split("\n");
378
+ buffer = lines.pop() ?? "";
379
+ for (const line of lines) {
380
+ if (line.trim() === "") continue;
381
+ let envelope;
382
+ try {
383
+ envelope = JSON.parse(line);
384
+ } catch {
385
+ continue;
386
+ }
387
+ if (settled) continue;
388
+ settled = true;
389
+ clearTimeout(timeout);
390
+ socket.destroy();
391
+ if (envelope.error !== void 0) {
392
+ reject(new Error(`${envelope.error.code ?? "herdr error"}: ${envelope.error.message ?? "unknown error"}`));
393
+ } else {
394
+ resolve(envelope.result);
395
+ }
396
+ }
397
+ });
398
+ socket.on("error", (error) => fail(error));
399
+ socket.on("close", () => {
400
+ if (!settled && buffer.trim() !== "") {
401
+ try {
402
+ const envelope = JSON.parse(buffer);
403
+ settled = true;
404
+ clearTimeout(timeout);
405
+ if (envelope.error !== void 0) reject(new Error(`${envelope.error.code ?? "herdr error"}: ${envelope.error.message ?? "unknown error"}`));
406
+ else resolve(envelope.result);
407
+ } catch {
408
+ fail(new Error(`herdr socket closed without a response: ${method}`));
409
+ }
410
+ } else if (!settled) {
411
+ fail(new Error(`herdr socket closed without a response: ${method}`));
412
+ }
413
+ });
414
+ });
415
+ }
416
+
6
417
  // src/hub.ts
7
418
  import { randomUUID } from "node:crypto";
8
419
 
@@ -291,6 +702,22 @@ function hubTools(hub, registry, options) {
291
702
  ts: message.ts
292
703
  });
293
704
  const presentWait = (result) => result.type === "timeout" ? result : { type: "message", message: present(result.message) };
705
+ const checkControl = (peer) => {
706
+ const herdr = options.herdr;
707
+ if (herdr === void 0) {
708
+ throw new Error("herdr control not enabled \u2014 start the hub with --herdr-bin or pass a herdrCtl to hubTools");
709
+ }
710
+ const control = options.herdrControlPeers ?? "all";
711
+ if (control !== "all" && !control.has(peer)) {
712
+ throw new Error(`peer '${peer}' is not allowed to use bridge_agent_* tools`);
713
+ }
714
+ return herdr;
715
+ };
716
+ const asStatuses = (value) => {
717
+ if (!Array.isArray(value)) return void 0;
718
+ const statuses = value.map(String).filter((status) => AGENT_STATUSES.includes(status));
719
+ return statuses.length > 0 ? statuses : void 0;
720
+ };
294
721
  const wrap = (peerAware, handler) => async (args, sessionId) => {
295
722
  const peer = peerAware ? requirePeer(sessionId) : "";
296
723
  return handler(args, peer, sessionId);
@@ -416,6 +843,203 @@ function hubTools(hub, registry, options) {
416
843
  description: "Recent messages involving you (newest first); pass `peer` to inspect another peer's conversation. Use to refresh context after a reconnect.",
417
844
  inputSchema: schema({ peer: optStr("PeerId whose conversation to inspect; default: yourself."), limit: int("How many messages to return (default 20).") }),
418
845
  handler: wrap(true, async (args, peer) => ({ messages: hub.history(args.peer === void 0 ? peer : String(args.peer), Math.min(args.limit === void 0 ? 20 : Number(args.limit), 100)).map(present) }))
846
+ },
847
+ // ---- herdr control tools ------------------------------------------
848
+ // These type into real agent terminals via the herdr runtime. They are
849
+ // gated by checkControl and documented as physical input: unlike
850
+ // bridge_chat (a mailbox message the model may ignore), a prompt here is
851
+ // executed by the target's TUI — slash commands included.
852
+ {
853
+ name: "bridge_agent_list",
854
+ description: "List agent panes detected by the herdr terminal runtime (paneId, agent kind, lifecycle status, cwd, interactive-ready). Use a paneId as the `target` of the other bridge_agent_* tools. Control tools: they type into the target terminal \u2014 use with care.",
855
+ inputSchema: schema({}),
856
+ handler: wrap(true, async (_args, peer) => ({ agents: await checkControl(peer).list() }))
857
+ },
858
+ {
859
+ name: "bridge_agent_status",
860
+ description: 'Live status of a target: for agents herdr recognizes, the full lifecycle state (idle/working/blocked/done) and agent kind; for unrecognized panes, a pane-derived summary with status "unknown" and `pane` populated. `target` is a herdr paneId from bridge_pane_list / bridge_agent_list.',
861
+ inputSchema: schema({ target: str("herdr paneId, e.g. w1:p1, from bridge_agent_list or bridge_pane_list.") }, ["target"]),
862
+ handler: wrap(true, async (args, peer) => {
863
+ const result = await checkControl(peer).statusSmart(String(args.target));
864
+ return { agent: result.agent, ...result.pane !== null ? { pane: result.pane } : {} };
865
+ })
866
+ },
867
+ {
868
+ name: "bridge_agent_prompt",
869
+ description: 'Submit text directly into the target terminal. For agents herdr recognizes, uses agent.prompt \u2014 a state-machine wait (`wait: true` blocks until idle/done/blocked, exact states via `until`). For unrecognized panes (e.g. MiniMax Code), falls back to pane-level input (`pane.send_input`) and waits for the pane output to settle. Slash commands are executed by the target\'s TUI either way. Returns `via: "agent" | "pane"` so callers know which channel was used.',
870
+ inputSchema: schema(
871
+ {
872
+ target: str("herdr paneId, e.g. w1:p1, from bridge_pane_list / bridge_agent_list."),
873
+ text: str("Text to submit (slash commands are executed, not sent as chat)."),
874
+ wait: { type: "boolean", description: "Wait for the agent to settle after submission (default false)." },
875
+ until: { type: "array", items: { type: "string", enum: [...AGENT_STATUSES] }, description: "Exact states to wait for (agent channel; default: idle/done/blocked)." },
876
+ timeoutMs: int("Wait cap in ms (default 30000).")
877
+ },
878
+ ["target", "text"]
879
+ ),
880
+ handler: wrap(true, async (args, peer) => {
881
+ const ctl = checkControl(peer);
882
+ const waiting = args.wait === true;
883
+ const result = await ctl.promptSmart(String(args.target), String(args.text), {
884
+ wait: waiting,
885
+ until: asStatuses(args.until),
886
+ timeoutMs: args.timeoutMs === void 0 ? void 0 : Number(args.timeoutMs)
887
+ });
888
+ return waiting ? { submitted: true, via: result.via, settled: result.settled } : { submitted: true, via: result.via };
889
+ })
890
+ },
891
+ {
892
+ name: "bridge_agent_wait",
893
+ description: 'Wait until the target settles. For agents herdr recognizes: state-machine wait (agent.wait \u2014 idle/working/blocked/done, `until` for exact states). For unrecognized panes: falls back to polling pane output until it stops changing. Returns `via: "agent" | "pane"`; a `settled: null` result means the timeout fired first.',
894
+ inputSchema: schema(
895
+ {
896
+ target: str("herdr paneId, e.g. w1:p1, from bridge_pane_list / bridge_agent_list."),
897
+ until: { type: "array", items: { type: "string", enum: [...AGENT_STATUSES] }, description: "Exact states to wait for (agent channel; default: idle/done/blocked)." },
898
+ timeoutMs: int("Wait cap in ms (default 30000).")
899
+ },
900
+ ["target"]
901
+ ),
902
+ handler: wrap(true, async (args, peer) => {
903
+ const result = await checkControl(peer).waitSmart(String(args.target), {
904
+ until: asStatuses(args.until),
905
+ timeoutMs: args.timeoutMs === void 0 ? void 0 : Number(args.timeoutMs)
906
+ });
907
+ return { via: result.via, settled: result.settled };
908
+ })
909
+ },
910
+ {
911
+ name: "bridge_agent_read",
912
+ description: "Read the target's recent terminal output (plain text). Uses agent.read for recognized agents, pane.read otherwise. Use to collect the reply of an agent that is not connected to the hub (its output never enters a mailbox).",
913
+ inputSchema: schema(
914
+ {
915
+ target: str("herdr paneId, e.g. w1:p1, from bridge_pane_list / bridge_agent_list."),
916
+ lines: int("How many lines to read (default: all recent)."),
917
+ source: { type: "string", enum: ["visible", "recent", "recent-unwrapped", "detection"], description: "Terminal snapshot source (default recent)." }
918
+ },
919
+ ["target"]
920
+ ),
921
+ handler: wrap(
922
+ true,
923
+ async (args, peer) => checkControl(peer).readSmart(String(args.target), {
924
+ lines: args.lines === void 0 ? void 0 : Number(args.lines),
925
+ source: args.source === void 0 ? void 0 : args.source
926
+ })
927
+ )
928
+ },
929
+ {
930
+ name: "bridge_agent_keys",
931
+ description: "Send raw key presses to the target terminal \u2014 Enter, esc, ctrl-c, arrows, etc. Use to dismiss permission prompts or interrupt a stuck agent. Keys are passed verbatim.",
932
+ inputSchema: schema(
933
+ {
934
+ target: str("herdr paneId, e.g. w1:p1, from bridge_pane_list / bridge_agent_list."),
935
+ keys: { type: "array", items: { type: "string" }, description: 'Keys to send, e.g. ["Enter"], ["esc"], ["ctrl-c", "Enter"].' }
936
+ },
937
+ ["target", "keys"]
938
+ ),
939
+ handler: wrap(true, async (args, peer) => {
940
+ const ctl = checkControl(peer);
941
+ const keys = Array.isArray(args.keys) ? args.keys.map(String) : [];
942
+ if (keys.length === 0) throw new Error("keys: at least one key is required");
943
+ await ctl.keysSmart(String(args.target), keys);
944
+ return { ok: true, sent: keys };
945
+ })
946
+ },
947
+ // ---- pane-level control tools (socket API) -----------------------
948
+ // Unlike the bridge_agent_* tools (which require herdr to RECOGNIZE the
949
+ // agent), these drive any pane through the herdr local socket: physical
950
+ // input and output for agents herdr does not know (e.g. MiniMax Code).
951
+ {
952
+ name: "bridge_pane_list",
953
+ description: "List every herdr pane (ids, titles, agent status, cwd) via the herdr socket \u2014 including panes running agents herdr does not recognize. Use a paneId as `target` of bridge_pane_send / bridge_pane_keys / bridge_pane_read. Control tools: they type into real terminals \u2014 use with care.",
954
+ inputSchema: schema({}),
955
+ handler: wrap(true, async (_args, peer) => ({ panes: await checkControl(peer).paneList() }))
956
+ },
957
+ {
958
+ name: "bridge_pane_send",
959
+ description: "Type text into a herdr pane's input line (physical keystrokes via the herdr socket; works for ANY pane, no agent detection needed). This is how you drive an agent herdr does not recognize: the text lands in the target's terminal as if typed. Slash commands are executed by the target's TUI. With enter: true (default), the text is submitted with Enter.",
960
+ inputSchema: schema(
961
+ {
962
+ target: str("herdr paneId, e.g. wT:p2, from bridge_pane_list."),
963
+ text: str("Text to type into the pane (slash commands are executed, not sent as chat)."),
964
+ enter: { type: "boolean", description: "Submit with Enter after typing (default true)." }
965
+ },
966
+ ["target", "text"]
967
+ ),
968
+ handler: wrap(true, async (args, peer) => {
969
+ const ctl = checkControl(peer);
970
+ const paneId = String(args.target);
971
+ const text = String(args.text);
972
+ await ctl.paneSendText(paneId, text);
973
+ if (args.enter !== false) await ctl.paneSendKeys(paneId, ["Enter"]);
974
+ return { ok: true, target: paneId, sent: text };
975
+ })
976
+ },
977
+ {
978
+ name: "bridge_pane_keys",
979
+ description: "Send raw key presses to any herdr pane (Enter, esc, ctrl-c, arrows...). Use to dismiss permission prompts or interrupt a stuck program in a pane herdr does not recognize as an agent.",
980
+ inputSchema: schema(
981
+ {
982
+ target: str("herdr paneId, e.g. wT:p2, from bridge_pane_list."),
983
+ keys: { type: "array", items: { type: "string" }, description: 'Keys to send, e.g. ["Enter"], ["esc"], ["ctrl-c"].' }
984
+ },
985
+ ["target", "keys"]
986
+ ),
987
+ handler: wrap(true, async (args, peer) => {
988
+ const ctl = checkControl(peer);
989
+ const keys = Array.isArray(args.keys) ? args.keys.map(String) : [];
990
+ if (keys.length === 0) throw new Error("keys: at least one key is required");
991
+ await ctl.paneSendKeys(String(args.target), keys);
992
+ return { ok: true, sent: keys };
993
+ })
994
+ },
995
+ {
996
+ name: "bridge_pane_read",
997
+ description: "Read a herdr pane's recent terminal output (plain text, ANSI stripped). Use to collect the reply of an agent that is not connected to the hub or not recognized by herdr.",
998
+ inputSchema: schema(
999
+ {
1000
+ target: str("herdr paneId, e.g. wT:p2, from bridge_pane_list."),
1001
+ lines: int("How many lines to read (default: all recent)."),
1002
+ source: { type: "string", enum: ["visible", "recent", "recent-unwrapped", "detection"], description: "Terminal snapshot source (default recent)." }
1003
+ },
1004
+ ["target"]
1005
+ ),
1006
+ handler: wrap(
1007
+ true,
1008
+ async (args, peer) => checkControl(peer).paneRead(String(args.target), {
1009
+ lines: args.lines === void 0 ? void 0 : Number(args.lines),
1010
+ source: args.source === void 0 ? void 0 : args.source
1011
+ })
1012
+ )
1013
+ },
1014
+ {
1015
+ name: "bridge_pane_wait",
1016
+ description: "Wait until a herdr pane's output matches a pattern (substring or regex) or the budget elapses \u2014 the pane-level counterpart of bridge_agent_wait for agents herdr does not recognize. Returns the matched pane output, or `matched: null` on timeout.",
1017
+ inputSchema: schema(
1018
+ {
1019
+ target: str("herdr paneId, e.g. wT:p2, from bridge_pane_list."),
1020
+ match: {
1021
+ type: "object",
1022
+ properties: {
1023
+ type: { type: "string", enum: ["substring", "regex"], description: "Match kind (default substring)." },
1024
+ value: { type: "string", description: "Text or regex to match in the pane output." }
1025
+ },
1026
+ required: ["value"],
1027
+ description: "Output pattern to wait for."
1028
+ },
1029
+ timeoutMs: int("Wait cap in ms (default 30000).")
1030
+ },
1031
+ ["target", "match"]
1032
+ ),
1033
+ handler: wrap(true, async (args, peer) => {
1034
+ const ctl = checkControl(peer);
1035
+ const match = args.match ?? {};
1036
+ if (typeof match.value !== "string" || match.value === "") throw new Error("match.value: a non-empty string is required");
1037
+ const type = match.type === "regex" ? "regex" : "substring";
1038
+ const read = await ctl.paneWaitForOutput(String(args.target), { type, value: match.value }, {
1039
+ timeoutMs: args.timeoutMs === void 0 ? void 0 : Number(args.timeoutMs)
1040
+ });
1041
+ return read === null ? { matched: null } : { matched: read };
1042
+ })
419
1043
  }
420
1044
  ];
421
1045
  }
@@ -527,10 +1151,10 @@ var McpStreamableHttpServer = class {
527
1151
  }
528
1152
  sseStreams = /* @__PURE__ */ new Map();
529
1153
  /** Attach request handling for `path` (e.g. `/mcp`) to an http server. */
530
- attach(server, path) {
1154
+ attach(server, path2) {
531
1155
  server.on("request", (req, res) => {
532
1156
  const url = new URL(req.url ?? "/", "http://localhost");
533
- if (url.pathname !== path) {
1157
+ if (url.pathname !== path2) {
534
1158
  res.writeHead(404, { "Content-Type": "application/json" }).end(JSON.stringify({ error: "not found" }));
535
1159
  return;
536
1160
  }
@@ -710,7 +1334,7 @@ function readBody(req) {
710
1334
 
711
1335
  // src/index.ts
712
1336
  var SERVER_NAME = "agent-comm-hub";
713
- var SERVER_VERSION = "0.2.0";
1337
+ var SERVER_VERSION = "0.3.0";
714
1338
  var DEFAULT_HOST = "127.0.0.1";
715
1339
  var DEFAULT_PORT = 18764;
716
1340
  var DEFAULT_PATH = "/mcp";
@@ -739,8 +1363,20 @@ function startHub(config = {}, log2 = console) {
739
1363
  isPeerLive: (peerId) => livePeersFor(registry).has(peerId)
740
1364
  });
741
1365
  const registry = new SessionRegistry();
1366
+ const herdr = new HerdrCtl({
1367
+ bin: resolved.herdrBin,
1368
+ baseArgs: resolved.herdrBaseArgs,
1369
+ defaultTimeoutMs: resolved.herdrTimeoutMs,
1370
+ socketPath: resolved.herdrSocketPath,
1371
+ sendRequest: resolved.herdrSendRequest
1372
+ });
742
1373
  const mcp = new McpStreamableHttpServer(
743
- hubTools(hub, registry, { defaultWaitMs: resolved.defaultWaitMs, waitTimeoutMs: resolved.waitTimeoutMs }),
1374
+ hubTools(hub, registry, {
1375
+ defaultWaitMs: resolved.defaultWaitMs,
1376
+ waitTimeoutMs: resolved.waitTimeoutMs,
1377
+ herdr,
1378
+ herdrControlPeers: resolved.herdrControlPeers === "all" || resolved.herdrControlPeers === void 0 ? "all" : new Set(resolved.herdrControlPeers)
1379
+ }),
744
1380
  { name: SERVER_NAME, version: SERVER_VERSION },
745
1381
  registry,
746
1382
  (message) => log2.warn(message),
@@ -774,7 +1410,7 @@ function startHub(config = {}, log2 = console) {
774
1410
  }
775
1411
 
776
1412
  // src/setup.ts
777
- import { copyFile, mkdir, readFile, writeFile } from "node:fs/promises";
1413
+ import { copyFile, mkdir, readFile, readdir, writeFile } from "node:fs/promises";
778
1414
  import { existsSync } from "node:fs";
779
1415
  import { homedir } from "node:os";
780
1416
  import { dirname, join } from "node:path";
@@ -865,6 +1501,68 @@ url = "${opts.url}"
865
1501
  function escapeRegExp(value) {
866
1502
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
867
1503
  }
1504
+ var DSH_PATCH_MARKER = "# \u2500\u2500 agent-comm-hub MCP client";
1505
+ function dshPatchBlock(url, serverName) {
1506
+ return `
1507
+ ${DSH_PATCH_MARKER} (installed by \`agent-comm-hub setup\`; undo with \`setup --remove\`) \u2500
1508
+ - insert:
1509
+ - id: ${serverName}
1510
+ name: '@deepseek-ai/dsh-mcp-client'
1511
+ config:
1512
+ serverName: ${serverName}
1513
+ transport: streamable-http
1514
+ url: ${url}
1515
+ `;
1516
+ }
1517
+ async function mergeDshPatch(file, opts) {
1518
+ if (!existsSync(file)) return "skipped";
1519
+ const text = await readFile(file, "utf8");
1520
+ const lines = text.split("\n");
1521
+ const markerLine = lines.findIndex((line) => line.includes(DSH_PATCH_MARKER));
1522
+ const hasBlock = markerLine >= 0;
1523
+ const blockRange = () => {
1524
+ let entryStart = -1;
1525
+ for (let i = markerLine + 1; i < lines.length; i++) {
1526
+ if (/^- /.test(lines[i])) {
1527
+ entryStart = i;
1528
+ break;
1529
+ }
1530
+ }
1531
+ let end = lines.length;
1532
+ if (entryStart >= 0) {
1533
+ for (let i = entryStart + 1; i < lines.length; i++) {
1534
+ if (/^- /.test(lines[i])) {
1535
+ end = i;
1536
+ break;
1537
+ }
1538
+ }
1539
+ }
1540
+ let start = markerLine;
1541
+ while (start > 0 && lines[start - 1].trim() === "") start--;
1542
+ return { start, end };
1543
+ };
1544
+ const withoutBlock = () => {
1545
+ const { start, end } = blockRange();
1546
+ return lines.slice(0, start).concat(lines.slice(end)).join("\n");
1547
+ };
1548
+ if (opts.remove) {
1549
+ if (!hasBlock) return "absent";
1550
+ const cleaned = withoutBlock();
1551
+ await backup(file);
1552
+ await writeFile(file, cleaned, "utf8");
1553
+ return "removed";
1554
+ }
1555
+ if (hasBlock) {
1556
+ if (lines.some((line) => line.includes(`url: ${opts.url}`))) return "unchanged";
1557
+ const replaced = withoutBlock();
1558
+ await backup(file);
1559
+ await writeFile(file, replaced.trimEnd() + dshPatchBlock(opts.url, opts.serverName), "utf8");
1560
+ return "changed";
1561
+ }
1562
+ await backup(file);
1563
+ await writeFile(file, text.trimEnd() + dshPatchBlock(opts.url, opts.serverName), "utf8");
1564
+ return "changed";
1565
+ }
868
1566
  async function syncSkill(skillDir, skillSrc, remove, log2) {
869
1567
  if (remove) {
870
1568
  if (existsSync(skillDir)) {
@@ -924,6 +1622,26 @@ async function runSetup(options = {}) {
924
1622
  summary.errors.push(`codex: ${codexFile} \u2014 ${error.message}`);
925
1623
  log2(` codex: SKIPPED \u2014 ${error.message}`);
926
1624
  }
1625
+ const dshProfilesDir = join(home, ".dsh", "profiles");
1626
+ if (existsSync(dshProfilesDir)) {
1627
+ let entries = [];
1628
+ try {
1629
+ entries = await readdir(dshProfilesDir, { withFileTypes: true });
1630
+ } catch (error) {
1631
+ summary.errors.push(`dsh profiles scan \u2014 ${error.message}`);
1632
+ }
1633
+ for (const entry of entries) {
1634
+ if (!entry.isDirectory()) continue;
1635
+ const patch = join(dshProfilesDir, entry.name, "cordis.patch.yml");
1636
+ try {
1637
+ const status = await mergeDshPatch(patch, { serverName, url, remove });
1638
+ record(status, `dsh (${entry.name})`, patch);
1639
+ } catch (error) {
1640
+ summary.errors.push(`dsh (${entry.name}): ${patch} \u2014 ${error.message}`);
1641
+ log2(` dsh (${entry.name}): SKIPPED \u2014 ${error.message}`);
1642
+ }
1643
+ }
1644
+ }
927
1645
  const skillDirs = [
928
1646
  join(home, ".agents", "skills", serverName),
929
1647
  // cross-agent standard
@@ -933,8 +1651,10 @@ async function runSetup(options = {}) {
933
1651
  join(home, ".gemini", "skills", serverName),
934
1652
  join(home, ".codex", "skills", serverName),
935
1653
  join(home, ".zcode", "skills", serverName),
936
- join(home, ".claude", "skills", serverName)
1654
+ join(home, ".claude", "skills", serverName),
937
1655
  // config is manual; skill still useful
1656
+ join(home, ".dsh", "skills", serverName)
1657
+ // DSH skill (config auto-installed)
938
1658
  ];
939
1659
  for (const dir of skillDirs) {
940
1660
  try {
@@ -944,8 +1664,8 @@ async function runSetup(options = {}) {
944
1664
  log2(` skill ${dir}: SKIPPED \u2014 ${error.message}`);
945
1665
  }
946
1666
  }
947
- if (remove) log2("done. Manual targets (see agents/README.md): Claude Code (.mcp.json), DSH (cordis.patch.yml).");
948
- else log2("done. Manual targets (see agents/README.md): Claude Code (.mcp.json), DSH (cordis.patch.yml). Restart agent sessions to pick up the MCP server.");
1667
+ if (remove) log2("done. Manual target (see agents/README.md): Claude Code (.mcp.json).");
1668
+ else log2("done. Manual target (see agents/README.md): Claude Code (.mcp.json). Restart agent sessions (and the dsh profile) to pick up the MCP server.");
949
1669
  return summary;
950
1670
  }
951
1671
 
@@ -959,8 +1679,8 @@ import { fileURLToPath as fileURLToPath2 } from "node:url";
959
1679
  async function runStatus(options = {}) {
960
1680
  const host = options.host ?? "127.0.0.1";
961
1681
  const port = options.port ?? 18764;
962
- const path = options.path ?? "/mcp";
963
- const url = options.url ?? `http://${host}:${port}${path}`;
1682
+ const path2 = options.path ?? "/mcp";
1683
+ const url = options.url ?? `http://${host}:${port}${path2}`;
964
1684
  const probeName = "agent-comm-hub-cli";
965
1685
  const notRunning = { running: false, url, peers: [] };
966
1686
  try {
@@ -1046,7 +1766,7 @@ function runService(options) {
1046
1766
  const messages = [];
1047
1767
  const port = options.port ?? 18764;
1048
1768
  const host = options.host ?? "127.0.0.1";
1049
- const path = options.path ?? "/mcp";
1769
+ const path2 = options.path ?? "/mcp";
1050
1770
  const dryRun = options.dryRun === true;
1051
1771
  try {
1052
1772
  if (process.platform === "win32") {
@@ -1056,7 +1776,7 @@ function runService(options) {
1056
1776
  const runKey = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run";
1057
1777
  const valueName = "agent-comm-hub";
1058
1778
  if (options.action === "install") {
1059
- const cmd = `"${nodeExe()}" "${cliPath()}" --host ${host} --port ${port} --path ${path}`;
1779
+ const cmd = `"${nodeExe()}" "${cliPath()}" --host ${host} --port ${port} --path ${path2}`;
1060
1780
  const vbsContent = `CreateObject("WScript.Shell").Run "${cmd.replace(/"/g, '""')}", 0, False
1061
1781
  `;
1062
1782
  if (dryRun) {
@@ -1093,7 +1813,7 @@ Description=agent-comm-hub (multi-peer MCP hub)
1093
1813
  After=network.target
1094
1814
 
1095
1815
  [Service]
1096
- ExecStart=${nodeExe()} ${cliPath()} --host ${host} --port ${port} --path ${path}
1816
+ ExecStart=${nodeExe()} ${cliPath()} --host ${host} --port ${port} --path ${path2}
1097
1817
  Restart=on-failure
1098
1818
 
1099
1819
  [Install]
@@ -1130,8 +1850,8 @@ WantedBy=default.target
1130
1850
  // src/cli.ts
1131
1851
  function parseArgs(argv) {
1132
1852
  const args = {};
1133
- const numeric = /* @__PURE__ */ new Set(["--port", "--max-queue", "--history-limit", "--wait-timeout-ms", "--default-wait-ms", "--connected-window-ms", "--peer-idle-timeout-ms"]);
1134
- const string = /* @__PURE__ */ new Set(["--host", "--path", "--url", "--server-name"]);
1853
+ const numeric = /* @__PURE__ */ new Set(["--port", "--max-queue", "--history-limit", "--wait-timeout-ms", "--default-wait-ms", "--connected-window-ms", "--peer-idle-timeout-ms", "--herdr-timeout-ms"]);
1854
+ const string = /* @__PURE__ */ new Set(["--host", "--path", "--url", "--server-name", "--herdr-bin"]);
1135
1855
  for (let i = 0; i < argv.length; i++) {
1136
1856
  const flag = argv[i];
1137
1857
  if (flag === "--help" || flag === "-h" || flag === "--version" || flag === "-V") {
@@ -1185,6 +1905,9 @@ Hub options:
1185
1905
  --default-wait-ms <n> bridge_wait default budget (default 30000)
1186
1906
  --connected-window-ms <n> Peer counts as active within this window (default 30000)
1187
1907
  --peer-idle-timeout-ms <n> Auto-unregister idle peers after this; 0 disables (default 600000)
1908
+ --herdr-bin <path> herdr CLI binary for bridge_agent_* control tools
1909
+ (default herdr, resolved via PATH)
1910
+ --herdr-timeout-ms <n> Default cap for one herdr call in ms (default 30000)
1188
1911
 
1189
1912
  Setup options:
1190
1913
  --url <url> Hub endpoint to register (default http://127.0.0.1:18764/mcp)
@@ -1294,7 +2017,9 @@ try {
1294
2017
  waitTimeoutMs: args["--wait-timeout-ms"],
1295
2018
  defaultWaitMs: args["--default-wait-ms"],
1296
2019
  connectedWindowMs: args["--connected-window-ms"],
1297
- peerIdleTimeoutMs: args["--peer-idle-timeout-ms"]
2020
+ peerIdleTimeoutMs: args["--peer-idle-timeout-ms"],
2021
+ herdrBin: args["--herdr-bin"],
2022
+ herdrTimeoutMs: args["--herdr-timeout-ms"]
1298
2023
  }, log);
1299
2024
  const shutdown = () => {
1300
2025
  log.info("agent-comm-hub shutting down");