@howaboua/pi-shepherdr 0.2.23 → 0.2.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/CHANGELOG.md +7 -18
  2. package/README.md +63 -60
  3. package/biome.json +1 -1
  4. package/index.ts +2 -2
  5. package/package.json +14 -9
  6. package/src/agents-discovery.ts +41 -26
  7. package/src/agents-focus.ts +2 -2
  8. package/src/agents-reply.ts +1 -1
  9. package/src/agents-spawn.ts +2 -2
  10. package/src/agents-tool.ts +2 -2
  11. package/src/agents-work.ts +3 -3
  12. package/src/attachment-notes.ts +14 -2
  13. package/src/attachment-protocol.ts +21 -4
  14. package/src/attachment-routing.ts +1 -1
  15. package/src/attachment-target.ts +5 -2
  16. package/src/attachment.ts +2 -3
  17. package/src/board/host.ts +2 -2
  18. package/src/board/membership.ts +1 -1
  19. package/src/{control-panel-actions.ts → control-panel/actions.ts} +2 -2
  20. package/src/{control-panel.ts → control-panel/index.ts} +4 -4
  21. package/src/{control-panel-items.ts → control-panel/items.ts} +3 -3
  22. package/src/{control-panel-view.ts → control-panel/view.ts} +3 -3
  23. package/src/controller.ts +6 -3
  24. package/src/fleet/index.ts +384 -0
  25. package/src/fleet/inspection.ts +141 -0
  26. package/src/fleet/machine.ts +52 -0
  27. package/src/fleet/monitor.ts +71 -0
  28. package/src/fleet/persistence.ts +42 -0
  29. package/src/fleet/reconnect.ts +75 -0
  30. package/src/fleet/setup.ts +92 -0
  31. package/src/messages/attachments.ts +39 -0
  32. package/src/messages/attribution.ts +75 -0
  33. package/src/messages/event-details.ts +69 -0
  34. package/src/messages/events.ts +189 -0
  35. package/src/messages/focus.ts +38 -0
  36. package/src/messages/guidance.ts +83 -0
  37. package/src/messages/render.ts +89 -0
  38. package/src/messages/voice-announcements.ts +79 -0
  39. package/src/monitor.ts +2 -2
  40. package/src/peer-inbox.ts +2 -2
  41. package/src/remote/client.ts +127 -0
  42. package/src/remote/context-relay.ts +84 -0
  43. package/src/remote/deployment.ts +179 -0
  44. package/src/remote/focus-channels.ts +89 -0
  45. package/src/remote/transport.ts +369 -0
  46. package/src/settlement/collector.ts +122 -0
  47. package/src/settlement/delivery.ts +144 -0
  48. package/src/{settlement.ts → settlement/index.ts} +23 -233
  49. package/src/shared-context-host.ts +33 -11
  50. package/src/shared-context.ts +10 -4
  51. package/src/spawn-context.ts +20 -17
  52. package/src/voice-handoff.ts +1 -1
  53. package/src/worker-service.ts +2 -2
  54. package/src/fleet.ts +0 -702
  55. package/src/messages.ts +0 -637
  56. package/src/remote-client.ts +0 -761
@@ -1,11 +1,11 @@
1
1
  import type { AgentToolUpdateCallback } from "@earendil-works/pi-coding-agent";
2
2
  import { activityTask } from "./activity.js";
3
- import type { ConnectedMachine } from "./fleet.js";
3
+ import type { ConnectedMachine } from "./fleet/index.js";
4
4
  import { getSnapshot } from "./herdr.js";
5
5
  import { type HerdrConnection, isDispatchRejected } from "./herdr-client.js";
6
- import { agentSource } from "./messages.js";
6
+ import { agentSource } from "./messages/attribution.js";
7
7
  import type { WorkAttempt } from "./monitor-state.js";
8
- import type { ClaimedSettlement } from "./settlement.js";
8
+ import type { ClaimedSettlement } from "./settlement/index.js";
9
9
  import type { ExtensionReply, PaneInfo, PeerDelivery } from "./types.js";
10
10
 
11
11
  export function toolResult(value: Record<string, unknown>, warning?: string) {
@@ -4,7 +4,7 @@ import type {
4
4
  ContextSharingService,
5
5
  SharedContextRequest,
6
6
  SharedContextResult,
7
- } from "@howaboua/pi-codex-conversion/context-sharing";
7
+ } from "@howaboua/pi-notes-compaction/context-sharing";
8
8
 
