@howaboua/pi-shepherdr 0.1.4 → 0.1.6

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/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # @howaboua/pi-shepherdr
2
2
 
3
+ ## 0.1.6
4
+
5
+ - Deliver blocked-agent handoffs even when transcripts are unavailable.
6
+
7
+ - Reviewer spawns wait for their result before the controller continues.
8
+ - Implementation subagents are instructed to work directly rather than delegate implementation again.
9
+ - Discover and answer Pi Ask questions called inside Code and Notebook Mode.
10
+ - Retain working local and remote monitoring during connection updates, distinguish incomplete coverage from disconnection, and report recovery.
11
+ - Worker states now show their last-known status during incomplete monitoring. `/herdr connect` retries without replacing a working remote connection.
12
+ - Catch worker completions during reconnect setup and cancel obsolete or stopped monitoring connections.
13
+
14
+ ## 0.1.5
15
+
16
+ - Make the agents tool always available and start fleet monitoring automatically. `/herdr` now toggles only orchestration guidance, not tool availability.
17
+
3
18
  ## 0.1.4
4
19
 
5
20
  - Preserve extension-owned messages while delivering true developer-role policy through compatible Pi Codex Responses adapters.
package/README.md CHANGED
@@ -26,15 +26,15 @@ Pi Codex 3.0.25 or newer is optional. Without it, Shepherdr remains a normal Pi
26
26
 
27
27
  ## Enable orchestration
28
28
 
29
- Pi sessions remain ordinary workers until explicitly promoted. Run Pi inside Herdr, then activate the agent tool and orchestration guidance for the current session:
29
+ The agent tool is always available in Pi, Code Mode and Notebook Mode. Run Pi inside Herdr to connect the fleet and start monitoring automatically. To prioritize orchestration over direct work for the current session:
30
30
 
31
31
  ```text
32
32
  /herdr
33
33
  ```
34
34
 
35
- The command records one visible mode message without triggering a turn. Run `/herdr` again to return to normal guidance while keeping the agent tool available. Resumed controller sessions restore their last mode; new worker sessions in the same directory remain dormant.
35
+ The command only records one visible guidance message without triggering a turn. Run `/herdr` again to return to normal guidance. Resumed sessions restore their last mode; new sessions start with normal guidance. Tool availability and monitoring do not depend on this mode.
36
36
 
37
- `/herdr machines` opens the Add/Remove Machine interface. Settings live at `<pi-agent-directory>/shepherdr.json`, where the directory defaults to `~/.pi/agent` and `PI_CODING_AGENT_DIR` overrides it. `/herdr connect [machine]` retries configured remotes after activation.
37
+ `/herdr machines` opens the Add/Remove Machine interface. Settings live at `<pi-agent-directory>/shepherdr.json`, where the directory defaults to `~/.pi/agent` and `PI_CODING_AGENT_DIR` overrides it. `/herdr connect [machine]` retries failed connections or incomplete monitoring without dropping a working remote connection.
38
38
 
39
39
  Remote machines connect over noninteractive SSH. The target needs Node, Herdr 0.8.x, the Herdr Pi integration and a running Herdr session. Shepherdr installs one helper at `~/.pi/agent/shepherdr.mjs` on each remote, runs it only for the connection lifetime and leaves no remote daemon behind.
40
40
 
@@ -56,10 +56,14 @@ Call the `agents` tool with `action: "help"` before first use, then send flat re
56
56
 
57
57
  `spawn`, `send` and `answer` block by default. Set `blocking: false` only when the controller should continue other work immediately. Completion and blockage are then delivered automatically.
58
58
 
59
+ Reviewer spawns always block, even when `blocking: false` is supplied. The controller waits for the review before continuing work on its scope.
60
+
59
61
  Every `spawn` needs an `agent_type` and a concise two- or three-word `label`. The label names both the Herdr tab and Pi session; the routing `name` remains optional and is derived from it when omitted.
60
62
 
61
63
  Cancelling a blocking call does not kill its worker. The waiter detaches and the eventual result returns through normal asynchronous delivery.
62
64
 
65
+ For `answer` inside Code or Notebook Mode, update Pi Ask on workers together with Shepherdr on controllers.
66
+
63
67
  ## Profiles
64
68
 
65
69
  On first load, Shepherdr installs three editable profiles:
