@howaboua/pi-shepherdr 0.1.5 → 0.2.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/src/fleet.ts CHANGED
@@ -6,16 +6,16 @@ import { getSnapshot } from "./herdr.js";
6
6
  import { HerdrClient, type HerdrConnection } from "./herdr-client.js";
7
7
  import {
8
8
  LOCAL_MACHINE,
9
- type MachinesConfig,
10
- type RemoteMachineConfig,
11
- readMachinesConfig,
12
- } from "./machines-config.js";
9
+ readMachineCatalog,
10
+ type SshMachine,
11
+ } from "./machine-catalog.js";
13
12
  import { AgentMonitor } from "./monitor.js";
14
13
  import { parseMonitoredAgent } from "./monitor-record.js";
15
14
  import { RemoteHerdrClient } from "./remote-client.js";
16
15
  import type {
17
16
  MachineStatus,
18
17
  MonitoredAgent,
18
+ MonitoringIssue,
19
19
  ScopedMonitoredAgent,
20
20
  SessionSnapshot,
21
21
  } from "./types.js";
@@ -26,9 +26,10 @@ const MONITOR_STATE_TYPE = "herdr-agents-monitor-state";
26
26
  interface Runtime {
27
27
  attempting?: boolean;
28
28
  client?: HerdrConnection;
29
- config?: RemoteMachineConfig;
29
+ config?: SshMachine;
30
30
  local: boolean;
31
31
  monitor?: AgentMonitor;
32
+ monitoringIssue?: MonitoringIssue;
32
33
  pending: unknown[];
33
34
  reason?: string;
34
35
  status: MachineStatus["status"];
@@ -61,41 +62,28 @@ function shellQuote(value: string): string {
61
62
  return `'${value.replaceAll("'", `'"'"'`)}'`;
62
63
  }
63
64
 
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
- );
65
+ function operatorPrefix(config: SshMachine): string {
66
+ return `ssh -T -o BatchMode=yes -- ${shellQuote(config.target)} herdr --session ${shellQuote(config.session)}`;
90
67
  }
91
68
 
92
69
  function savedAgents(ctx: ExtensionContext): unknown[] {
93
70
  let latest: unknown[] = [];
71
+ let version: unknown;
94
72
  for (const entry of ctx.sessionManager.getBranch()) {
95
73
  if (entry.type !== "custom" || entry.customType !== MONITOR_STATE_TYPE)
96
74
  continue;
97
- const data = entry.data as { agents?: unknown };
98
- if (Array.isArray(data?.agents)) latest = data.agents;
75
+ const data = entry.data as { version?: unknown; agents?: unknown };
76
+ if (Array.isArray(data?.agents)) {
77
+ latest = data.agents;
78
+ version = data.version;
79
+ }
80
+ }
81
+ if (latest.length > 0 && version !== 2) {
82
+ ctx.ui.notify(
83
+ "Cleared legacy Shepherdr watches; use watch to subscribe explicitly. Remote agents are unchanged.",
84
+ "warning",
85
+ );
86
+ return [];
99
87
  }
100
88
  return latest;
101
89
  }
@@ -118,7 +106,6 @@ function groupSaved(values: unknown[]): Map<string, unknown[]> {
118
106
  }
119
107
 