9
9
  /** Read-only continuity when a live owner disappears. Parsing remains Conversion-owned. */
10
10
  export class AttachmentNotes {
@@ -174,7 +174,19 @@ export class AttachmentNotes {
174
174
  }),
175
175
  };
176
176
  return {
177
- content: [{ type: "text", text: JSON.stringify(details) }],
177
+ content: [
178
+ ...result.content,
179
+ {
180
+ type: "text",
181
+ text: `Read-only checkpoints captured ${details.captured_at}.${
182
+ detached
183
+ ? " Counterpart detached."
184
+ : unavailable
185
+ ? " Live owner and saved updates unavailable; these checkpoints may be stale. Resume the counterpart for current notes."
186
+ : " Live owner unavailable; reading saved checkpoints."
187
+ }`,
188
+ },
189
+ ],
178
190
  details: { codexHistoryNotes: details },
179
191
  };
180
192
  }
@@ -2,7 +2,7 @@ import { isDeepStrictEqual } from "node:util";
2
2
  import { Type } from "@earendil-works/pi-ai";
3
3
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
4
4
  import { BindingSchema } from "@howaboua/pi-agent-board/integration";
5
- import type { SharedContextResult } from "@howaboua/pi-codex-conversion/context-sharing";
5
+ import type { SharedContextResult } from "@howaboua/pi-notes-compaction/context-sharing";
6
6
  import type { Static, TSchema } from "typebox";
7
7
  import { Check } from "typebox/value";
8
8
 
@@ -115,8 +115,7 @@ export function remapResult(
115
115
  typeof result.details.codexHistoryNotes["encrypted_output"] === "string" ||
116
116
  ("externalNotesResponses" in result.details &&
117
117
  Array.isArray(result.details.externalNotesResponses) &&
118
- result.details.externalNotesResponses.length > 0) ||
119
- Object.keys(result.details.codexHistoryNotes).length === 0
118
+ result.details.externalNotesResponses.length > 0)
120
119
  ) {
121
120
  const hint = `Source ${from}, access through ${to}. Use ${to}/notes for note paths and ${to} for history agent_name`;
122
121
  // Ciphertext paths cannot be remapped. Preserve host-only provenance on the original details.
@@ -135,7 +134,25 @@ export function remapResult(
135
134
  ) as Record<string, unknown>;
136
135
  return {
137
136
  ...result,
138
- content: [{ type: "text", text: JSON.stringify(details) }],
137
+ // Remap the public payload, never regenerate it from private receipts.
138
+ content: result.content.map((item) => {
139
+ if (item.type !== "text") return item;
140
+ try {
141
+ return {
142
+ ...item,
143
+ text: JSON.stringify(
144
+ JSON.parse(item.text, (key, value: unknown) =>
145
+ (key === "path" || key === "agent_name") &&
146
+ typeof value === "string"
147
+ ? remap(value, from, to)
148
+ : value,
149
+ ),
150
+ ),
151
+ };
152
+ } catch {
153
+ return item;
154
+ }
155
+ }),
139
156
  details: { ...result.details, codexHistoryNotes: details },
140
157
  };
141
158
  }
@@ -4,7 +4,7 @@ import type {
4
4
  ContextSharingService,
5
5
  SharedContextRequest,
6
6
  SharedContextResult,
7
- } from "@howaboua/pi-codex-conversion/context-sharing";
7
+ } from "@howaboua/pi-notes-compaction/context-sharing";
8
8
  import type { AttachmentNotes } from "./attachment-notes.js";