package/index.ts CHANGED
@@ -22,30 +22,23 @@ export default async function shepherdrExtension(
22
22
 
23
23
  registerAgentEventRenderer(pi);
24
24
  pi.registerTool(tool);
25
- const registration = await registerAgentsInCodeMode(pi, tool, fleet);
26
- registerAgentController(pi, fleet, {
27
- onActiveChange: () => registration?.refresh(),
28
- });
25
+ await registerAgentsInCodeMode(pi, tool);
26
+ registerAgentController(pi, fleet);
29
27
  }
30
28
 
31
29
  async function registerAgentsInCodeMode(
32
30
  pi: ExtensionAPI,
33
31
  tool: ReturnType<typeof createAgentsTool>,
34
- fleet: AgentFleet,
35
32
  ) {
36
33
  try {
37
34
  const { adaptToolForCodeMode, registerCodeModeExtensionTools } =
38
35
  await import("@howaboua/pi-codex-conversion/code-mode");
39
- const registration = registerCodeModeExtensionTools(
40
- pi,
41
- () => [
42
- adaptToolForCodeMode(tool, {
43
- blocking: isBlockingAgentsCall,
44
- usage: 'await tools.agents({ action: "help" }) // first call alone',
45
- }),
46
- ],
47
- { isActive: () => fleet.isActive() },
48
- );
36
+ const registration = registerCodeModeExtensionTools(pi, () => [
37
+ adaptToolForCodeMode(tool, {
38
+ blocking: isBlockingAgentsCall,
39
+ usage: 'await tools.agents({ action: "help" }) // first call alone',
40
+ }),
41
+ ]);
49
42
  pi.on("session_shutdown", () => registration.unregister());
50
43
  return registration;
51
44
  } catch (error) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@howaboua/pi-shepherdr",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
4
4
  "description": "Persistent blocking and asynchronous Pi agents through Herdr.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -43,7 +43,7 @@
43
43
  "pack:dry": "npm pack --dry-run"
44
44
  },
45
45
  "peerDependencies": {
46
- "@howaboua/pi-codex-conversion": ">=3.0.26",
46
+ "@howaboua/pi-codex-conversion": ">=3.0.30",
47
47
  "@earendil-works/pi-ai": ">=0.84.3",
48
48
  "@earendil-works/pi-coding-agent": ">=0.84.3",
49
49
  "@earendil-works/pi-tui": ">=0.84.3",
@@ -55,11 +55,11 @@
55
55
  }
56
56
  },
