@howaboua/pi-shepherdr 0.1.1 → 0.1.2

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/README.md CHANGED
@@ -4,7 +4,7 @@ Talk to one Pi. Let it run the others.
4
4
 
5
5
  Shepherdr turns one Pi session into an orchestrator for Pi agents running across [Herdr](https://herdr.dev). Give work to the master; it can find existing agents, start new ones in explicit locations, send follow-ups and bring their full replies back into the same conversation.
6
6
 
7
- The master gets one small JSON-schema tool with the actions and arguments it needs. Its complete active surface measures 271 `o200k` tokens: 228 for the OpenAI Responses tool declaration and 43 for the master guideline. Workers load none of it.
7
+ The master gets one small JSON-schema tool with the actions and arguments it needs. Its complete active surface measures 290 `o200k` tokens: 247 for the OpenAI Responses tool declaration and 43 for the master guideline. Workers load none of it.
8
8
 
9
9
  Enable master mode and Pi already knows its job. You do not have to explain Herdr, ask it to load an orchestration skill or remind it to delegate. The schema handles ordinary delegation without `--help` or improvised CLI commands. Herdr and Shepherdr should be enough on their own; any other Pi extensions and skills continue to work alongside them.
10
10
 
@@ -54,6 +54,14 @@ Future Pi sessions in that directory start as masters. `/herdr master` affects o
54
54
 
55
55
  While master mode is active, Pi is guided to delegate project implementation and synthesize the results. It works directly when you explicitly ask, and for configuration, documentation and routine operations in its current directory.
56
56
 
57
+ ## Connect more machines
58
+
59
+ Run `/herdr` and choose **Add machine**. Give the machine a name and an SSH target that already connects noninteractively; the remote machine needs Node, Herdr and the Pi integration. Machine settings live in `~/.pi/agent/shepherdr.json`.
60
+
61
+ Master mode connects every configured machine once in parallel. A failed or dropped connection remains unavailable without retrying automatically; use `/herdr connect` or `/herdr connect <machine>` to try again.
62
+
63
+ Shepherdr maintains one remote helper at `~/.pi/agent/shepherdr.mjs`. It updates that file atomically when needed, runs it only for the lifetime of the SSH connection and leaves no remote daemon behind. Agent lists, workspaces, monitored state and full replies retain their machine identity. Ask the master naturally—for example, “run this on desktop”—and it routes the existing `herdr_agents` tool with the configured machine name.
64
+
57
65
  ## What the master can do
58
66
 
59
67
  Shepherdr adds one compact `herdr_agents` tool. Its schema is the complete model-facing control surface:
package/index.ts CHANGED
@@ -1,14 +1,13 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { AgentFleet } from "./src/fleet.js";
2
3
  import { registerMasterMode } from "./src/master-mode.js";
3
4
  import { registerAgentEventRenderer } from "./src/messages.js";
4
- import { AgentMonitor } from "./src/monitor.js";
5
5
  import { registerHerdrAgentsTool } from "./src/tool.js";
6
6
 
7
7
  export default function shepherdrExtension(pi: ExtensionAPI): void {
8
- let monitor: AgentMonitor | undefined;
9
- const getMonitor = () => (monitor ??= new AgentMonitor(pi));
8
+ const fleet = new AgentFleet(pi);
10
9
 
11
10
  registerAgentEventRenderer(pi);
12
- registerHerdrAgentsTool(pi, getMonitor);
13
- registerMasterMode(pi, getMonitor);
11
+ registerHerdrAgentsTool(pi, fleet);
12
+ registerMasterMode(pi, fleet);
14
13
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@howaboua/pi-shepherdr",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "Herdr-native multi-agent orchestration for Pi.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/fleet.ts ADDED
@@ -0,0 +1,556 @@
1
+ import type {
2
+ ExtensionAPI,
3
+ ExtensionContext,
4
+ } from "@earendil-works/pi-coding-agent";
5
+ import { getSnapshot } from "./herdr.js";
6
+ import { HerdrClient, type HerdrConnection } from "./herdr-client.js";
7
+ import {
8
+ LOCAL_MACHINE,
9
+ type MachinesConfig,
10
+ type RemoteMachineConfig,
11
+ readMachinesConfig,
12
+ } from "./machines-config.js";
13
+ import { AgentMonitor } from "./monitor.js";
14
+ import { parseMonitoredAgent } from "./monitor-record.js";
15
+ import { RemoteHerdrClient } from "./remote-client.js";
16
+ import type {
17
+ MachineStatus,
18
+ MonitoredAgent,
19
+ ScopedMonitoredAgent,
20
+ SessionSnapshot,
21
+ } from "./types.js";
22
+ import { renderAgentWidget } from "./widget.js";
23
+
24
+ const MONITOR_STATE_TYPE = "herdr-agents-monitor-state";
25
+
26
+ interface Runtime {
27
+ attempting?: boolean;
28
+ client?: HerdrConnection;
29
+ config?: RemoteMachineConfig;
30
+ local: boolean;
31
+ monitor?: AgentMonitor;
32
+ pending: unknown[];
33
+ reason?: string;
34
+ status: MachineStatus["status"];
35
+ }
36
+
37
+ export interface ConnectedMachine {
38
+ client: HerdrConnection;
39
+ fallbackCwd: string;
40
+ local: boolean;
41
+ machine: string;
42
+ monitor: AgentMonitor;
43
+ resolveDirectory?: (
44
+ value: string | undefined,
45
+ fallback: string,
46
+ ) => Promise<string>;
47
+ }
48
+
49
+ export interface MachineSnapshot extends MachineStatus {
50
+ monitoredPaneIds?: ReadonlySet<string>;
51
+ snapshot?: SessionSnapshot;
52
+ snapshotError?: string;
53
+ }
54
+
55
+ function errorMessage(error: unknown): string {
56
+ const message = error instanceof Error ? error.message : String(error);
57
+ return message.length <= 500 ? message : `${message.slice(0, 499)}…`;
58
+ }
59
+
60
+ function shellQuote(value: string): string {
61
+ return `'${value.replaceAll("'", `'"'"'`)}'`;
62
+ }
63
+
64
+ function operatorPrefix(config: RemoteMachineConfig): string {
65
+ const socket = config.socket?.startsWith("~/")
66
+ ? `HERDR_SOCKET_PATH="$HOME"/${shellQuote(config.socket.slice(2))}`
67
+ : config.socket === "~"
68
+ ? 'HERDR_SOCKET_PATH="$HOME"'
69
+ : config.socket
70
+ ? `HERDR_SOCKET_PATH=${shellQuote(config.socket)}`
71
+ : undefined;
72
+ const remote = socket
73
+ ? ["env", socket, config.herdr]
74
+ : [config.herdr, ...(config.session ? ["--session", config.session] : [])];
75
+ return [...config.command, ...remote].map(shellQuote).join(" ");
76
+ }
77
+
78
+ function sameMachineConfig(
79
+ left: RemoteMachineConfig,
80
+ right: RemoteMachineConfig,
81
+ ): boolean {
82
+ return (
83
+ left.herdr === right.herdr &&
84
+ left.node === right.node &&
85
+ left.session === right.session &&
86
+ left.socket === right.socket &&
87
+ left.command.length === right.command.length &&
88
+ left.command.every((part, index) => part === right.command[index])
89
+ );
90
+ }
91
+
92
+ function savedAgents(ctx: ExtensionContext): unknown[] {
93
+ let latest: unknown[] = [];
94
+ for (const entry of ctx.sessionManager.getBranch()) {
95
+ if (entry.type !== "custom" || entry.customType !== MONITOR_STATE_TYPE)
96
+ continue;
97
+ const data = entry.data as { agents?: unknown };
98
+ if (Array.isArray(data?.agents)) latest = data.agents;
99
+ }
100
+ return latest;
101
+ }
102
+
103
+ function groupSaved(values: unknown[]): Map<string, unknown[]> {
104
+ const grouped = new Map<string, unknown[]>();
105
+ for (const value of values) {
106
+ const machine =
107
+ typeof value === "object" &&
108
+ value !== null &&
109
+ "machine" in value &&
110
+ typeof value.machine === "string"
111
+ ? value.machine
112
+ : LOCAL_MACHINE;
113
+ const records = grouped.get(machine) ?? [];
114
+ records.push(value);
115
+ grouped.set(machine, records);
116
+ }
117
+ return grouped;
118
+ }
119
+
120
+ export class AgentFleet {
121
+ private config: MachinesConfig = { machines: {} };
122
+ private context: ExtensionContext | undefined;
123
+ private generation = 0;
124
+ private readonly pi: ExtensionAPI;
125
+ private readonly runtimes = new Map<string, Runtime>();
126
+
127
+ constructor(pi: ExtensionAPI) {
128
+ this.pi = pi;
129
+ }
130
+
131
+ async activate(ctx: ExtensionContext): Promise<void> {
132
+ this.deactivate();
133
+ const generation = this.generation;
134
+ this.context = ctx;
135
+ const config = await readMachinesConfig();
136
+ if (!this.isCurrent(generation, ctx)) return;
137
+ this.config = config;
138
+ const grouped = groupSaved(savedAgents(ctx));
139
+ const known = new Set([
140
+ LOCAL_MACHINE,
141
+ ...Object.keys(this.config.machines),
142
+ ]);
143
+ const orphaned = [...grouped.entries()]
144
+ .filter(([machine]) => !known.has(machine))
145
+ .reduce((count, [, records]) => count + records.length, 0);
146
+ if (orphaned > 0) {
147
+ ctx.ui.notify(
148
+ `Ignored ${orphaned} saved Shepherdr ${orphaned === 1 ? "agent" : "agents"} from removed machines`,
149
+ "warning",
150
+ );
151
+ }
152
+
153
+ const localRuntime: Runtime = {
154
+ local: true,
155
+ pending: grouped.get(LOCAL_MACHINE) ?? [],
156
+ status: "connecting",
157
+ };
158
+ this.runtimes.set(LOCAL_MACHINE, localRuntime);
159
+ for (const [name, config] of Object.entries(this.config.machines)) {
160
+ this.runtimes.set(name, {
161
+ config,
162
+ local: false,
163
+ pending: grouped.get(name) ?? [],
164
+ status: "connecting",
165
+ });
166
+ }
167
+
168
+ const localClient = new HerdrClient();
169
+ await localClient.request("ping");
170
+ if (!this.isCurrent(generation, ctx)) return;
171
+ const localMonitor = this.createMonitor(
172
+ LOCAL_MACHINE,
173
+ localRuntime,
174
+ localClient,
175
+ );
176
+ localRuntime.client = localClient;
177
+ localRuntime.monitor = localMonitor;
178
+ await localMonitor.activate(ctx, localRuntime.pending);
179
+ if (
180
+ !this.isCurrent(generation, ctx) ||
181
+ this.runtimes.get(LOCAL_MACHINE) !== localRuntime ||
182
+ localRuntime.client !== localClient ||
183
+ localRuntime.monitor !== localMonitor
184
+ ) {
185
+ localMonitor.deactivate();
186
+ return;
187
+ }
188
+ localRuntime.pending = [];
189
+ localRuntime.status = "connected";
190
+ this.refresh();
191
+
192
+ for (const name of Object.keys(this.config.machines)) {
193
+ void this.connectMachine(name, generation, true);
194
+ }
195
+ }
196
+
197
+ deactivate(): void {
198
+ this.generation += 1;
199
+ for (const runtime of this.runtimes.values()) {
200
+ runtime.monitor?.deactivate();
201
+ if (runtime.client instanceof RemoteHerdrClient) runtime.client.close();
202
+ }
203
+ this.runtimes.clear();
204
+ renderAgentWidget(this.context, [], []);
205
+ this.context = undefined;
206
+ }
207
+
208
+ isActive(): boolean {
209
+ return this.context !== undefined;
210
+ }
211
+
212
+ async reload(): Promise<void> {
213
+ const ctx = this.context;
214
+ if (!ctx) return;
215
+ const generation = this.generation;
216
+ const config = await readMachinesConfig();
217
+ if (!this.isCurrent(generation, ctx)) return;
218
+ const reconnect: string[] = [];
219
+
220
+ for (const [name, runtime] of this.runtimes) {
221
+ if (runtime.local || Object.hasOwn(config.machines, name)) continue;
222
+ runtime.monitor?.deactivate();
223
+ if (runtime.client instanceof RemoteHerdrClient) runtime.client.close();
224
+ this.runtimes.delete(name);
225
+ }
226
+ for (const [name, machineConfig] of Object.entries(config.machines)) {
227
+ const runtime = this.runtimes.get(name);
228
+ if (runtime?.config && sameMachineConfig(runtime.config, machineConfig)) {
229
+ continue;
230
+ }
231
+ const pending = runtime?.monitor?.list() ?? runtime?.pending ?? [];
232
+ runtime?.monitor?.deactivate();
233
+ if (runtime?.client instanceof RemoteHerdrClient) runtime.client.close();
234
+ this.runtimes.set(name, {
235
+ config: machineConfig,
236
+ local: false,
237
+ pending,
238
+ status: "connecting",
239
+ });
240
+ reconnect.push(name);
241
+ }
242
+ this.config = config;
243
+ this.changed();
244
+ for (const name of reconnect) {
245
+ void this.connectMachine(name, generation, true);
246
+ }
247
+ }
248
+
249
+ statuses(): MachineStatus[] {
250
+ return [...this.runtimes.entries()].map(([name, runtime]) => ({
251
+ name,
252
+ local: runtime.local,
253
+ status: runtime.status,
254
+ ...(runtime.reason ? { reason: runtime.reason } : {}),
255
+ }));
256
+ }
257
+
258
+ list(): ScopedMonitoredAgent[] {
259
+ return [...this.runtimes.entries()].flatMap(([machine, runtime]) => {
260
+ const values = runtime.monitor?.list() ?? runtime.pending;
261
+ return values
262
+ .map((value) => parseMonitoredAgent(value))
263
+ .filter((value): value is MonitoredAgent => value !== undefined)
264
+ .map((agent) => ({ ...agent, machine }));
265
+ });
266
+ }
267
+
268
+ connected(machine?: string): ConnectedMachine {
269
+ const name = machine?.trim() || LOCAL_MACHINE;
270
+ const runtime = this.runtimes.get(name);
271
+ if (!runtime) {
272
+ throw new Error(
273
+ `unknown Herdr machine ${JSON.stringify(name)}; use list to see configured machines`,
274
+ );
275
+ }
276
+ if (runtime.status !== "connected" || !runtime.client || !runtime.monitor) {
277
+ throw new Error(
278
+ `Herdr machine ${JSON.stringify(name)} is ${runtime.status}${runtime.reason ? `: ${runtime.reason}` : ""}; run /herdr connect ${name} to retry`,
279
+ );
280
+ }
281
+ const remote =
282
+ runtime.client instanceof RemoteHerdrClient ? runtime.client : undefined;
283
+ return {
284
+ machine: name,
285
+ local: runtime.local,
286
+ client: runtime.client,
287
+ monitor: runtime.monitor,
288
+ fallbackCwd: runtime.local ? (this.context?.cwd ?? ".") : "~",
289
+ ...(remote
290
+ ? {
291
+ resolveDirectory: (value: string | undefined, fallback: string) =>
292
+ remote.directory(value, fallback),
293
+ }
294
+ : {}),
295
+ };
296
+ }
297
+
298
+ private isCurrent(generation: number, ctx: ExtensionContext): boolean {
299
+ return generation === this.generation && ctx === this.context;
300
+ }
301
+
302
+ async snapshots(machine?: string): Promise<MachineSnapshot[]> {
303
+ const selected = machine?.trim()
304
+ ? [this.statusFor(machine.trim())]
305
+ : this.statuses();
306
+ return Promise.all(
307
+ selected.map(async (status) => {
308
+ const runtime = this.runtimes.get(status.name);
309
+ if (
310
+ status.status !== "connected" ||
311
+ !runtime?.client ||
312
+ !runtime.monitor
313
+ )
314
+ return status;
315
+ const client = runtime.client;
316
+ const monitor = runtime.monitor;
317
+ try {
318
+ const snapshot = await getSnapshot(client);
319
+ if (
320
+ runtime.status !== "connected" ||
321
+ runtime.client !== client ||
322
+ runtime.monitor !== monitor ||
323
+ this.runtimes.get(status.name) !== runtime
324
+ ) {
325
+ return this.runtimes.has(status.name)
326
+ ? this.statusFor(status.name)
327
+ : status;
328
+ }
329
+ return {
330
+ ...status,
331
+ monitoredPaneIds: new Set(
332
+ monitor.list().map((record) => record.paneId),
333
+ ),
334
+ snapshot,
335
+ };
336
+ } catch (error) {
337
+ if (
338
+ runtime.status !== "connected" ||
339
+ runtime.client !== client ||
340
+ runtime.monitor !== monitor ||
341
+ this.runtimes.get(status.name) !== runtime
342
+ ) {
343
+ return this.runtimes.has(status.name)
344
+ ? this.statusFor(status.name)
345
+ : status;
346
+ }
347
+ return { ...status, snapshotError: errorMessage(error) };
348
+ }
349
+ }),
350
+ );
351
+ }
352
+
353
+ connect(machine?: string): string {
354
+ const target = machine?.trim();
355
+ if (target) {
356
+ const runtime = this.runtimes.get(target);
357
+ if (!runtime)
358
+ throw new Error(`unknown Herdr machine ${JSON.stringify(target)}`);
359
+ if (runtime.local) {
360
+ return `${target} is the local machine and is already connected`;
361
+ }
362
+ if (runtime.status === "connected") {
363
+ return `${target} is already connected`;
364
+ }
365
+ if (runtime.attempting || runtime.status === "connecting") {
366
+ return `${target} is already connecting`;
367
+ }
368
+ void this.connectMachine(target, this.generation, false);
369
+ return `Connecting to ${target}`;
370
+ }
371
+
372
+ const names = [...this.runtimes.entries()]
373
+ .filter(
374
+ ([, runtime]) =>
375
+ !runtime.local &&
376
+ runtime.status !== "connected" &&
377
+ !runtime.attempting,
378
+ )
379
+ .map(([name]) => name);
380
+ for (const name of names) {
381
+ void this.connectMachine(name, this.generation, false);
382
+ }
383
+ if (names.length > 0) {
384
+ return `Connecting to ${names.join(", ")}`;
385
+ }
386
+ const remotes = [...this.runtimes.entries()].filter(
387
+ ([, runtime]) => !runtime.local,
388
+ );
389
+ if (remotes.length === 0) {
390
+ return "No remote machines are configured";
391
+ }
392
+ const connecting = remotes
393
+ .filter(([, runtime]) => runtime.attempting)
394
+ .map(([name]) => name);
395
+ return connecting.length > 0
396
+ ? `Already connecting to ${connecting.join(", ")}`
397
+ : "All configured machines are connected";
398
+ }
399
+
400
+ private statusFor(name: string): MachineStatus {
401
+ const runtime = this.runtimes.get(name);
402
+ if (!runtime)
403
+ throw new Error(`unknown Herdr machine ${JSON.stringify(name)}`);
404
+ return {
405
+ name,
406
+ local: runtime.local,
407
+ status: runtime.status,
408
+ ...(runtime.reason ? { reason: runtime.reason } : {}),
409
+ };
410
+ }
411
+
412
+ private createMonitor(
413
+ machine: string,
414
+ runtime: Runtime,
415
+ client: HerdrConnection,
416
+ ): AgentMonitor {
417
+ return new AgentMonitor(this.pi, {
418
+ client,
419
+ machine,
420
+ onChange: () => this.changed(),
421
+ onRefresh: () => this.refresh(),
422
+ operatorPrefix: runtime.local ? "herdr" : operatorPrefix(runtime.config!),
423
+ onWarning: runtime.local
424
+ ? (message) => this.context?.ui.notify(message, "warning")
425
+ : (message) => {
426
+ if (this.runtimes.get(machine) === runtime) {
427
+ this.disconnected(machine, runtime, message);
428
+ }
429
+ },
430
+ reconnect: runtime.local,
431
+ ...(client instanceof RemoteHerdrClient ? { reader: client } : {}),
432
+ ...(runtime.local && process.env["HERDR_PANE_ID"]
433
+ ? { selfPaneId: process.env["HERDR_PANE_ID"] }
434
+ : {}),
435
+ });
436
+ }
437
+
438
+ private async connectMachine(
439
+ name: string,
440
+ generation: number,
441
+ initial: boolean,
442
+ ): Promise<void> {
443
+ const runtime = this.runtimes.get(name);
444
+ const ctx = this.context;
445
+ if (
446
+ !runtime?.config ||
447
+ runtime.local ||
448
+ runtime.status === "connected" ||
449
+ runtime.attempting ||
450
+ !ctx ||
451
+ generation !== this.generation
452
+ ) {
453
+ return;
454
+ }
455
+ runtime.attempting = true;
456
+ runtime.status = "connecting";
457
+ delete runtime.reason;
458
+ this.refresh();
459
+ let attached = false;
460
+ let client: RemoteHerdrClient | undefined;
461
+ try {
462
+ client = await RemoteHerdrClient.connect(runtime.config, (error) => {
463
+ if (runtime.client === client)
464
+ this.disconnected(name, runtime, error.message);
465
+ });
466
+ if (
467
+ !this.isCurrent(generation, ctx) ||
468
+ this.runtimes.get(name) !== runtime
469
+ ) {
470
+ client.close();
471
+ return;
472
+ }
473
+ await client.request("ping");
474
+ if (
475
+ !this.isCurrent(generation, ctx) ||
476
+ this.runtimes.get(name) !== runtime
477
+ ) {
478
+ client.close();
479
+ return;
480
+ }
481
+ const monitor = this.createMonitor(name, runtime, client);
482
+ runtime.client = client;
483
+ runtime.monitor = monitor;
484
+ attached = true;
485
+ await monitor.activate(ctx, runtime.pending);
486
+ if (
487
+ !this.isCurrent(generation, ctx) ||
488
+ this.runtimes.get(name) !== runtime ||
489
+ runtime.client !== client ||
490
+ runtime.monitor !== monitor
491
+ ) {
492
+ monitor.deactivate();
493
+ client.close();
494
+ return;
495
+ }
496
+ runtime.pending = [];
497
+ runtime.status = "connected";
498
+ delete runtime.attempting;
499
+ this.refresh();
500
+ if (!initial) ctx.ui.notify(`Connected to ${name}`, "info");
501
+ } catch (error) {
502
+ delete runtime.attempting;
503
+ client?.close();
504
+ if (generation !== this.generation || ctx !== this.context) return;
505
+ if (
506
+ this.runtimes.get(name) !== runtime ||
507
+ (attached && runtime.client !== client)
508
+ ) {
509
+ return;
510
+ }
511
+ this.disconnected(name, runtime, errorMessage(error));
512
+ }
513
+ }
514
+
515
+ private disconnected(name: string, runtime: Runtime, reason: string): void {
516
+ reason = errorMessage(reason);
517
+ if (runtime.status === "unavailable" && runtime.reason === reason) return;
518
+ if (runtime.monitor) {
519
+ runtime.pending = runtime.monitor.list();
520
+ runtime.monitor.deactivate();
521
+ }
522
+ if (runtime.client instanceof RemoteHerdrClient) runtime.client.close();
523
+ delete runtime.monitor;
524
+ delete runtime.client;
525
+ runtime.status = "unavailable";
526
+ delete runtime.attempting;
527
+ runtime.reason = reason;
528
+ this.changed();
529
+ this.context?.ui.notify(
530
+ `Shepherdr could not connect to ${name}: ${reason}\nRun /herdr connect ${name} to retry`,
531
+ "warning",
532
+ );
533
+ }
534
+
535
+ private changed(): void {
536
+ if (!this.context) return;
537
+ const agents = this.persistedAgents();
538
+ this.pi.appendEntry(MONITOR_STATE_TYPE, { agents });
539
+ this.refresh();
540
+ }
541
+
542
+ private refresh(): void {
543
+ if (!this.context) return;
544
+ renderAgentWidget(this.context, this.list(), this.statuses());
545
+ }
546
+
547
+ private persistedAgents(): Array<MonitoredAgent & { machine: string }> {
548
+ return [...this.runtimes.entries()].flatMap(([machine, runtime]) => {
549
+ const values = runtime.monitor?.list() ?? runtime.pending;
550
+ return values
551
+ .map((value) => parseMonitoredAgent(value))
552
+ .filter((value): value is MonitoredAgent => value !== undefined)
553
+ .map((value) => ({ ...value, machine }));
554
+ });
555
+ }
556
+ }
@@ -39,7 +39,16 @@ export function isHerdrErrorCode(error: unknown, code: string): boolean {
39
39
  );
40
40
  }
41
41
 
42
- export class HerdrClient {
42
+ export interface HerdrConnection {
43
+ request<T>(method: string, params?: object, timeoutMs?: number): Promise<T>;
44
+ subscribe(
45
+ subscriptions: object[],
46
+ onEvent: (event: HerdrEvent) => void,
47
+ onDisconnect: (error?: Error) => void,
48
+ ): Promise<() => void>;
49
+ }
50
+
51
+ export class HerdrClient implements HerdrConnection {
43
52
  readonly socketPath: string;
44
53
 
45
54
  constructor(socketPath = process.env["HERDR_SOCKET_PATH"]) {
package/src/herdr.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { HerdrClient } from "./herdr-client.js";
1
+ import type { HerdrConnection } from "./herdr-client.js";
2
2
  import type {
3
3
  AgentStatus,
4
4
  PaneInfo,
@@ -15,7 +15,7 @@ const AGENT_STATUSES: ReadonlySet<string> = new Set([
15
15
  ]);
16
16
 
17
17
  export async function getSnapshot(
18
- client: HerdrClient,
18
+ client: HerdrConnection,
19
19
  ): Promise<SessionSnapshot> {
20
20
  const result = record(
21
21
  await client.request<unknown>("session.snapshot", {}),
@@ -25,7 +25,7 @@ export async function getSnapshot(
25
25
  }
26
26
 
27
27
  export async function getAgent(
28
- client: HerdrClient,
28
+ client: HerdrConnection,
29
29
  target: string,
30
30
  ): Promise<PaneInfo> {
31
31
  const result = record(
@@ -36,12 +36,13 @@ export async function getAgent(
36
36
  }
37
37
 
38
38
  export async function resolvePiAgent(
39
- client: HerdrClient,
39
+ client: HerdrConnection,
40
40
  target: string,
41
+ controllingPaneId = process.env["HERDR_PANE_ID"],
41
42
  ): Promise<PaneInfo> {
42
43
  const agent = await getAgent(client, target);
43
44
  if (agent.agent !== "pi") throw new Error(`${target} is not a Pi agent`);
44
- if (agent.pane_id === process.env["HERDR_PANE_ID"]) {
45
+ if (controllingPaneId && agent.pane_id === controllingPaneId) {
45
46
  throw new Error("refusing to target the controlling Pi session");
46
47
  }
47
48
  return agent;