120
108
  export class AgentFleet {
121
- private config: MachinesConfig = { machines: {} };
122
109
  private context: ExtensionContext | undefined;
123
110
  private generation = 0;
124
111
  private readonly pi: ExtensionAPI;
@@ -132,14 +119,13 @@ export class AgentFleet {
132
119
  this.deactivate();
133
120
  const generation = this.generation;
134
121
  this.context = ctx;
135
- const config = await readMachinesConfig();
122
+ const catalog = await readMachineCatalog();
136
123
  if (!this.isCurrent(generation, ctx)) return;
137
- this.config = config;
124
+ const machines = Object.entries(catalog).filter(
125
+ ([, machine]) => machine.enabled,
126
+ );
138
127
  const grouped = groupSaved(savedAgents(ctx));
139
- const known = new Set([
140
- LOCAL_MACHINE,
141
- ...Object.keys(this.config.machines),
142
- ]);
128
+ const known = new Set([LOCAL_MACHINE, ...machines.map(([id]) => id)]);
143
129
  const orphaned = [...grouped.entries()]
144
130
  .filter(([machine]) => !known.has(machine))
145
131
  .reduce((count, [, records]) => count + records.length, 0);
@@ -156,7 +142,7 @@ export class AgentFleet {
156
142
  status: "connecting",
157
143
  };
158
144
  this.runtimes.set(LOCAL_MACHINE, localRuntime);
159
- for (const [name, config] of Object.entries(this.config.machines)) {
145
+ for (const [name, config] of machines) {
160
146
  this.runtimes.set(name, {
161
147
  config,
162
148
  local: false,
@@ -187,9 +173,9 @@ export class AgentFleet {
187
173
  }
188
174
  localRuntime.pending = [];
189
175
  localRuntime.status = "connected";
190
- this.refresh();
176
+ this.changed();
191
177
 
192
- for (const name of Object.keys(this.config.machines)) {
178
+ for (const [name] of machines) {
193
179
  void this.connectMachine(name, generation, true);
194
180
  }
195
181
  }
@@ -213,19 +199,25 @@ export class AgentFleet {
213
199
  const ctx = this.context;
214
200
  if (!ctx) return;
215
201
  const generation = this.generation;
216
- const config = await readMachinesConfig();
202
+ const catalog = await readMachineCatalog();
217
203
  if (!this.isCurrent(generation, ctx)) return;
218
204
  const reconnect: string[] = [];
219
205
 
220
206
  for (const [name, runtime] of this.runtimes) {
221
- if (runtime.local || Object.hasOwn(config.machines, name)) continue;
207
+ if (runtime.local || catalog[name]?.enabled) continue;
222
208
  runtime.monitor?.deactivate();
223
209
  if (runtime.client instanceof RemoteHerdrClient) runtime.client.close();
224
210
  this.runtimes.delete(name);
225
211
  }
226
- for (const [name, machineConfig] of Object.entries(config.machines)) {
212
+ for (const [name, machineConfig] of Object.entries(catalog)) {
213
+ if (!machineConfig.enabled) continue;
227
214
  const runtime = this.runtimes.get(name);
228
- if (runtime?.config && sameMachineConfig(runtime.config, machineConfig)) {
215
+ if (
216
+ runtime?.config &&
217
+ runtime.config.target === machineConfig.target &&
218
+ runtime.config.session === machineConfig.session
219
+ ) {
220
+ runtime.config = machineConfig;
229
221
  continue;
230
222
  }
231
223
  const pending = runtime?.monitor?.list() ?? runtime?.pending ?? [];
@@ -239,7 +231,6 @@ export class AgentFleet {
239
231
  });
240
232
  reconnect.push(name);
241
233
  }
242
- this.config = config;
243
234
  this.changed();
244
235
  for (const name of reconnect) {
245
236
  void this.connectMachine(name, generation, true);
@@ -247,12 +238,7 @@ export class AgentFleet {
247
238
  }
248
239
 
249
240
  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
- }));
241
+ return [...this.runtimes.keys()].map((name) => this.statusFor(name));
256
242
  }
257
243
 
258
244
  list(): ScopedMonitoredAgent[] {
@@ -305,7 +291,7 @@ export class AgentFleet {
305
291
  : this.statuses();
306
292
  return Promise.all(
307
293
  selected.map(async (status) => {
308
- const runtime = this.runtimes.get(status.name);
294
+ const runtime = this.runtimes.get(status.id);
309
295
  if (
310
296
  status.status !== "connected" ||
311
297
  !runtime?.client ||
@@ -320,10 +306,10 @@ export class AgentFleet {
320
306
  runtime.status !== "connected" ||
321
307
  runtime.client !== client ||
322
308
  runtime.monitor !== monitor ||
323
- this.runtimes.get(status.name) !== runtime
309
+ this.runtimes.get(status.id) !== runtime
324
310
  ) {
325
- return this.runtimes.has(status.name)
326
- ? this.statusFor(status.name)
311
+ return this.runtimes.has(status.id)
312
+ ? this.statusFor(status.id)
327
313
  : status;
328
314
  }
329
315
  return {
@@ -338,10 +324,10 @@ export class AgentFleet {
338
324
  runtime.status !== "connected" ||
339
325
  runtime.client !== client ||
340
326
  runtime.monitor !== monitor ||
341
- this.runtimes.get(status.name) !== runtime
327
+ this.runtimes.get(status.id) !== runtime
342
328
  ) {
343
- return this.runtimes.has(status.name)
344
- ? this.statusFor(status.name)
329
+ return this.runtimes.has(status.id)
330
+ ? this.statusFor(status.id)
345
331
  : status;
346
332
  }
347
333
  return { ...status, snapshotError: errorMessage(error) };
@@ -356,6 +342,12 @@ export class AgentFleet {
356
342
  const runtime = this.runtimes.get(target);
357
343
  if (!runtime)
358
344
  throw new Error(`unknown Herdr machine ${JSON.stringify(target)}`);
345
+ if (runtime.status === "connected" && runtime.monitoringIssue) {
346
+ if (runtime.attempting)
347
+ return `Already retrying monitoring on ${target}`;
348
+ void this.retryMonitoring(target, runtime);
349
+ return `Retrying monitoring on ${target}`;
350
+ }
359
351
  if (runtime.local) {
360
352
  return `${target} is the local machine and is already connected`;
361
353
  }
@@ -369,6 +361,14 @@ export class AgentFleet {
369
361
  return `Connecting to ${target}`;
370
362
  }
371
363
 
364
+ const retries = [...this.runtimes.entries()].filter(
365
+ ([, runtime]) =>
366
+ runtime.status === "connected" &&
367
+ runtime.monitoringIssue &&
368
+ !runtime.attempting,
369
+ );
370
+ for (const [name, runtime] of retries)
371
+ void this.retryMonitoring(name, runtime);
372
372
  const names = [...this.runtimes.entries()]
373
373
  .filter(
374
374
  ([, runtime]) =>
@@ -380,8 +380,15 @@ export class AgentFleet {
380
380
  for (const name of names) {
381
381
  void this.connectMachine(name, this.generation, false);
382
382
  }
383
- if (names.length > 0) {
384
- return `Connecting to ${names.join(", ")}`;
383
+ if (names.length > 0 || retries.length > 0) {
384
+ return [
385
+ retries.length > 0
386
+ ? `Retrying monitoring on ${retries.map(([name]) => name).join(", ")}`
387
+ : "",
388
+ names.length > 0 ? `Connecting to ${names.join(", ")}` : "",
389
+ ]
390
+ .filter(Boolean)
391
+ .join(". ");
385
392
  }
386
393
  const remotes = [...this.runtimes.entries()].filter(
387
394
  ([, runtime]) => !runtime.local,
@@ -402,9 +409,19 @@ export class AgentFleet {
402
409
  if (!runtime)
403
410
  throw new Error(`unknown Herdr machine ${JSON.stringify(name)}`);
404
411
  return {
405
- name,
412
+ id: name,
406
413
  local: runtime.local,
414
+ ...(runtime.config
415
+ ? {
416
+ label: runtime.config.label,
417
+ target: runtime.config.target,
418
+ session: runtime.config.session,
419
+ }
420
+ : {}),
407
421
  status: runtime.status,
422
+ ...(runtime.monitoringIssue
423
+ ? { monitoringIssue: runtime.monitoringIssue }
424
+ : {}),
408
425
  ...(runtime.reason ? { reason: runtime.reason } : {}),
409
426
  };
410
427
  }
@@ -417,16 +434,37 @@ export class AgentFleet {
417
434
  return new AgentMonitor(this.pi, {
418
435
  client,
419
436
  machine,
437
+ machineLabel: () => runtime.config?.label ?? LOCAL_MACHINE,
420
438
  onChange: () => this.changed(),
421
439
  onRefresh: () => this.refresh(),
422
440
  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
- },
441
+ onWarning: (issue) => {
442
+ if (this.runtimes.get(machine) !== runtime) return;
443
+ if (!runtime.local && issue.state === "unavailable") {
444
+ this.disconnected(machine, runtime, issue.message);
445
+ return;
446
+ }
447
+ runtime.monitoringIssue = {
448
+ ...issue,
449
+ message: errorMessage(issue.message),
450
+ };
451
+ this.refresh();
452
+ this.context?.ui.notify(
453
+ `${machine}: ${issue.message}${runtime.local ? "" : `\nRun /herdr connect ${machine} to retry`}`,
454
+ "warning",
455
+ );
456
+ },
457
+ onRecovered: () => {
458
+ if (this.runtimes.get(machine) !== runtime || !runtime.monitoringIssue)
459
+ return;
460
+ delete runtime.monitoringIssue;
461
+ this.refresh();
462
+ if (runtime.monitor?.list().length)
463
+ this.context?.ui.notify(
464
+ `Herdr monitoring restored: ${machine}`,
465
+ "info",
466
+ );
467
+ },
430
468
  reconnect: runtime.local,
431
469
  ...(client instanceof RemoteHerdrClient ? { reader: client } : {}),
432
470
  ...(runtime.local && process.env["HERDR_PANE_ID"]
@@ -435,6 +473,31 @@ export class AgentFleet {
435
473
  });
436
474
  }
437
475
 
476
+ private async retryMonitoring(name: string, runtime: Runtime): Promise<void> {
477
+ const monitor = runtime.monitor;
478
+ const ctx = this.context;
479
+ const generation = this.generation;
480
+ if (!monitor || !ctx || runtime.attempting) return;
481
+ runtime.attempting = true;
482
+ try {
483
+ await monitor.retryMonitoring();
484
+ } catch (error) {
485
+ if (
486
+ this.isCurrent(generation, ctx) &&
487
+ this.runtimes.get(name) === runtime &&
488
+ runtime.monitor === monitor
489
+ ) {
490
+ ctx.ui.notify(
491
+ `Monitoring retry failed on ${name}: ${errorMessage(error)}`,
492
+ "warning",
493
+ );
494
+ }
495
+ } finally {
496
+ if (this.runtimes.get(name) === runtime && runtime.monitor === monitor)
497
+ delete runtime.attempting;
498
+ }
499
+ }
500
+
438
501
  private async connectMachine(
439
502
  name: string,
440
503
  generation: number,
@@ -478,11 +541,12 @@ export class AgentFleet {
478
541
  client.close();
479
542
  return;
480
543
  }
544
+ const pending = runtime.monitor?.list() ?? runtime.pending;
481
545
  const monitor = this.createMonitor(name, runtime, client);
482
546
  runtime.client = client;
483
547
  runtime.monitor = monitor;
484
548
  attached = true;
485
- await monitor.activate(ctx, runtime.pending);
549
+ await monitor.activate(ctx, pending);
486
550
  if (
487
551
  !this.isCurrent(generation, ctx) ||
488
552
  this.runtimes.get(name) !== runtime ||
@@ -500,6 +564,18 @@ export class AgentFleet {
500
564
  if (!initial) ctx.ui.notify(`Connected to ${name}`, "info");
501
565
  } catch (error) {
502
566
  delete runtime.attempting;
567
+ if (
568
+ this.isCurrent(generation, ctx) &&
569
+ this.runtimes.get(name) === runtime &&
570
+ runtime.client === client &&
571
+ runtime.monitor &&
572
+ runtime.monitoringIssue?.state === "degraded"
573
+ ) {
574
+ runtime.pending = [];
575
+ runtime.status = "connected";
576
+ this.refresh();
577
+ return;
578
+ }
503
579
  client?.close();
504
580
  if (generation !== this.generation || ctx !== this.context) return;
505
581
  if (
@@ -515,19 +591,18 @@ export class AgentFleet {
515
591
  private disconnected(name: string, runtime: Runtime, reason: string): void {
516
592
  reason = errorMessage(reason);
517
593
  if (runtime.status === "unavailable" && runtime.reason === reason) return;
518
- if (runtime.monitor) {
519
- runtime.pending = runtime.monitor.list();
520
- runtime.monitor.deactivate();
521
- }
594
+ // Keep the stopped owner until reconnect so in-flight dispatch cleanup
595
+ // updates the state we persist, rather than a detached snapshot.
596
+ runtime.monitor?.deactivate();
522
597
  if (runtime.client instanceof RemoteHerdrClient) runtime.client.close();
523
- delete runtime.monitor;
524
598
  delete runtime.client;
599
+ delete runtime.monitoringIssue;
525
600
  runtime.status = "unavailable";
526
601
  delete runtime.attempting;
527
602
  runtime.reason = reason;
528
603
  this.changed();
529
604
  this.context?.ui.notify(
530
- `Shepherdr could not connect to ${name}: ${reason}\nRun /herdr connect ${name} to retry`,
605
+ `Shepherdr unavailable on ${name}: ${reason}\nRun /herdr connect ${name} to retry`,
531
606
  "warning",
532
607
  );
533
608
  }
@@ -535,7 +610,7 @@ export class AgentFleet {
535
610
  private changed(): void {
536
611
  if (!this.context) return;
537
612
  const agents = this.persistedAgents();
538
- this.pi.appendEntry(MONITOR_STATE_TYPE, { agents });
613
+ this.pi.appendEntry(MONITOR_STATE_TYPE, { version: 2, agents });
539
614
  this.refresh();
540
615
  }
541
616
 
@@ -45,6 +45,7 @@ export interface HerdrConnection {
45
45
  subscriptions: object[],
46
46
  onEvent: (event: HerdrEvent) => void,
47
47
  onDisconnect: (error?: Error) => void,
48
+ signal?: AbortSignal,
48
49
  ): Promise<() => void>;
49
50
  }
50
51
 
@@ -129,6 +130,7 @@ export class HerdrClient implements HerdrConnection {
129
130
  subscriptions: object[],
130
131
  onEvent: (event: HerdrEvent) => void,
131
132
  onDisconnect: (error?: Error) => void,
133
+ signal?: AbortSignal,
132
134
  ): Promise<() => void> {
133
135
  return new Promise((resolve, reject) => {
134
136
  const id = `pi-shepherdr:subscribe:${crypto.randomUUID()}`;
@@ -138,21 +140,35 @@ export class HerdrClient implements HerdrConnection {
138
140
  let disconnected = false;
139
141
  const socket = createConnection(socketEndpoint(this.socketPath));
140
142
  socket.setEncoding("utf8");
141
- const timer = setTimeout(() => {
142
- const error = new Error("Herdr events.subscribe timed out");
143
- socket.destroy();
144
- reject(error);
145
- }, 10_000);
143
+ const timer = setTimeout(
144
+ () => disconnect(new Error("Herdr events.subscribe timed out")),
145
+ 10_000,
146
+ );
146
147
  timer.unref();
147
148
 
148
149
  const disconnect = (error?: Error) => {
149
150
  if (disconnected) return;
150
151
  disconnected = true;
151
152
  clearTimeout(timer);
153
+ signal?.removeEventListener("abort", abort);
154
+ socket.destroy();
152
155
  if (!acknowledged)
153
- reject(error ?? new Error("Herdr subscription disconnected"));
156
+ reject(
157
+ error ??
158
+ new Error("Herdr events.subscribe closed before acknowledgement"),
159
+ );
154
160
  else if (!closed) onDisconnect(error);
155
161
  };
162
+ const abort = () => {
163
+ closed = true;
164
+ disconnect(
165
+ signal?.reason instanceof Error
166
+ ? signal.reason
167
+ : new Error("Herdr subscription cancelled"),
168
+ );
169
+ };
170
+ signal?.addEventListener("abort", abort, { once: true });
171
+ if (signal?.aborted) abort();
156
172
 
157
173
  socket.on("connect", () => {
158
174
  socket.write(
@@ -163,6 +179,7 @@ export class HerdrClient implements HerdrConnection {
163
179
  socket.on("end", () => disconnect());
164
180
  socket.on("close", () => disconnect());
165
181
  socket.on("data", (chunk: string) => {
182
+ if (disconnected) return;
166
183
  buffer += chunk;
167
184
  if (buffer.length > MAX_FRAME_BUFFER) {
168
185
  disconnect(new Error("Herdr event frame is too large"));
@@ -212,7 +229,7 @@ export class HerdrClient implements HerdrConnection {
212
229
  clearTimeout(timer);
213
230
  resolve(() => {
214
231
  closed = true;
215
- socket.destroy();
232
+ disconnect();
216
233
  });
217
234
  continue;
218
235
  }
package/src/herdr.ts CHANGED
@@ -46,6 +46,21 @@ export async function getPane(
46
46
  return parsePaneInfo(result["pane"], "pane.get result.pane");
47
47
  }
48
48
 
49
+ export async function getCurrentPane(
50
+ client: HerdrConnection,
51
+ ): Promise<PaneInfo> {
52
+ const callerPaneId = process.env["HERDR_PANE_ID"];
53
+ if (!callerPaneId)
54
+ throw new Error("HERDR_PANE_ID is required to identify the sender");
55
+ const result = record(
56
+ await client.request<unknown>("pane.current", {
57
+ caller_pane_id: callerPaneId,
58
+ }),
59
+ "pane.current result",
60
+ );
61
+ return parsePaneInfo(result["pane"], "pane.current result.pane");
62
+ }
63
+
49
64
  export async function resolvePiAgent(
50
65
  client: HerdrConnection,
51
66
  target: string,
@@ -101,6 +116,7 @@ export function parsePaneInfo(value: unknown, path = "pane"): PaneInfo {
101
116
  ...optionalNullableString(pane, "foreground_cwd", path),
102
117
  ...optionalNullableString(pane, "label", path),
103
118
  ...optionalNullableString(pane, "name", path),
119
+ ...optionalNullableString(pane, "title", path),
104
120
  ...optionalBoolean(pane, "interactive_ready", path),
105
121
  ...optionalBoolean(pane, "launch_pending", path),
106
122
  ...parseAgentSession(pane["agent_session"], path),
@@ -182,7 +198,7 @@ function parseAgentSession(
182
198
  }
183
199
 
184
200
  function optionalNullableString<
185
- K extends "agent" | "cwd" | "foreground_cwd" | "label" | "name",
201
+ K extends "agent" | "cwd" | "foreground_cwd" | "label" | "name" | "title",
186
202
  >(
187
203
  value: Record<string, unknown>,
188
204
  key: K,
package/src/launch.ts CHANGED
@@ -8,7 +8,6 @@ import {
8
8
  resolveWorkspace,
9
9
  } from "./herdr.js";
10
10
  import { type HerdrConnection, isHerdrErrorCode } from "./herdr-client.js";
11
- import type { AgentMonitor } from "./monitor.js";
12
11
  import type { PaneInfo } from "./types.js";
13
12
 
14
13
  export const START_PLACEMENTS = ["new_workspace", "new_tab", "pane"] as const;
@@ -20,7 +19,6 @@ export interface StartAgentParams {
20
19
  name?: string;
21
20
  pane?: string;
22
21
  placement?: (typeof START_PLACEMENTS)[number];
23
- prompt?: string;
24
22
  workspace?: string;
25
23
  }
26
24
 
@@ -200,7 +198,6 @@ function nestedId(value: unknown, key: string, path: string): string {
200
198
 
201
199
  export async function startAgent(
202
200
  client: HerdrConnection,
203
- monitor: AgentMonitor,
204
201
  params: StartAgentParams,
205
202
  fallbackCwd: string,
206
203
  resolveDirectory: DirectoryResolver = directory,
@@ -234,25 +231,6 @@ export async function startAgent(
234
231
  } catch (error) {
235
232
  return rollbackCreatedLocation(client, created.cleanup, error);
236
233
  }
237
- try {
238
- await monitor.watch(agent);
239
- } catch (error) {
240
- return rollbackCreatedLocation(client, created.cleanup, error);
241
- }
242
- if (params.prompt?.trim()) {
243
- const prompt = params.prompt.trim();
244
- const attempt = monitor.beginWork(agent.pane_id, prompt);
245
- try {
246
- await client.request("agent.prompt", {
247
- target: agent.pane_id,
248
- text: prompt,
249
- });
250
- monitor.acceptWork(attempt);
251
- } catch (error) {
252
- await monitor.handleWorkFailure(attempt, error);
253
- throw error;
254
- }
255
- }
256
234
  return {
257
235
  agent,
258
236
  ...(created.cleanup ? { cleanup: created.cleanup } : {}),
@@ -262,12 +240,9 @@ export async function startAgent(
262
240
 
263
241
  export async function rollbackStartedAgent(
264
242
  client: HerdrConnection,
265
- monitor: AgentMonitor,
266
243
  started: StartedAgent,
267
244
  cause: unknown,
268
245
  ): Promise<never> {
269
- if (!started.cleanup) throw cause;
270
- await monitor.unwatch(started.id).catch(() => undefined);
271
246
  return rollbackCreatedLocation(client, started.cleanup, cause);
272
247
  }
273
248
 
@@ -0,0 +1,60 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import { type Static, Type } from "typebox";
4
+ import { Check } from "typebox/value";
5
+
6
+ export const LOCAL_MACHINE = "local";
7
+
8
+ const Machine = Type.Object({
9
+ id: Type.String({ pattern: "^[a-f0-9]{32}$" }),
10
+ label: Type.String({ minLength: 1, pattern: "^[^\\x00-\\x1f\\x7f]+$" }),
11
+ target: Type.String({
12
+ minLength: 1,
13
+ pattern: "^[^-\\x00-\\x1f\\x7f][^\\x00-\\x1f\\x7f]*$",
14
+ }),
15
+ session: Type.String({
16
+ minLength: 1,
17
+ maxLength: 64,
18
+ pattern: "^[a-zA-Z0-9_.-]+$",
19
+ }),
20
+ enabled: Type.Boolean(),
21
+ });
22
+ const Catalog = Type.Array(Machine);
23
+ export type SshMachine = Static<typeof Machine>;
24
+
25
+ export async function readMachineCatalog(): Promise<
26
+ Record<string, SshMachine>
27
+ > {
28
+ let stdout: string;
29
+ try {
30
+ ({ stdout } = await promisify(execFile)(
31
+ process.env["HERDR_BIN_PATH"]?.trim() || "herdr",
32
+ ["machine", "list", "--json"],
33
+ {
34
+ timeout: 10_000,
35
+ maxBuffer: 1024 * 1024,
36
+ encoding: "utf8",
37
+ },
38
+ ));
39
+ } catch (error) {
40
+ throw new Error(
41
+ `Could not read Herdr machines; requires Herdr 0.9 or newer: ${error instanceof Error ? error.message : String(error)}`,
42
+ );
43
+ }
44
+ let value: unknown;
45
+ try {
46
+ value = JSON.parse(stdout);
47
+ } catch {
48
+ throw new Error("Herdr machine list returned invalid JSON");
49
+ }
50
+ if (
51
+ !Check(Catalog, value) ||
52
+ value.some((machine) => machine.session === "." || machine.session === "..")
53
+ ) {
54
+ throw new Error("Herdr machine list returned an invalid catalog");
55
+ }
56
+ if (new Set(value.map((machine) => machine.id)).size !== value.length) {
57
+ throw new Error("Herdr machine list returned duplicate profile IDs");
58
+ }
59
+ return Object.fromEntries(value.map((machine) => [machine.id, machine]));
60
+ }