57
57
  "devDependencies": {
58
- "@howaboua/pi-codex-conversion": "3.0.26",
58
+ "@howaboua/pi-codex-conversion": "3.0.30",
59
59
  "@biomejs/biome": "^2.5.10",
60
- "@earendil-works/pi-ai": "0.85.0",
61
- "@earendil-works/pi-coding-agent": "0.85.0",
62
- "@earendil-works/pi-tui": "0.85.0",
60
+ "@earendil-works/pi-ai": "0.85.1",
61
+ "@earendil-works/pi-coding-agent": "0.85.1",
62
+ "@earendil-works/pi-tui": "0.85.1",
63
63
  "@types/node": "^26.2.0",
64
64
  "typebox": "1.3.18",
65
65
  "typescript": "^7.0.2"
@@ -1 +1 @@
1
- You are a general implementation agent. Complete the assigned task in the given directory, validate your work, and report the result.
1
+ You are the implementation subagent. Treat the task as the complete brief. Complete it in the given directory, validate your work, and report the result. Do not spawn implementation subagents.
@@ -135,8 +135,17 @@ export function parseAgentsRequest(input: unknown): AgentsParams {
135
135
  export function isBlockingAgentsCall(input: unknown): boolean {
136
136
  try {
137
137
  const value = parseAgentsRequest(input);
138
+ if (value.action === "spawn")
139
+ return shouldBlockAgentSpawn(value.agent_type, value.blocking);
138
140
  return BLOCKING_ACTIONS.has(value.action) && value.blocking !== false;
139
141
  } catch {
140
142
  return false;
141
143
  }
142
144
  }
145
+
146
+ export function shouldBlockAgentSpawn(
147
+ agentType: string | undefined,
148
+ blocking: boolean | undefined,
149
+ ): boolean {
150
+ return agentType?.trim() === "reviewer" || blocking !== false;
151
+ }
@@ -47,7 +47,7 @@ export async function agentsHelp(): Promise<Record<string, unknown>> {
47
47
  label: "2-3 words; tab/session",
48
48
  answers: "[{selections?:string[],other?:string,comment?:string}]",
49
49
  blocking:
50
- "true default; false only while continuing work; results push, never poll",
50
+ "reviewers always wait; otherwise false only for independent work; async results push, never poll",
51
51
  prompt:
52
52
  "Only task + inaccessible context; no method/evidence/reporting boilerplate",
53
53
  reuse:
@@ -5,6 +5,7 @@ import {
5
5
  type AgentsParams,
6
6
  type AgentsToolParams,
7
7
  parseAgentsRequest,
8
+ shouldBlockAgentSpawn,
8
9
  } from "./agents-contract.js";
9
10
  import {
10
11
  agentsHelp,
@@ -54,7 +55,7 @@ export function createAgentsTool(fleet: AgentFleet) {
54
55
  parameters: AgentsParameters,
55
56
  promptSnippet: "Load agents help before first use.",
56
57
  promptGuidelines: [
57
- "agents: Blocking is default; set blocking false only while continuing other work. Asynchronous settlement is pushed automatically, so never poll.",
58
+ "agents: Reviewer spawns always block. Await the review before continuing work on its scope. Set blocking false only for independent work.",
58
59
  "agents: Specialists know their job. Give only the concrete task and inaccessible context; never append generic method, evidence, or reporting instructions.",
59
60
  "agents: Reuse specialists only for the same investigation. Keep reviews independent. New scope gets a new agent.",
60
61
  "agents: For advanced Herdr workspace, pane, process or layout control, run herdr --skill.",
@@ -147,12 +148,13 @@ export function createAgentsTool(fleet: AgentFleet) {
147
148
  let promptSubmissionStarted = false;
148
149
  let promptAccepted = false;
149
150
  let settlement;
151
+ const blocking = shouldBlockAgentSpawn(profile.name, params.blocking);
150
152
  try {
151
153
  settlement = await dispatchAgentWork(
152
154
  runtime,
153
155
  started.agent,
154
156
  message,
155
- params.blocking !== false,
157
+ blocking,
156
158
  executionSignal,
157
159
  update,
158
160
  async () => {
package/src/controller.ts CHANGED
@@ -7,10 +7,6 @@ import type { AgentFleet } from "./fleet.js";
7
7
  import { showMachineMenu } from "./machine-menu.js";
8
8
  import { loadAgentProfiles } from "./profiles.js";
9
9
 
10
- interface AgentControllerOptions {
11
- onActiveChange?(): void;
12
- }
13
-
14
10
  const ORCHESTRATION_STATE_TYPE = "pi-shepherdr-orchestration-state";
15
11
  const GENERAL_ORCHESTRATION_MESSAGE =
16
12
  "Your main goal from now on is to orchestrate agents. Fan out suitable work to general agents, synthesize their results, and report the outcome. Work directly only when asked or for routine local tasks.";
@@ -21,13 +17,8 @@ const NORMAL_MESSAGE = "Work normally. Delegate only when useful or requested.";
21
17
  export function registerAgentController(
22
18
  pi: ExtensionAPI,
23
19
  fleet: AgentFleet,
24
- options: AgentControllerOptions = {},
25
20
  ): void {
26
21
  let orchestrationEnabled = false;
27
- const setActive = (active: boolean) => {
28
- setToolActive(pi, "agents", active);
29
- options.onActiveChange?.();
30
- };
31
22
  pi.registerCommand("herdr", {
32
23
  description: "Toggle agent orchestration or manage Herdr machines",
33
24
  getArgumentCompletions: (prefix) =>
@@ -38,13 +29,7 @@ export function registerAgentController(
38
29
  const [rawAction = "", ...rest] = args.trim().split(/\s+/);
39
30
  const action = rawAction.toLowerCase();
40
31
  if (!action) {
41
- orchestrationEnabled = restoreOrchestrationState(ctx).enabled;
42
- if (
43
- !fleet.isActive() &&
44
- !(await activateController(fleet, ctx, setActive))
45
- ) {
46
- return;
47
- }
32
+ orchestrationEnabled = restoreOrchestrationState(ctx);
48
33
  orchestrationEnabled = !orchestrationEnabled;
49
34
  sendPolicyMessage(
50
35
  pi,
@@ -72,8 +57,8 @@ export function registerAgentController(
72
57
  }
73
58
  if (action === "connect") {
74
59
  if (!fleet.isActive()) {
75
- ctx.ui.notify("Run /herdr to activate agents first", "warning");
76
- return;
60
+ await activateController(fleet, ctx);
61
+ if (!fleet.isActive()) return;
77
62
  }
78
63
  try {
79
64
  ctx.ui.notify(fleet.connect(rest[0]), "info");
@@ -90,11 +75,8 @@ export function registerAgentController(
90
75
  });
91
76
 
92
77
  pi.on("session_start", async (_event, ctx) => {
93
- const state = restoreOrchestrationState(ctx);
94
- orchestrationEnabled = state.enabled;
95
- fleet.deactivate();
96
- setActive(false);
97
- if (state.recorded) await activateController(fleet, ctx, setActive);
78
+ orchestrationEnabled = restoreOrchestrationState(ctx);
79
+ await activateController(fleet, ctx);
98
80
  });
99
81
 
100
82
  pi.on("session_shutdown", () => {
@@ -108,12 +90,8 @@ async function orchestrationMessage(): Promise<string> {
108
90
  : ORCHESTRATION_MESSAGE;
109
91
  }
110
92
 
111
- function restoreOrchestrationState(ctx: ExtensionContext): {
112
- enabled: boolean;
113
- recorded: boolean;
114
- } {
93
+ function restoreOrchestrationState(ctx: ExtensionContext): boolean {
115
94
  let enabled = false;
116
- let recorded = false;
117
95
  for (const entry of ctx.sessionManager.getBranch()) {
118
96
  if (
119
97
  (entry.type !== "custom" && entry.type !== "custom_message") ||
@@ -129,52 +107,28 @@ function restoreOrchestrationState(ctx: ExtensionContext): {
129
107
  typeof state.enabled === "boolean"
130
108
  ) {
131
109
  enabled = state.enabled;
132
- recorded = true;
133
110
  }
134
111
  }
135
- return { enabled, recorded };
112
+ return enabled;
136
113
  }
137
114
 
138
115
  async function activateController(
139
116
  fleet: AgentFleet,
140
117
  ctx: ExtensionContext,
141
- setActive: (active: boolean) => void,
142
118
  ): Promise<boolean> {
143
119
  if (process.env["HERDR_ENV"] !== "1" || !process.env["HERDR_SOCKET_PATH"]) {
144
- setActive(false);
145
- ctx.ui.notify(
146
- "Agent orchestration requires Pi to run inside Herdr",
147
- "error",
148
- );
120
+ ctx.ui.notify("Shepherdr requires Pi to run inside Herdr", "error");
149
121
  return false;
150
122
  }
151
123
  try {
152
124
  await fleet.activate(ctx);
153
- setActive(true);
154
125
  return true;
155
126
  } catch (error) {
156
127
  fleet.deactivate();
157
- setActive(false);
158
128
  ctx.ui.notify(
159
- `Agent orchestration could not start: ${error instanceof Error ? error.message : String(error)}`,
129
+ `Shepherdr could not start: ${error instanceof Error ? error.message : String(error)}`,
160
130
  "error",
161
131
  );
162
132
  return false;
163
133
  }
164
134
  }
165
-
166
- function setToolActive(
167
- pi: ExtensionAPI,
168
- toolName: string,
169
- active: boolean,
170
- ): void {
171
- const current = pi.getActiveTools();
172
- const withoutTool = current.filter((name) => name !== toolName);
173
- const next = active ? [...withoutTool, toolName] : withoutTool;
174
- if (
175
- next.length !== current.length ||
176
- next.some((name, index) => name !== current[index])
177
- ) {
178
- pi.setActiveTools(next);
179
- }
180
- }
package/src/fleet.ts CHANGED
@@ -16,6 +16,7 @@ import { RemoteHerdrClient } from "./remote-client.js";
16
16
  import type {
17
17
  MachineStatus,
18
18
  MonitoredAgent,
19
+ MonitoringIssue,
19
20
  ScopedMonitoredAgent,
20
21
  SessionSnapshot,
21
22
  } from "./types.js";
@@ -29,6 +30,7 @@ interface Runtime {
29
30
  config?: RemoteMachineConfig;
30
31
  local: boolean;
31
32
  monitor?: AgentMonitor;
33
+ monitoringIssue?: MonitoringIssue;
32
34
  pending: unknown[];
33
35
  reason?: string;
34
36
  status: MachineStatus["status"];
@@ -247,12 +249,7 @@ export class AgentFleet {
247
249
  }
248
250
 
249
251
  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
- }));
252
+ return [...this.runtimes.keys()].map((name) => this.statusFor(name));
256
253
  }
257
254
 
258
255
  list(): ScopedMonitoredAgent[] {
@@ -356,6 +353,12 @@ export class AgentFleet {
356
353
  const runtime = this.runtimes.get(target);
357
354
  if (!runtime)
358
355
  throw new Error(`unknown Herdr machine ${JSON.stringify(target)}`);
356
+ if (runtime.status === "connected" && runtime.monitoringIssue) {
357
+ if (runtime.attempting)
358
+ return `Already retrying monitoring on ${target}`;
359
+ void this.retryMonitoring(target, runtime);
360
+ return `Retrying monitoring on ${target}`;
361
+ }
359
362
  if (runtime.local) {
360
363
  return `${target} is the local machine and is already connected`;
361
364
  }
@@ -369,6 +372,14 @@ export class AgentFleet {
369
372
  return `Connecting to ${target}`;
370
373
  }
371
374
 
375
+ const retries = [...this.runtimes.entries()].filter(
376
+ ([, runtime]) =>
377
+ runtime.status === "connected" &&
378
+ runtime.monitoringIssue &&
379
+ !runtime.attempting,
380
+ );
381
+ for (const [name, runtime] of retries)
382
+ void this.retryMonitoring(name, runtime);
372
383
  const names = [...this.runtimes.entries()]
373
384
  .filter(
374
385
  ([, runtime]) =>
@@ -380,8 +391,15 @@ export class AgentFleet {
380
391
  for (const name of names) {
381
392
  void this.connectMachine(name, this.generation, false);
382
393
  }
383
- if (names.length > 0) {
384
- return `Connecting to ${names.join(", ")}`;
394
+ if (names.length > 0 || retries.length > 0) {
395
+ return [
396
+ retries.length > 0
397
+ ? `Retrying monitoring on ${retries.map(([name]) => name).join(", ")}`
398
+ : "",
399
+ names.length > 0 ? `Connecting to ${names.join(", ")}` : "",
400
+ ]
401
+ .filter(Boolean)
402
+ .join(". ");
385
403
  }
386
404
  const remotes = [...this.runtimes.entries()].filter(
387
405
  ([, runtime]) => !runtime.local,
@@ -405,6 +423,9 @@ export class AgentFleet {
405
423
  name,
406
424
  local: runtime.local,
407
425
  status: runtime.status,
426
+ ...(runtime.monitoringIssue
427
+ ? { monitoringIssue: runtime.monitoringIssue }
428
+ : {}),
408
429
  ...(runtime.reason ? { reason: runtime.reason } : {}),
409
430
  };
410
431
  }
@@ -420,13 +441,33 @@ export class AgentFleet {
420
441
  onChange: () => this.changed(),
421
442
  onRefresh: () => this.refresh(),
422
443
  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
- },
444
+ onWarning: (issue) => {
445
+ if (this.runtimes.get(machine) !== runtime) return;
446
+ if (!runtime.local && issue.state === "unavailable") {
447
+ this.disconnected(machine, runtime, issue.message);
448
+ return;
449
+ }
450
+ runtime.monitoringIssue = {
451
+ ...issue,
452
+ message: errorMessage(issue.message),
453
+ };
454
+ this.refresh();
455
+ this.context?.ui.notify(
456
+ `${machine}: ${issue.message}${runtime.local ? "" : `\nRun /herdr connect ${machine} to retry`}`,
457
+ "warning",
458
+ );
459
+ },
460
+ onRecovered: () => {
461
+ if (this.runtimes.get(machine) !== runtime || !runtime.monitoringIssue)
462
+ return;
463
+ delete runtime.monitoringIssue;
464
+ this.refresh();
465
+ if (runtime.monitor?.list().length)
466
+ this.context?.ui.notify(
467
+ `Herdr monitoring restored: ${machine}`,
468
+ "info",
469
+ );
470
+ },
430
471
  reconnect: runtime.local,
431
472
  ...(client instanceof RemoteHerdrClient ? { reader: client } : {}),
432
473
  ...(runtime.local && process.env["HERDR_PANE_ID"]
@@ -435,6 +476,31 @@ export class AgentFleet {
435
476
  });
436
477
  }
437
478
 
479
+ private async retryMonitoring(name: string, runtime: Runtime): Promise<void> {
480
+ const monitor = runtime.monitor;
481
+ const ctx = this.context;
482
+ const generation = this.generation;
483
+ if (!monitor || !ctx || runtime.attempting) return;
484
+ runtime.attempting = true;
485
+ try {
486
+ await monitor.retryMonitoring();
487
+ } catch (error) {
488
+ if (
489
+ this.isCurrent(generation, ctx) &&
490
+ this.runtimes.get(name) === runtime &&
491
+ runtime.monitor === monitor
492
+ ) {
493
+ ctx.ui.notify(
494
+ `Monitoring retry failed on ${name}: ${errorMessage(error)}`,
495
+ "warning",
496
+ );
497
+ }
498
+ } finally {
499
+ if (this.runtimes.get(name) === runtime && runtime.monitor === monitor)
500
+ delete runtime.attempting;
501
+ }
502
+ }
503
+
438
504
  private async connectMachine(
439
505
  name: string,
440
506
  generation: number,
@@ -500,6 +566,18 @@ export class AgentFleet {
500
566
  if (!initial) ctx.ui.notify(`Connected to ${name}`, "info");
501
567
  } catch (error) {
502
568
  delete runtime.attempting;
569
+ if (
570
+ this.isCurrent(generation, ctx) &&
571
+ this.runtimes.get(name) === runtime &&
572
+ runtime.client === client &&
573
+ runtime.monitor &&
574
+ runtime.monitoringIssue?.state === "degraded"
575
+ ) {
576
+ runtime.pending = [];
577
+ runtime.status = "connected";
578
+ this.refresh();
579
+ return;
580
+ }
503
581
  client?.close();
504
582
  if (generation !== this.generation || ctx !== this.context) return;
505
583
  if (
@@ -522,12 +600,13 @@ export class AgentFleet {
522
600
  if (runtime.client instanceof RemoteHerdrClient) runtime.client.close();
523
601
  delete runtime.monitor;
524
602
  delete runtime.client;
603
+ delete runtime.monitoringIssue;
525
604
  runtime.status = "unavailable";
526
605
  delete runtime.attempting;
527
606
  runtime.reason = reason;
528
607
  this.changed();
529
608
  this.context?.ui.notify(
530
- `Shepherdr could not connect to ${name}: ${reason}\nRun /herdr connect ${name} to retry`,
609
+ `Shepherdr unavailable on ${name}: ${reason}\nRun /herdr connect ${name} to retry`,
531
610
  "warning",
532
611
  );
533
612
  }
@@ -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
  }
@@ -6,6 +6,7 @@ import {
6
6
  readMachinesConfig,
7
7
  writeMachinesConfig,
8
8
  } from "./machines-config.js";
9
+ import type { MachineStatus } from "./types.js";
9
10
 
10
11
  function parseSshArguments(value: string): string[] {
11
12
  const parts: string[] = [];
@@ -64,7 +65,7 @@ export async function showMachineMenu(
64
65
  return undefined;
65
66
  });
66
67
  if (!config) return;
67
- const statuses = fleet.isActive()
68
+ const statuses: MachineStatus[] = fleet.isActive()
68
69
  ? fleet.statuses()
69
70
  : Object.keys(config.machines).map((name) => ({
70
71
  local: false,
@@ -77,7 +78,7 @@ export async function showMachineMenu(
77
78
  .filter((machine) => !machine.local)
78
79
  .map(
79
80
  (machine) =>
80
- `${machine.status === "connected" ? "●" : machine.status === "connecting" ? "◌" : "○"} ${machine.name} · ${machine.status}`,
81
+ `${machine.status === "connected" ? "●" : machine.status === "connecting" ? "◌" : "○"} ${machine.name} · ${machine.status}${machine.monitoringIssue ? " · monitoring needs attention" : ""}`,
81
82
  ),
82
83
  ]);
83
84
  if (!selected) return;
@@ -89,12 +90,16 @@ export async function showMachineMenu(
89
90
  if (!name) return;
90
91
  const status = statuses.find((machine) => machine.name === name);
91
92
  const action = await ctx.ui.select(name, [
93
+ ...(status?.monitoringIssue ? ["Retry monitoring"] : []),
92
94
  ...(status?.status !== "connected" ? ["Connect"] : []),
93
95
  "Remove",
94
96
  ]);
95
- if (action === "Connect") {
97
+ if (action === "Connect" || action === "Retry monitoring") {
96
98
  if (!fleet.isActive()) {
97
- ctx.ui.notify("Run /herdr to activate agents first", "warning");
99
+ ctx.ui.notify(
100
+ "Fleet unavailable; run /herdr connect to retry",
101
+ "warning",
102
+ );
98
103
  return;
99
104
  }
100
105
  ctx.ui.notify(fleet.connect(name), "info");