@howaboua/pi-shepherdr 0.2.22 → 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 (61) hide show
  1. package/CHANGELOG.md +16 -18
  2. package/README.md +79 -58
  3. package/biome.json +1 -1
  4. package/index.ts +7 -3
  5. package/package.json +14 -9
  6. package/src/agents-discovery.ts +42 -27
  7. package/src/agents-focus.ts +2 -2
  8. package/src/agents-reply.ts +1 -1
  9. package/src/agents-spawn.ts +143 -137
  10. package/src/agents-tool.ts +3 -3
  11. package/src/agents-work.ts +33 -9
  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/launch.ts +14 -2
  32. package/src/messages/attachments.ts +39 -0
  33. package/src/messages/attribution.ts +75 -0
  34. package/src/messages/event-details.ts +69 -0
  35. package/src/messages/events.ts +189 -0
  36. package/src/messages/focus.ts +38 -0
  37. package/src/messages/guidance.ts +83 -0
  38. package/src/messages/render.ts +89 -0
  39. package/src/messages/voice-announcements.ts +79 -0
  40. package/src/monitor-extension-messages.ts +14 -1
  41. package/src/monitor.ts +4 -2
  42. package/src/peer-inbox.ts +2 -2
  43. package/src/profile-prompt.ts +32 -0
  44. package/src/profiles.ts +5 -25
  45. package/src/remote/client.ts +127 -0
  46. package/src/remote/context-relay.ts +84 -0
  47. package/src/remote/deployment.ts +179 -0
  48. package/src/remote/focus-channels.ts +89 -0
  49. package/src/remote/transport.ts +369 -0
  50. package/src/settlement/collector.ts +122 -0
  51. package/src/settlement/delivery.ts +144 -0
  52. package/src/{settlement.ts → settlement/index.ts} +23 -233
  53. package/src/shared-context-host.ts +33 -11
  54. package/src/shared-context.ts +10 -4
  55. package/src/spawn-context.ts +20 -17
  56. package/src/voice-handoff.ts +1 -1
  57. package/src/worker-role.ts +83 -0
  58. package/src/worker-service.ts +74 -89
  59. package/src/fleet.ts +0 -702
  60. package/src/messages.ts +0 -629
  61. package/src/remote-client.ts +0 -751