9
9
  import {
10
10
  type AttachmentRoute,
@@ -4,7 +4,7 @@ import type {
4
4
  ExtensionContext,
5
5
  } from "@earendil-works/pi-coding-agent";
6
6
  import { binding } from "@howaboua/pi-agent-board/integration";
7
- import type { ContextSharingService } from "@howaboua/pi-codex-conversion/context-sharing";
7
+ import type { ContextSharingService } from "@howaboua/pi-notes-compaction/context-sharing";
8
8
  import type { Static } from "typebox";
9
9
  import { Check } from "typebox/value";
10
10
  import { AttachmentNotes } from "./attachment-notes.js";
@@ -21,7 +21,10 @@ import {
21
21
  } from "./attachment-protocol.js";
22
22
  import type { AgentBoard } from "./board/host.js";
23
23
  import { sendPolicyMessage } from "./delivery.js";
24
- import { attachmentMessage, detachmentMessage } from "./messages.js";
24
+ import {
25
+ attachmentMessage,
26
+ detachmentMessage,
27
+ } from "./messages/attachments.js";
25
28
 
26
29
  /** Validates and commits attachment membership in the settled target session. */
27
30
  export class AttachmentTarget {
package/src/attachment.ts CHANGED
@@ -5,7 +5,7 @@ import type {
5
5
  ExtensionContext,
6
6
  } from "@earendil-works/pi-coding-agent";
7
7
  import { binding } from "@howaboua/pi-agent-board/integration";
8
- import type { ContextSharingService } from "@howaboua/pi-codex-conversion/context-sharing";
8
+ import type { ContextSharingService } from "@howaboua/pi-notes-compaction/context-sharing";
9
9
  import type { Static } from "typebox";
10
10
  import { Check } from "typebox/value";
11
11
  import type { AgentsParams } from "./agents-contract.js";
@@ -20,7 +20,7 @@ import {
20
20
  import { AttachmentRouting } from "./attachment-routing.js";
21
21
  import { AttachmentTarget } from "./attachment-target.js";
22
22
  import type { AgentBoard } from "./board/host.js";
23
- import type { ConnectedMachine } from "./fleet.js";
23
+ import type { ConnectedMachine } from "./fleet/index.js";
24
24
  import { sessionPath } from "./herdr.js";
25
25
  import { sessionContextPath } from "./remote/shepherdr-context.mjs";
26
26
  import type { PaneInfo } from "./types.js";
@@ -202,7 +202,6 @@ export class AgentAttachment {
202
202
  ...(route.plan.board
203
203
  ? {
204
204
  boardAgent: route.plan.board.desired.agentName,
205
- previousBoard: route.plan.board.previous.boardId,
206
205
  }
207
206
  : {}),
208
207
  };
package/src/board/host.ts CHANGED
@@ -15,9 +15,9 @@ import {
15
15
  type BoardRuntime,
16
16
  discoverBoard,
17
17
  } from "@howaboua/pi-agent-board/runtime";
18
- import type { AgentFleet, ConnectedMachine } from "../fleet.js";
18
+ import type { AgentFleet, ConnectedMachine } from "../fleet/index.js";
19
19
  import { sessionPath } from "../herdr.js";
20
- import { boardBriefing, boardMigrationWarning } from "../messages.js";
20
+ import { boardBriefing, boardMigrationWarning } from "../messages/guidance.js";
21
21
  import {
22
22
  requestContext,
23
23
  sessionContextPath,
@@ -14,7 +14,7 @@ import {
14
14
  saveChild,
15
15
  saveMember,
16
16
  } from "@howaboua/pi-agent-board/integration";
17
- import type { ConnectedMachine } from "../fleet.js";
17
+ import type { ConnectedMachine } from "../fleet/index.js";
18
18
 
19
19
  function sameMembership(left: BoardBinding, right: BoardBinding) {
20
20
  return isDeepStrictEqual(
@@ -1,5 +1,5 @@
1
- import type { PanelOwners } from "./control-panel-items.js";
2
- import { type SshSetupDraft, sshSetupArgs } from "./ssh-setup.js";
1
+ import { type SshSetupDraft, sshSetupArgs } from "../ssh-setup.js";
2
+ import type { PanelOwners } from "./items.js";
3
3
 
4
4
  export interface PanelOptions extends PanelOwners {
5
5
  setOrchestration: (enabled: boolean, signal: AbortSignal) => Promise<void>;
@@ -1,8 +1,8 @@
1
1
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
- import { PanelActions, type PanelOptions } from "./control-panel-actions.js";
3
- import type { PanelTab as Tab } from "./control-panel-items.js";
4
- import { PanelView } from "./control-panel-view.js";
5
- import { addSshConnection, type SshSetupDraft } from "./ssh-setup.js";
2
+ import { addSshConnection, type SshSetupDraft } from "../ssh-setup.js";
3
+ import { PanelActions, type PanelOptions } from "./actions.js";
4
+ import type { PanelTab as Tab } from "./items.js";
5
+ import { PanelView } from "./view.js";
6
6
 
7
7
  export function controlPanelStatus(options: PanelOptions): string {
8
8
  return [
@@ -1,7 +1,7 @@
1
1
  import type { SettingItem } from "@earendil-works/pi-tui";
2
- import { commandConfigPath } from "./command-config.js";
3
- import type { AgentFleet } from "./fleet.js";
4
- import { type SshSetupDraft, sshSetupItems } from "./ssh-setup.js";
2
+ import { commandConfigPath } from "../command-config.js";
3
+ import type { AgentFleet } from "../fleet/index.js";
4
+ import { type SshSetupDraft, sshSetupItems } from "../ssh-setup.js";
5
5
 
6
6
  export const PANEL_TABS = ["Settings", "Status", "Connections"] as const;
7
7
  export type PanelTab = (typeof PANEL_TABS)[number];
@@ -14,14 +14,14 @@ import {
14
14
  truncateToWidth,
15
15
  wrapTextWithAnsi,
16
16
  } from "@earendil-works/pi-tui";
17
- import type { PanelActions } from "./control-panel-actions.js";
17
+ import type { SshSetupDraft } from "../ssh-setup.js";
18
+ import type { PanelActions } from "./actions.js";
18
19
  import {
19
20
  buildPanelItems,
20
21
  type PanelOwners,
21
22
  type PanelTab,
22
23
  PANEL_TABS as TABS,
23
- } from "./control-panel-items.js";
24
- import type { SshSetupDraft } from "./ssh-setup.js";
24
+ } from "./items.js";
25
25
 
26
26
  const LIST_ROWS = 8;
27
27
 
package/src/controller.ts CHANGED
@@ -8,10 +8,13 @@ import {
8
8
  recordContextBriefing,
9
9
  registerContextBriefing,
10
10
  } from "@howaboua/pi-agent-board/integration";
11
- import { controlPanelStatus, openControlPanel } from "./control-panel.js";
11
+ import { controlPanelStatus, openControlPanel } from "./control-panel/index.js";
12
12
  import { sendPolicyMessage } from "./delivery.js";
13
- import type { AgentFleet } from "./fleet.js";
14
- import { activeAgentsBriefing, orchestrationGuidance } from "./messages.js";
13
+ import type { AgentFleet } from "./fleet/index.js";
14
+ import {
15
+ activeAgentsBriefing,
16
+ orchestrationGuidance,
17
+ } from "./messages/guidance.js";
15
18
  import type { createPeerCommands } from "./peer-commands.js";
16
19
  import { loadAgentProfiles } from "./profiles.js";
17
20
 
@@ -0,0 +1,384 @@
1
+ import type {
2
+ ExtensionAPI,
3
+ ExtensionContext,
4
+ } from "@earendil-works/pi-coding-agent";
5
+ import { HerdrClient, type HerdrConnection } from "../herdr-client.js";
6
+ import { LOCAL_MACHINE, readMachineCatalog } from "../machine-catalog.js";
7
+ import { AgentMonitor } from "../monitor.js";
8
+ import { RemoteHerdrClient } from "../remote/client.js";
9
+ import type {
10
+ MachineStatus,
11
+ MonitoredAgent,
12
+ ScopedMonitoredAgent,
13
+ } from "../types.js";
14
+ import { renderAgentWidget } from "../widget.js";
15
+ import {
16
+ connectedMachine,
17
+ listAgents,
18
+ machineSnapshots,
19
+ statusFor,
20
+ } from "./inspection.js";
21
+ import {
22
+ type ConnectedMachine,
23
+ errorMessage,
24
+ type MachineRuntime,
25
+ type MachineSnapshot,
26
+ } from "./machine.js";
27
+ import { createMachineMonitor } from "./monitor.js";
28
+ import { groupSaved, MONITOR_STATE_TYPE, savedAgents } from "./persistence.js";
29
+ import { connectMachines } from "./reconnect.js";
30
+ import { FleetSetup } from "./setup.js";
31
+
32
+ export type { ConnectedMachine, MachineSnapshot } from "./machine.js";
33
+
34
+ export class AgentFleet {
35
+ private readonly listeners = new Set<() => void>();
36
+ subscribe(listener: () => void): () => void {
37
+ this.listeners.add(listener);
38
+ return () => {
39
+ this.listeners.delete(listener);
40
+ };
41
+ }
42
+ private readonly setup = new FleetSetup(() => this.refresh());
43
+ setContextRelay(
44
+ handler: (
45
+ ctx: ExtensionContext,
46
+ request: unknown,
47
+ signal: AbortSignal,
48
+ ) => Promise<unknown>,
49
+ ): void {
50
+ this.setup.setContextRelay(handler);
51
+ }
52
+ private context: ExtensionContext | undefined;
53
+ private generation = 0;
54
+ private readonly pi: ExtensionAPI;
55
+ private readonly runtimes = new Map<string, MachineRuntime>();
56
+
57
+ constructor(pi: ExtensionAPI) {
58
+ this.pi = pi;
59
+ }
60
+
61
+ async activate(ctx: ExtensionContext): Promise<void> {
62
+ this.deactivate();
63
+ const generation = this.generation;
64
+ this.context = ctx;
65
+ const catalog = await readMachineCatalog();
66
+ if (!this.isCurrent(generation, ctx)) return;
67
+ const machines = Object.entries(catalog).filter(
68
+ ([, machine]) => machine.enabled,
69
+ );
70
+ const grouped = groupSaved(savedAgents(ctx));
71
+ const known = new Set([LOCAL_MACHINE, ...machines.map(([id]) => id)]);
72
+ const orphaned = [...grouped.entries()]
73
+ .filter(([machine]) => !known.has(machine))
74
+ .reduce((count, [, records]) => count + records.length, 0);
75
+ if (orphaned > 0) {
76
+ ctx.ui.notify(
77
+ `Ignored ${orphaned} saved Shepherdr ${orphaned === 1 ? "agent" : "agents"} from removed machines`,
78
+ "warning",
79
+ );
80
+ }
81
+
82
+ const localRuntime: MachineRuntime = {
83
+ local: true,
84
+ pending: grouped.get(LOCAL_MACHINE) ?? [],
85
+ status: "connecting",
86
+ };
87
+ this.runtimes.set(LOCAL_MACHINE, localRuntime);
88
+ for (const [name, config] of machines) {
89
+ this.runtimes.set(name, {
90
+ config,
91
+ local: false,
92
+ pending: grouped.get(name) ?? [],
93
+ status: "connecting",
94
+ });
95
+ }
96
+
97
+ const localClient = new HerdrClient();
98
+ await localClient.request("ping");
99
+ if (!this.isCurrent(generation, ctx)) return;
100
+ const localMonitor = this.createMonitor(
101
+ LOCAL_MACHINE,
102
+ localRuntime,
103
+ localClient,
104
+ );
105
+ localRuntime.client = localClient;
106
+ localRuntime.monitor = localMonitor;
107
+ await localMonitor.activate(ctx, localRuntime.pending);
108
+ if (
109
+ !this.isCurrent(generation, ctx) ||
110
+ this.runtimes.get(LOCAL_MACHINE) !== localRuntime ||
111
+ localRuntime.client !== localClient ||
112
+ localRuntime.monitor !== localMonitor
113
+ ) {
114
+ localMonitor.deactivate();
115
+ return;
116
+ }
117
+ localRuntime.pending = [];
118
+ localRuntime.status = "connected";
119
+ this.changed();
120
+
121
+ for (const [name] of machines) {
122
+ void this.connectMachine(name, generation, true);
123
+ }
124
+ }
125
+
126
+ deactivate(): void {
127
+ this.generation += 1;
128
+ for (const runtime of this.runtimes.values()) {
129
+ runtime.monitor?.deactivate();
130
+ if (runtime.client instanceof RemoteHerdrClient) runtime.client.close();
131
+ }
132
+ this.runtimes.clear();
133
+ renderAgentWidget(this.context, [], []);
134
+ this.context = undefined;
135
+ for (const listener of this.listeners) listener();
136
+ }
137
+
138
+ isActive(): boolean {
139
+ return this.context !== undefined;
140
+ }
141
+
142
+ async reload(): Promise<void> {
143
+ const ctx = this.context;
144
+ if (!ctx) return;
145
+ const generation = this.generation;
146
+ const catalog = await readMachineCatalog();
147
+ if (!this.isCurrent(generation, ctx)) return;
148
+ const reconnect: string[] = [];
149
+
150
+ for (const [name, runtime] of this.runtimes) {
151
+ if (runtime.local || catalog[name]?.enabled) continue;
152
+ runtime.monitor?.deactivate();
153
+ if (runtime.client instanceof RemoteHerdrClient) runtime.client.close();
154
+ this.runtimes.delete(name);
155
+ }
156
+ for (const [name, machineConfig] of Object.entries(catalog)) {
157
+ if (!machineConfig.enabled) continue;
158
+ const runtime = this.runtimes.get(name);
159
+ if (
160
+ runtime?.config &&
161
+ runtime.config.target === machineConfig.target &&
162
+ runtime.config.session === machineConfig.session
163
+ ) {
164
+ runtime.config = machineConfig;
165
+ continue;
166
+ }
167
+ const pending = runtime?.monitor?.list() ?? runtime?.pending ?? [];
168
+ runtime?.monitor?.deactivate();
169
+ if (runtime?.client instanceof RemoteHerdrClient) runtime.client.close();
170
+ this.runtimes.set(name, {
171
+ config: machineConfig,
172
+ local: false,
173
+ pending,
174
+ status: "connecting",
175
+ });
176
+ reconnect.push(name);
177
+ }
178
+ this.changed();
179
+ for (const name of reconnect) {
180
+ void this.connectMachine(name, generation, true);
181
+ }
182
+ }
183
+
184
+ statuses(): MachineStatus[] {
185
+ return [...this.runtimes.keys()].map((name) =>
186
+ statusFor(this.runtimes, name),
187
+ );
188
+ }
189
+
190
+ list(): ScopedMonitoredAgent[] {
191
+ return listAgents(this.runtimes);
192
+ }
193
+ connected(machine?: string): ConnectedMachine {
194
+ return connectedMachine(this.runtimes, this.context, machine);
195
+ }
196
+ private isCurrent(generation: number, ctx: ExtensionContext): boolean {
197
+ return generation === this.generation && ctx === this.context;
198
+ }
199
+
200
+ async snapshots(machine?: string): Promise<MachineSnapshot[]> {
201
+ return machineSnapshots(this.runtimes, machine);
202
+ }
203
+ connect(machine?: string): string {
204
+ return connectMachines(
205
+ this.runtimes,
206
+ machine,
207
+ (name, runtime) => this.retrySetup(name, runtime),
208
+ (name) => this.connectMachine(name, this.generation, false),
209
+ );
210
+ }
211
+ private createMonitor(
212
+ machine: string,
213
+ runtime: MachineRuntime,
214
+ client: HerdrConnection,
215
+ ): AgentMonitor {
216
+ return createMachineMonitor(machine, runtime, client, this.pi, {
217
+ isAttached: () => this.runtimes.get(machine) === runtime,
218
+ context: () => this.context,
219
+ changed: () => this.changed(),
220
+ refresh: () => this.refresh(),
221
+ disconnected: (reason) => this.disconnected(machine, runtime, reason),
222
+ });
223
+ }
224
+ private async prepareContextRelay(
225
+ name: string,
226
+ runtime: MachineRuntime,
227
+ client: RemoteHerdrClient,
228
+ ctx: ExtensionContext,
229
+ ): Promise<void> {
230
+ return this.setup.prepareContextRelay(
231
+ name,
232
+ runtime,
233
+ client,
234
+ ctx,
235
+ () => this.context === ctx && this.runtimes.get(name) === runtime,
236
+ );
237
+ }
238
+ private async retrySetup(
239
+ name: string,
240
+ runtime: MachineRuntime,
241
+ ): Promise<void> {
242
+ const ctx = this.context;
243
+ const generation = this.generation;
244
+ return this.setup.retrySetup(
245
+ name,
246
+ runtime,
247
+ ctx,
248
+ () => ctx !== undefined && this.isCurrent(generation, ctx),
249
+ () => this.runtimes.get(name) === runtime,
250
+ () => this.context === ctx && this.runtimes.get(name) === runtime,
251
+ );
252
+ }
253
+ private async connectMachine(
254
+ name: string,
255
+ generation: number,
256
+ initial: boolean,
257
+ ): Promise<void> {
258
+ const runtime = this.runtimes.get(name);
259
+ const ctx = this.context;
260
+ if (
261
+ !runtime?.config ||
262
+ runtime.local ||
263
+ runtime.status === "connected" ||
264
+ runtime.attempting ||
265
+ !ctx ||
266
+ generation !== this.generation
267
+ ) {
268
+ return;
269
+ }
270
+ runtime.attempting = true;
271
+ runtime.status = "connecting";
272
+ delete runtime.reason;
273
+ this.refresh();
274
+ let attached = false;
275
+ let client: RemoteHerdrClient | undefined;
276
+ try {
277
+ client = await RemoteHerdrClient.connect(runtime.config, (error) => {
278
+ if (runtime.client === client)
279
+ this.disconnected(name, runtime, error.message);
280
+ });
281
+ await this.prepareContextRelay(name, runtime, client, ctx);
282
+ if (
283
+ !this.isCurrent(generation, ctx) ||
284
+ this.runtimes.get(name) !== runtime
285
+ ) {
286
+ client.close();
287
+ return;
288
+ }
289
+ await client.request("ping");
290
+ if (
291
+ !this.isCurrent(generation, ctx) ||
292
+ this.runtimes.get(name) !== runtime
293
+ ) {
294
+ client.close();
295
+ return;
296
+ }
297
+ const pending = runtime.monitor?.list() ?? runtime.pending;
298
+ const monitor = this.createMonitor(name, runtime, client);
299
+ runtime.client = client;
300
+ runtime.monitor = monitor;
301
+ attached = true;
302
+ await monitor.activate(ctx, pending);
303
+ if (
304
+ !this.isCurrent(generation, ctx) ||
305
+ this.runtimes.get(name) !== runtime ||
306
+ runtime.client !== client ||
307
+ runtime.monitor !== monitor
308
+ ) {
309
+ monitor.deactivate();
310
+ client.close();
311
+ return;
312
+ }
313
+ runtime.pending = [];
314
+ runtime.status = "connected";
315
+ delete runtime.attempting;
316
+ this.refresh();
317
+ if (!initial) ctx.ui.notify(`Connected to ${name}`, "info");
318
+ } catch (error) {
319
+ delete runtime.attempting;
320
+ if (
321
+ this.isCurrent(generation, ctx) &&
322
+ this.runtimes.get(name) === runtime &&
323
+ runtime.client === client &&
324
+ runtime.monitor &&
325
+ runtime.monitoringIssue?.state === "degraded"
326
+ ) {
327
+ runtime.pending = [];
328
+ runtime.status = "connected";
329
+ this.refresh();
330
+ return;
331
+ }
332
+ client?.close();
333
+ if (generation !== this.generation || ctx !== this.context) return;
334
+ if (
335
+ this.runtimes.get(name) !== runtime ||
336
+ (attached && runtime.client !== client)
337
+ ) {
338
+ return;
339
+ }
340
+ this.disconnected(name, runtime, errorMessage(error));
341
+ }
342
+ }
343
+
344
+ private disconnected(
345
+ name: string,
346
+ runtime: MachineRuntime,
347
+ reason: string,
348
+ ): void {
349
+ reason = errorMessage(reason);
350
+ if (runtime.status === "unavailable" && runtime.reason === reason) return;
351
+ // Keep the stopped owner until reconnect so in-flight dispatch cleanup
352
+ // updates the state we persist, rather than a detached snapshot.
353
+ runtime.monitor?.deactivate();
354
+ if (runtime.client instanceof RemoteHerdrClient) runtime.client.close();
355
+ delete runtime.client;
356
+ delete runtime.contextRelayError;
357
+ delete runtime.monitoringIssue;
358
+ runtime.status = "unavailable";
359
+ delete runtime.attempting;
360
+ runtime.reason = reason;
361
+ this.changed();
362
+ this.context?.ui.notify(
363
+ `Shepherdr unavailable on ${name}: ${reason}\nOpen /herdr → Status to reconnect`,
364
+ "warning",
365
+ );
366
+ }
367
+
368
+ private changed(): void {
369
+ if (!this.context) return;
370
+ const agents = this.persistedAgents();
371
+ this.pi.appendEntry(MONITOR_STATE_TYPE, { version: 2, agents });
372
+ this.refresh();
373
+ }
374
+
375
+ private refresh(): void {
376
+ if (!this.context) return;
377
+ renderAgentWidget(this.context, this.list(), this.statuses());
378
+ for (const listener of this.listeners) listener();
379
+ }
380
+
381
+ private persistedAgents(): Array<MonitoredAgent & { machine: string }> {
382
+ return listAgents(this.runtimes);
383
+ }
384
+ }