@@ -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
+ }
@@ -0,0 +1,141 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { getSnapshot } from "../herdr.js";
3
+ import { LOCAL_MACHINE } from "../machine-catalog.js";
4
+ import { parseMonitoredAgent } from "../monitor-record.js";
5
+ import { RemoteHerdrClient } from "../remote/client.js";
6
+ import type {
7
+ MachineStatus,
8
+ MonitoredAgent,
9
+ ScopedMonitoredAgent,
10
+ } from "../types.js";
11
+ import {
12
+ type ConnectedMachine,
13
+ errorMessage,
14
+ type MachineRuntime,
15
+ type MachineSnapshot,
16
+ } from "./machine.js";
17
+
18
+ export function listAgents(
19
+ runtimes: ReadonlyMap<string, MachineRuntime>,
20
+ ): ScopedMonitoredAgent[] {
21
+ return [...runtimes.entries()].flatMap(([machine, runtime]) => {
22
+ const values = runtime.monitor?.list() ?? runtime.pending;
23
+ return values
24
+ .map((value) => parseMonitoredAgent(value))
25
+ .filter((value): value is MonitoredAgent => value !== undefined)
26
+ .map((agent) => ({ ...agent, machine }));
27
+ });
28
+ }
29
+
30
+ export function connectedMachine(
31
+ runtimes: ReadonlyMap<string, MachineRuntime>,
32
+ context: ExtensionContext | undefined,
33
+ machine?: string,
34
+ ): ConnectedMachine {
35
+ const name = machine?.trim() || LOCAL_MACHINE;
36
+ const runtime = runtimes.get(name);
37
+ if (!runtime) {
38
+ throw new Error(
39
+ `unknown Herdr machine ${JSON.stringify(name)}; use list to see configured machines`,
40
+ );
41
+ }
42
+ if (runtime.status !== "connected" || !runtime.client || !runtime.monitor) {
43
+ throw new Error(
44
+ `Herdr machine ${JSON.stringify(name)} is ${runtime.status}${runtime.reason ? `: ${runtime.reason}` : ""}; open /herdr → Status to reconnect`,
45
+ );
46
+ }
47
+ const remote =
48
+ runtime.client instanceof RemoteHerdrClient ? runtime.client : undefined;
49
+ return {
50
+ machine: name,
51
+ local: runtime.local,
52
+ client: runtime.client,
53
+ monitor: runtime.monitor,
54
+ fallbackCwd: runtime.local ? (context?.cwd ?? ".") : "~",
55
+ ...(remote
56
+ ? {
57
+ resolveDirectory: (value: string | undefined, fallback: string) =>
58
+ remote.directory(value, fallback),
59
+ }
60
+ : {}),
61
+ };
62
+ }
63
+
64
+ export async function machineSnapshots(
65
+ runtimes: ReadonlyMap<string, MachineRuntime>,
66
+ machine?: string,
67
+ ): Promise<MachineSnapshot[]> {
68
+ const selected = machine?.trim()
69
+ ? [statusFor(runtimes, machine.trim())]
70
+ : [...runtimes.keys()].map((name) => statusFor(runtimes, name));
71
+ return Promise.all(
72
+ selected.map(async (status) => {
73
+ const runtime = runtimes.get(status.id);
74
+ if (status.status !== "connected" || !runtime?.client || !runtime.monitor)
75
+ return status;
76
+ const client = runtime.client;
77
+ const monitor = runtime.monitor;
78
+ try {
79
+ const snapshot = await getSnapshot(client);
80
+ if (
81
+ runtime.status !== "connected" ||
82
+ runtime.client !== client ||
83
+ runtime.monitor !== monitor ||
84
+ runtimes.get(status.id) !== runtime
85
+ ) {
86
+ return runtimes.has(status.id)
87
+ ? statusFor(runtimes, status.id)
88
+ : status;
89
+ }
90
+ return {
91
+ ...status,
92
+ monitoredPaneIds: new Set(
93
+ monitor.list().map((record) => record.paneId),
94
+ ),
95
+ snapshot,
96
+ };
97
+ } catch (error) {
98
+ if (
99
+ runtime.status !== "connected" ||
100
+ runtime.client !== client ||
101
+ runtime.monitor !== monitor ||
102
+ runtimes.get(status.id) !== runtime
103
+ ) {
104
+ return runtimes.has(status.id)
105
+ ? statusFor(runtimes, status.id)
106
+ : status;
107
+ }
108
+ return { ...status, snapshotError: errorMessage(error) };
109
+ }
110
+ }),
111
+ );
112
+ }
113
+
114
+ export function statusFor(
115
+ runtimes: ReadonlyMap<string, MachineRuntime>,
116
+ name: string,
117
+ ): MachineStatus {
118
+ const runtime = runtimes.get(name);
119
+ if (!runtime)
120
+ throw new Error(`unknown Herdr machine ${JSON.stringify(name)}`);
121
+ return {
122
+ id: name,
123
+ local: runtime.local,
124
+ ...(runtime.config
125
+ ? {
126
+ label: runtime.config.label,
127
+ target: runtime.config.target,
128
+ session: runtime.config.session,
129
+ }
130
+ : {}),
131
+ status: runtime.status,
132
+ ...(runtime.monitoringIssue
133
+ ? { monitoringIssue: runtime.monitoringIssue }
134
+ : {}),
135
+ ...(runtime.reason ? { reason: runtime.reason } : {}),
136
+ ...(runtime.contextRelayError
137
+ ? { contextRelayError: runtime.contextRelayError }
138
+ : {}),
139
+ ...(runtime.attempting ? { attempting: true } : {}),
140
+ };
141
+ }
@@ -0,0 +1,52 @@
1
+ import type { HerdrConnection } from "../herdr-client.js";
2
+ import type { SshMachine } from "../machine-catalog.js";
3
+ import type { AgentMonitor } from "../monitor.js";
4
+ import type {
5
+ MachineStatus,
6
+ MonitoringIssue,
7
+ SessionSnapshot,
8
+ } from "../types.js";
9
+
10
+ export interface MachineRuntime {
11
+ attempting?: boolean;
12
+ client?: HerdrConnection;
13
+ config?: SshMachine;
14
+ contextRelayError?: string;
15
+ local: boolean;
16
+ monitor?: AgentMonitor;
17
+ monitoringIssue?: MonitoringIssue;
18
+ pending: unknown[];
19
+ reason?: string;
20
+ status: MachineStatus["status"];
21
+ }
22
+
23
+ export interface ConnectedMachine {
24
+ client: HerdrConnection;
25
+ fallbackCwd: string;
26
+ local: boolean;
27
+ machine: string;
28
+ monitor: AgentMonitor;
29
+ resolveDirectory?: (
30
+ value: string | undefined,
31
+ fallback: string,
32
+ ) => Promise<string>;
33
+ }
34
+
35
+ export interface MachineSnapshot extends MachineStatus {
36
+ monitoredPaneIds?: ReadonlySet<string>;
37
+ snapshot?: SessionSnapshot;
38
+ snapshotError?: string;
39
+ }
40
+
41
+ export function errorMessage(error: unknown): string {
42
+ const message = error instanceof Error ? error.message : String(error);
43
+ return message.length <= 500 ? message : `${message.slice(0, 499)}…`;
44
+ }
45
+
46
+ function shellQuote(value: string): string {
47
+ return `'${value.replaceAll("'", `'"'"'`)}'`;
48
+ }
49
+
50
+ export function operatorPrefix(config: SshMachine): string {
51
+ return `ssh -T -o BatchMode=yes -- ${shellQuote(config.target)} herdr --session ${shellQuote(config.session)}`;
52
+ }
@@ -0,0 +1,71 @@
1
+ import type {
2
+ ExtensionAPI,
3
+ ExtensionContext,
4
+ } from "@earendil-works/pi-coding-agent";
5
+ import type { HerdrConnection } from "../herdr-client.js";
6
+ import { LOCAL_MACHINE } from "../machine-catalog.js";
7
+ import { AgentMonitor } from "../monitor.js";
8
+ import { RemoteHerdrClient } from "../remote/client.js";
9
+ import {
10
+ errorMessage,
11
+ type MachineRuntime,
12
+ operatorPrefix,
13
+ } from "./machine.js";
14
+
15
+ interface FleetMonitorEvents {
16
+ isAttached(): boolean;
17
+ context(): ExtensionContext | undefined;
18
+ changed(): void;
19
+ refresh(): void;
20
+ disconnected(reason: string): void;
21
+ }
22
+
23
+ /** Owns the local/remote monitoring adapter and its warning/recovery policy. */
24
+ export function createMachineMonitor(
25
+ machine: string,
26
+ runtime: MachineRuntime,
27
+ client: HerdrConnection,
28
+ pi: ExtensionAPI,
29
+ events: FleetMonitorEvents,
30
+ ): AgentMonitor {
31
+ return new AgentMonitor(pi, {
32
+ client,
33
+ machine,
34
+ machineLabel: () => runtime.config?.label ?? LOCAL_MACHINE,
35
+ onChange: () => events.changed(),
36
+ onRefresh: () => events.refresh(),
37
+ operatorPrefix: runtime.local ? "herdr" : operatorPrefix(runtime.config!),
38
+ onWarning: (issue) => {
39
+ if (!events.isAttached()) return;
40
+ if (!runtime.local && issue.state === "unavailable") {
41
+ events.disconnected(issue.message);
42
+ return;
43
+ }
44
+ runtime.monitoringIssue = {
45
+ ...issue,
46
+ message: errorMessage(issue.message),
47
+ };
48
+ events.refresh();
49
+ events
50
+ .context()
51
+ ?.ui.notify(
52
+ `${machine}: ${issue.message}${runtime.local ? "" : "\nOpen /herdr → Status to reconnect"}`,
53
+ "warning",
54
+ );
55
+ },
56
+ onRecovered: () => {
57
+ if (!events.isAttached() || !runtime.monitoringIssue) return;
58
+ delete runtime.monitoringIssue;
59
+ events.refresh();
60
+ if (runtime.monitor?.list().length)
61
+ events
62
+ .context()
63
+ ?.ui.notify(`Herdr monitoring restored: ${machine}`, "info");
64
+ },
65
+ reconnect: runtime.local,
66
+ ...(client instanceof RemoteHerdrClient ? { reader: client } : {}),
67
+ ...(runtime.local && process.env["HERDR_PANE_ID"]
68
+ ? { selfPaneId: process.env["HERDR_PANE_ID"] }
69
+ : {}),
70
+ });
71
+ }
@@ -0,0 +1,42 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { LOCAL_MACHINE } from "../machine-catalog.js";
3
+ export const MONITOR_STATE_TYPE = "herdr-agents-monitor-state";
4
+
5
+ export function savedAgents(ctx: ExtensionContext): unknown[] {
6
+ let latest: unknown[] = [];
7
+ let version: unknown;
8
+ for (const entry of ctx.sessionManager.getBranch()) {
9
+ if (entry.type !== "custom" || entry.customType !== MONITOR_STATE_TYPE)
10
+ continue;
11
+ const data = entry.data as { version?: unknown; agents?: unknown };
12
+ if (Array.isArray(data?.agents)) {
13
+ latest = data.agents;
14
+ version = data.version;
15
+ }
16
+ }
17
+ if (latest.length > 0 && version !== 2) {
18
+ ctx.ui.notify(
19
+ "Cleared legacy Shepherdr watches; use watch to subscribe explicitly. Remote agents are unchanged.",
20
+ "warning",
21
+ );
22
+ return [];
23
+ }
24
+ return latest;
25
+ }
26
+
27
+ export function groupSaved(values: unknown[]): Map<string, unknown[]> {
28
+ const grouped = new Map<string, unknown[]>();
29
+ for (const value of values) {
30
+ const machine =
31
+ typeof value === "object" &&
32
+ value !== null &&
33
+ "machine" in value &&
34
+ typeof value.machine === "string"
35
+ ? value.machine
36
+ : LOCAL_MACHINE;
37
+ const records = grouped.get(machine) ?? [];
38
+ records.push(value);
39
+ grouped.set(machine, records);
40
+ }
41
+ return grouped;
42
+ }