@howaboua/pi-shepherdr 0.2.23 → 0.2.25

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 (96) hide show
  1. package/CHANGELOG.md +20 -18
  2. package/README.md +80 -69
  3. package/biome.json +1 -1
  4. package/index.ts +4 -2
  5. package/package.json +14 -9
  6. package/src/agents-contract.ts +9 -6
  7. package/src/agents-discovery.ts +78 -37
  8. package/src/agents-focus.ts +17 -11
  9. package/src/agents-reply.ts +1 -1
  10. package/src/agents-spawn.ts +24 -8
  11. package/src/agents-tool.ts +26 -8
  12. package/src/agents-work.ts +5 -5
  13. package/src/attachment-notes.ts +14 -2
  14. package/src/attachment-protocol.ts +21 -4
  15. package/src/attachment-routing.ts +1 -1
  16. package/src/attachment-target.ts +5 -2
  17. package/src/attachment.ts +4 -3
  18. package/src/board/host.ts +5 -3
  19. package/src/board/membership.ts +1 -1
  20. package/src/close-idle.ts +89 -0
  21. package/src/{control-panel-actions.ts → control-panel/actions.ts} +2 -2
  22. package/src/{control-panel.ts → control-panel/index.ts} +7 -5
  23. package/src/{control-panel-items.ts → control-panel/items.ts} +17 -5
  24. package/src/{control-panel-view.ts → control-panel/view.ts} +9 -5
  25. package/src/controller.ts +17 -5
  26. package/src/core/AGENTS.md +5 -0
  27. package/src/core/backend.ts +266 -0
  28. package/src/core/client.ts +249 -0
  29. package/src/core/context-relay.mjs +111 -0
  30. package/src/core/focus-channel-helper.mjs +165 -0
  31. package/src/core/focus-channel-stream.ts +140 -0
  32. package/src/core/focus-channel-wire.mjs +160 -0
  33. package/src/core/focus-channel.ts +213 -0
  34. package/src/core/focus-window.ts +192 -0
  35. package/src/core/pi-executable.mjs +34 -0
  36. package/src/core/protocol.ts +116 -0
  37. package/src/core/registration.ts +51 -0
  38. package/src/core/remote-endpoint.ts +119 -0
  39. package/src/core/remote-exec.ts +122 -0
  40. package/src/core/remote-helper.mjs +244 -0
  41. package/src/core/remote-reader.ts +67 -0
  42. package/src/core/remote-relay.ts +191 -0
  43. package/src/core/request.ts +124 -0
  44. package/src/core/spawn.ts +177 -0
  45. package/src/core/status.ts +68 -0
  46. package/src/core/terminal.ts +103 -0
  47. package/src/fleet/catalog.ts +83 -0
  48. package/src/fleet/connection.ts +111 -0
  49. package/src/fleet/index.ts +413 -0
  50. package/src/fleet/inspection.ts +159 -0
  51. package/src/fleet/machine.ts +55 -0
  52. package/src/fleet/monitor.ts +85 -0
  53. package/src/fleet/persistence.ts +65 -0
  54. package/src/fleet/reconnect.ts +75 -0
  55. package/src/fleet/setup.ts +133 -0
  56. package/src/herdr.ts +25 -5
  57. package/src/launch-contract.ts +48 -0
  58. package/src/launch-location.ts +151 -0
  59. package/src/launch.ts +30 -183
  60. package/src/messages/attachments.ts +39 -0
  61. package/src/messages/attribution.ts +84 -0
  62. package/src/messages/event-details.ts +69 -0
  63. package/src/messages/events.ts +195 -0
  64. package/src/messages/focus.ts +47 -0
  65. package/src/messages/guidance.ts +83 -0
  66. package/src/messages/render.ts +89 -0
  67. package/src/messages/voice-announcements.ts +79 -0
  68. package/src/monitor-record.ts +9 -6
  69. package/src/monitor.ts +33 -2
  70. package/src/peer-commands.ts +11 -0
  71. package/src/peer-inbox-delivery.ts +171 -0
  72. package/src/peer-inbox-focus.ts +113 -0
  73. package/src/peer-inbox.ts +127 -209
  74. package/src/remote/client.ts +127 -0
  75. package/src/remote/context-relay.ts +84 -0
  76. package/src/remote/deployment.ts +179 -0
  77. package/src/remote/focus-channels.ts +89 -0
  78. package/src/remote/shepherdr-context.mjs +1 -1
  79. package/src/remote/shepherdr-peer.mjs +18 -5
  80. package/src/remote/shepherdr-session.mjs +9 -2
  81. package/src/remote/shepherdr.mjs +1 -1
  82. package/src/remote/transport.ts +369 -0
  83. package/src/settlement/collector.ts +122 -0
  84. package/src/settlement/delivery.ts +144 -0
  85. package/src/{settlement.ts → settlement/index.ts} +35 -233
  86. package/src/shared-context-host.ts +40 -14
  87. package/src/shared-context.ts +44 -6
  88. package/src/spawn-context.ts +24 -17
  89. package/src/spawn-ownership.ts +91 -0
  90. package/src/types.ts +9 -5
  91. package/src/voice-handoff.ts +1 -1
  92. package/src/worker-ownership.ts +92 -0
  93. package/src/worker-service.ts +14 -83
  94. package/src/fleet.ts +0 -702
  95. package/src/messages.ts +0 -637
  96. package/src/remote-client.ts +0 -761
@@ -0,0 +1,103 @@
1
+ import type { AgentStatus, PaneInfo, SessionSnapshot } from "../types.js";
2
+ import { object } from "./protocol.js";
3
+ import { CORE_SESSION_LABEL } from "./registration.js";
4
+
5
+ export function terminalPane(value: unknown): PaneInfo {
6
+ const terminal = object(value);
7
+ const address = terminal["address"];
8
+ if (typeof address !== "string" || !address || address.includes("/"))
9
+ throw new Error("Expected a local Core terminal address");
10
+ const labels = object(terminal["labels"]);
11
+ const status = terminal["status"] == null ? {} : object(terminal["status"]);
12
+ const state = status["state"];
13
+ const agentStatus: AgentStatus =
14
+ state === "error"
15
+ ? "done"
16
+ : state === "idle" ||
17
+ state === "working" ||
18
+ state === "blocked" ||
19
+ state === "done"
20
+ ? state
21
+ : "unknown";
22
+ const session = labels[CORE_SESSION_LABEL];
23
+ const live = terminal["state"] === "live";
24
+ return {
25
+ backend: "core",
26
+ // The shared legacy key is an address, not a fabricated app pane ID.
27
+ pane_id: address,
28
+ terminal_id: address,
29
+ agent: typeof session === "string" && session ? "pi" : null,
30
+ agent_status: agentStatus,
31
+ interactive_ready: live && typeof session === "string" && !!session,
32
+ launch_pending: live && !session,
33
+ ...(typeof terminal["cwd"] === "string" ? { cwd: terminal["cwd"] } : {}),
34
+ ...(typeof terminal["title"] === "string"
35
+ ? { title: terminal["title"] }
36
+ : {}),
37
+ ...(typeof labels["pi.shepherdr.name"] === "string"
38
+ ? { name: labels["pi.shepherdr.name"] }
39
+ : typeof terminal["name"] === "string"
40
+ ? { name: terminal["name"] }
41
+ : {}),
42
+ ...(typeof labels["herdr.space"] === "string" && labels["herdr.space"]
43
+ ? { workspace_id: labels["herdr.space"] }
44
+ : {}),
45
+ ...(typeof labels["herdr.tab"] === "string" && labels["herdr.tab"]
46
+ ? { tab_id: labels["herdr.tab"] }
47
+ : {}),
48
+ ...(typeof session === "string" && session
49
+ ? {
50
+ agent_session: {
51
+ agent: "pi",
52
+ kind: "path",
53
+ source: CORE_SESSION_LABEL,
54
+ value: session,
55
+ },
56
+ }
57
+ : {}),
58
+ };
59
+ }
60
+
61
+ export function terminalSnapshot(value: unknown): SessionSnapshot {
62
+ const terminals = object(value)["terminals"];
63
+ if (!Array.isArray(terminals)) throw new Error("Core returned no terminals");
64
+ const panes = terminals
65
+ .filter((value) => {
66
+ const terminal = object(value);
67
+ return (
68
+ terminal["state"] === "live" &&
69
+ typeof terminal["address"] === "string" &&
70
+ !terminal["address"].includes("/")
71
+ );
72
+ })
73
+ .map(terminalPane);
74
+ const workspaces = [
75
+ ...new Set(
76
+ panes.flatMap((pane) => (pane.workspace_id ? [pane.workspace_id] : [])),
77
+ ),
78
+ ].map((id) => ({ workspace_id: id, label: id }));
79
+ const tabs = [
80
+ ...new Map(
81
+ panes.flatMap((pane) =>
82
+ pane.tab_id && pane.workspace_id
83
+ ? [
84
+ [
85
+ pane.tab_id,
86
+ {
87
+ tab_id: pane.tab_id,
88
+ workspace_id: pane.workspace_id,
89
+ label: pane.tab_id,
90
+ },
91
+ ] as const,
92
+ ]
93
+ : [],
94
+ ),
95
+ ).values(),
96
+ ];
97
+ return {
98
+ panes,
99
+ agents: panes.filter((pane) => pane.agent === "pi"),
100
+ tabs,
101
+ workspaces,
102
+ };
103
+ }
@@ -0,0 +1,83 @@
1
+ import { CoreConnection } from "../core/backend.js";
2
+ import type { CoreMachine } from "../core/remote-exec.js";
3
+ import type { SshMachine } from "../machine-catalog.js";
4
+ import { RemoteHerdrClient } from "../remote/client.js";
5
+ import type { MachineRuntime } from "./machine.js";
6
+
7
+ /** Reconcile catalog changes without changing fleet identity or scheduling retries. */
8
+ export function reloadCoreCatalog(
9
+ runtimes: Map<string, MachineRuntime>,
10
+ catalog: CoreMachine[],
11
+ connect: (id: string) => void,
12
+ ): void {
13
+ for (const [id, runtime] of runtimes) {
14
+ if (
15
+ runtime.local ||
16
+ catalog.some(
17
+ (machine) =>
18
+ machine.id === id && machine.name === runtime.coreMachine?.name,
19
+ )
20
+ )
21
+ continue;
22
+ runtime.monitor?.deactivate();
23
+ if (runtime.client instanceof CoreConnection) runtime.client.close();
24
+ if (!catalog.some((machine) => machine.id === id)) runtimes.delete(id);
25
+ else {
26
+ runtime.pending = runtime.monitor?.list() ?? runtime.pending;
27
+ delete runtime.client;
28
+ delete runtime.monitor;
29
+ runtime.status = "unavailable";
30
+ }
31
+ }
32
+ for (const machine of catalog) {
33
+ let runtime = runtimes.get(machine.id);
34
+ if (runtime) runtime.coreMachine = machine;
35
+ else {
36
+ runtime = {
37
+ coreMachine: machine,
38
+ local: false,
39
+ pending: [],
40
+ status: "connecting",
41
+ };
42
+ runtimes.set(machine.id, runtime);
43
+ }
44
+ if (!runtime.client) connect(machine.id);
45
+ }
46
+ }
47
+
48
+ export function reloadSshCatalog(
49
+ runtimes: Map<string, MachineRuntime>,
50
+ catalog: Record<string, SshMachine>,
51
+ ): string[] {
52
+ const reconnect: string[] = [];
53
+
54
+ for (const [name, runtime] of runtimes) {
55
+ if (runtime.local || catalog[name]?.enabled) continue;
56
+ runtime.monitor?.deactivate();
57
+ if (runtime.client instanceof RemoteHerdrClient) runtime.client.close();
58
+ runtimes.delete(name);
59
+ }
60
+ for (const [name, machineConfig] of Object.entries(catalog)) {
61
+ if (!machineConfig.enabled) continue;
62
+ const runtime = runtimes.get(name);
63
+ if (
64
+ runtime?.config &&
65
+ runtime.config.target === machineConfig.target &&
66
+ runtime.config.session === machineConfig.session
67
+ ) {
68
+ runtime.config = machineConfig;
69
+ continue;
70
+ }
71
+ const pending = runtime?.monitor?.list() ?? runtime?.pending ?? [];
72
+ runtime?.monitor?.deactivate();
73
+ if (runtime?.client instanceof RemoteHerdrClient) runtime.client.close();
74
+ runtimes.set(name, {
75
+ config: machineConfig,
76
+ local: false,
77
+ pending,
78
+ status: "connecting",
79
+ });
80
+ reconnect.push(name);
81
+ }
82
+ return reconnect;
83
+ }
@@ -0,0 +1,111 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { CoreConnection } from "../core/backend.js";
3
+ import type { AgentMonitor } from "../monitor.js";
4
+ import { RemoteHerdrClient } from "../remote/client.js";
5
+ import { errorMessage, type MachineRuntime } from "./machine.js";
6
+
7
+ interface ConnectionEvents {
8
+ isCurrent(): boolean;
9
+ refresh(): void;
10
+ createMonitor(client: RemoteHerdrClient | CoreConnection): AgentMonitor;
11
+ needsContextRelay(): boolean;
12
+ prepareContextRelay(
13
+ client: RemoteHerdrClient | CoreConnection,
14
+ ): Promise<void>;
15
+ disconnected(reason: string): void;
16
+ }
17
+
18
+ /** Owns remote connection attachment, stale-attempt cleanup and degraded-monitor acceptance. */
19
+ export async function connectMachine(
20
+ runtimes: ReadonlyMap<string, MachineRuntime>,
21
+ name: string,
22
+ runtime: MachineRuntime,
23
+ ctx: ExtensionContext,
24
+ initial: boolean,
25
+ events: ConnectionEvents,
26
+ ): Promise<void> {
27
+ if (
28
+ (!runtime.config && !runtime.coreMachine) ||
29
+ runtime.local ||
30
+ runtime.status === "connected" ||
31
+ runtime.attempting ||
32
+ !events.isCurrent()
33
+ ) {
34
+ return;
35
+ }
36
+ runtime.attempting = true;
37
+ runtime.status = "connecting";
38
+ delete runtime.reason;
39
+ events.refresh();
40
+ let attached = false;
41
+ let client: RemoteHerdrClient | CoreConnection | undefined;
42
+ try {
43
+ if (runtime.coreMachine) {
44
+ client = new CoreConnection(
45
+ process.env["HC_TERMINAL_SOCKET"],
46
+ runtime.coreMachine,
47
+ );
48
+ } else {
49
+ client = await RemoteHerdrClient.connect(runtime.config!, (error) => {
50
+ if (runtime.client === client) events.disconnected(error.message);
51
+ });
52
+ }
53
+ if (!events.isCurrent() || runtimes.get(name) !== runtime) {
54
+ client.close();
55
+ return;
56
+ }
57
+ await client.request("ping");
58
+ if (!events.isCurrent() || runtimes.get(name) !== runtime) {
59
+ client.close();
60
+ return;
61
+ }
62
+ const pending = runtime.monitor?.list() ?? runtime.pending;
63
+ const monitor = events.createMonitor(client);
64
+ runtime.client = client;
65
+ runtime.monitor = monitor;
66
+ attached = true;
67
+ await monitor.activate(ctx, pending);
68
+ if (
69
+ !events.isCurrent() ||
70
+ runtimes.get(name) !== runtime ||
71
+ runtime.client !== client ||
72
+ runtime.monitor !== monitor
73
+ ) {
74
+ monitor.deactivate();
75
+ client.close();
76
+ return;
77
+ }
78
+ runtime.pending = [];
79
+ runtime.status = "connected";
80
+ delete runtime.attempting;
81
+ // Late connections must see optional sharing owners that finished startup.
82
+ if (events.needsContextRelay())
83
+ await events.prepareContextRelay(client).catch(() => {});
84
+ if (!events.isCurrent() || runtime.client !== client) return;
85
+ events.refresh();
86
+ if (!initial) ctx.ui.notify(`Connected to ${name}`, "info");
87
+ } catch (error) {
88
+ delete runtime.attempting;
89
+ if (
90
+ events.isCurrent() &&
91
+ runtimes.get(name) === runtime &&
92
+ runtime.client === client &&
93
+ runtime.monitor &&
94
+ runtime.monitoringIssue?.state === "degraded"
95
+ ) {
96
+ runtime.pending = [];
97
+ runtime.status = "connected";
98
+ events.refresh();
99
+ return;
100
+ }
101
+ client?.close();
102
+ if (!events.isCurrent()) return;
103
+ if (
104
+ runtimes.get(name) !== runtime ||
105
+ (attached && runtime.client !== client)
106
+ ) {
107
+ return;
108
+ }
109
+ events.disconnected(errorMessage(error));
110
+ }
111
+ }
@@ -0,0 +1,413 @@
1
+ import type {
2
+ ExtensionAPI,
3
+ ExtensionContext,
4
+ } from "@earendil-works/pi-coding-agent";
5
+ import { CoreConnection } from "../core/backend.js";
6
+ import { CoreClient } from "../core/client.js";
7
+ import { type CoreMachine, coreMachines } from "../core/remote-exec.js";
8
+ import { HerdrClient, type HerdrConnection } from "../herdr-client.js";
9
+ import { LOCAL_MACHINE, readMachineCatalog } from "../machine-catalog.js";
10
+ import { AgentMonitor } from "../monitor.js";
11
+ import { RemoteHerdrClient } from "../remote/client.js";
12
+ import type {
13
+ MachineStatus,
14
+ MonitoredAgent,
15
+ ScopedMonitoredAgent,
16
+ } from "../types.js";
17
+ import { renderAgentWidget } from "../widget.js";
18
+ import { reloadCoreCatalog, reloadSshCatalog } from "./catalog.js";
19
+ import { connectMachine } from "./connection.js";
20
+ import {
21
+ connectedMachine,
22
+ listAgents,
23
+ machineSnapshots,
24
+ statusFor,
25
+ } from "./inspection.js";
26
+ import {
27
+ type ConnectedMachine,
28
+ errorMessage,
29
+ type MachineRuntime,
30
+ type MachineSnapshot,
31
+ } from "./machine.js";
32
+ import { createMachineMonitor } from "./monitor.js";
33
+ import { groupSaved, MONITOR_STATE_TYPE, savedAgents } from "./persistence.js";
34
+ import { connectMachines } from "./reconnect.js";
35
+ import { FleetSetup } from "./setup.js";
36
+
37
+ export type { ConnectedMachine, MachineSnapshot } from "./machine.js";
38
+
39
+ export class AgentFleet {
40
+ private readonly listeners = new Set<() => void>();
41
+ subscribe(listener: () => void): () => void {
42
+ this.listeners.add(listener);
43
+ return () => {
44
+ this.listeners.delete(listener);
45
+ };
46
+ }
47
+ private readonly setup = new FleetSetup(() => this.refresh());
48
+ private needsContextRelay: (
49
+ ctx: ExtensionContext,
50
+ machine: string,
51
+ ) => boolean = () => false;
52
+ setContextRelay(
53
+ handler: (
54
+ ctx: ExtensionContext,
55
+ request: unknown,
56
+ signal: AbortSignal,
57
+ ) => Promise<unknown>,
58
+ needsRelay: (ctx: ExtensionContext, machine: string) => boolean,
59
+ ): void {
60
+ this.setup.setContextRelay(handler);
61
+ this.needsContextRelay = needsRelay;
62
+ }
63
+ async restoreSharing(ctx: ExtensionContext): Promise<void> {
64
+ if (this.context !== ctx) return;
65
+ await Promise.all(
66
+ this.statuses()
67
+ .filter(
68
+ (machine) =>
69
+ !machine.local &&
70
+ machine.status === "connected" &&
71
+ this.needsContextRelay(ctx, machine.id),
72
+ )
73
+ .map((machine) =>
74
+ this.connected(machine.id)
75
+ .prepareSharing()
76
+ .catch(() => {}),
77
+ ),
78
+ );
79
+ }
80
+ private context: ExtensionContext | undefined;
81
+ private generation = 0;
82
+ private readonly pi: ExtensionAPI;
83
+ private readonly runtimes = new Map<string, MachineRuntime>();
84
+ private localCoreId: string | undefined;
85
+
86
+ constructor(pi: ExtensionAPI) {
87
+ this.pi = pi;
88
+ }
89
+
90
+ async activate(ctx: ExtensionContext): Promise<void> {
91
+ this.deactivate();
92
+ const generation = this.generation;
93
+ this.context = ctx;
94
+ const catalog = process.env["HC_TERMINAL_SOCKET"]
95
+ ? {}
96
+ : await readMachineCatalog();
97
+ if (!this.isCurrent(generation, ctx)) return;
98
+ const machines = Object.entries(catalog).filter(
99
+ ([, machine]) => machine.enabled,
100
+ );
101
+ if (process.env["HC_TERMINAL_SOCKET"]) {
102
+ const identityClient = new CoreConnection();
103
+ let coreId: string;
104
+ try {
105
+ coreId = (await identityClient.machineIdentity()).session;
106
+ } finally {
107
+ identityClient.close();
108
+ }
109
+ if (!this.isCurrent(generation, ctx)) return;
110
+ this.localCoreId = coreId;
111
+ }
112
+ const grouped = groupSaved(savedAgents(ctx, this.localCoreId));
113
+ const coreCatalog = await this.coreCatalog();
114
+ if (!this.isCurrent(generation, ctx)) return;
115
+ const known = new Set([
116
+ LOCAL_MACHINE,
117
+ ...machines.map(([id]) => id),
118
+ ...coreCatalog.map((machine) => machine.id),
119
+ ]);
120
+ const orphaned = [...grouped.entries()]
121
+ .filter(([machine]) => !known.has(machine))
122
+ .reduce((count, [, records]) => count + records.length, 0);
123
+ if (orphaned > 0) {
124
+ ctx.ui.notify(
125
+ `Ignored ${orphaned} saved Shepherdr ${orphaned === 1 ? "agent" : "agents"} from removed machines`,
126
+ "warning",
127
+ );
128
+ }
129
+
130
+ const localRuntime: MachineRuntime = {
131
+ local: true,
132
+ pending: grouped.get(LOCAL_MACHINE) ?? [],
133
+ status: "connecting",
134
+ };
135
+ this.runtimes.set(LOCAL_MACHINE, localRuntime);
136
+ for (const [name, config] of machines) {
137
+ this.runtimes.set(name, {
138
+ config,
139
+ local: false,
140
+ pending: grouped.get(name) ?? [],
141
+ status: "connecting",
142
+ });
143
+ }
144
+ for (const machine of coreCatalog)
145
+ this.runtimes.set(machine.id, {
146
+ coreMachine: machine,
147
+ local: false,
148
+ pending: grouped.get(machine.id) ?? [],
149
+ status: "connecting",
150
+ });
151
+
152
+ const localClient = process.env["HC_TERMINAL_SOCKET"]
153
+ ? new CoreConnection()
154
+ : new HerdrClient();
155
+ await localClient.request("ping");
156
+ if (!this.isCurrent(generation, ctx)) {
157
+ if (localClient instanceof CoreConnection) localClient.close();
158
+ return;
159
+ }
160
+ const localMonitor = this.createMonitor(
161
+ LOCAL_MACHINE,
162
+ localRuntime,
163
+ localClient,
164
+ );
165
+ localRuntime.client = localClient;
166
+ localRuntime.monitor = localMonitor;
167
+ await localMonitor.activate(ctx, localRuntime.pending);
168
+ if (
169
+ !this.isCurrent(generation, ctx) ||
170
+ this.runtimes.get(LOCAL_MACHINE) !== localRuntime ||
171
+ localRuntime.client !== localClient ||
172
+ localRuntime.monitor !== localMonitor
173
+ ) {
174
+ localMonitor.deactivate();
175
+ return;
176
+ }
177
+ localRuntime.pending = [];
178
+ localRuntime.status = "connected";
179
+ this.changed();
180
+
181
+ for (const [name] of machines) {
182
+ void this.connectMachine(name, generation, true);
183
+ }
184
+ for (const machine of coreCatalog)
185
+ void this.connectMachine(machine.id, generation, true);
186
+ }
187
+
188
+ deactivate(): void {
189
+ this.generation += 1;
190
+ this.localCoreId = undefined;
191
+ for (const runtime of this.runtimes.values()) {
192
+ runtime.monitor?.deactivate();
193
+ if (
194
+ runtime.client instanceof RemoteHerdrClient ||
195
+ runtime.client instanceof CoreConnection
196
+ )
197
+ runtime.client.close();
198
+ }
199
+ this.runtimes.clear();
200
+ renderAgentWidget(this.context, [], []);
201
+ this.context = undefined;
202
+ for (const listener of this.listeners) listener();
203
+ }
204
+
205
+ isActive(): boolean {
206
+ return this.context !== undefined;
207
+ }
208
+
209
+ async reload(): Promise<void> {
210
+ const ctx = this.context;
211
+ if (!ctx) return;
212
+ const generation = this.generation;
213
+ if (process.env["HC_TERMINAL_SOCKET"]) {
214
+ const catalog = await this.coreCatalog();
215
+ if (!this.isCurrent(generation, ctx)) return;
216
+ reloadCoreCatalog(this.runtimes, catalog, (id) => {
217
+ void this.connectMachine(id, generation, true);
218
+ });
219
+ this.changed();
220
+ return;
221
+ }
222
+ const catalog = process.env["HC_TERMINAL_SOCKET"]
223
+ ? {}
224
+ : await readMachineCatalog();
225
+ if (!this.isCurrent(generation, ctx)) return;
226
+ const reconnect = reloadSshCatalog(this.runtimes, catalog);
227
+ this.changed();
228
+ for (const name of reconnect) {
229
+ void this.connectMachine(name, generation, true);
230
+ }
231
+ }
232
+
233
+ statuses(): MachineStatus[] {
234
+ return [...this.runtimes.keys()].map((name) =>
235
+ statusFor(this.runtimes, name),
236
+ );
237
+ }
238
+
239
+ list(): ScopedMonitoredAgent[] {
240
+ return listAgents(this.runtimes);
241
+ }
242
+ connected(machine?: string): ConnectedMachine {
243
+ const ctx = this.context;
244
+ return connectedMachine(
245
+ this.runtimes,
246
+ ctx,
247
+ async (name, runtime, client) => {
248
+ if (
249
+ !ctx ||
250
+ this.context !== ctx ||
251
+ this.runtimes.get(name) !== runtime ||
252
+ runtime.client !== client
253
+ )
254
+ throw new Error(
255
+ "Session changed; retry sharing from the current session",
256
+ );
257
+ if (runtime.local) return;
258
+ if (
259
+ !(
260
+ client instanceof RemoteHerdrClient ||
261
+ client instanceof CoreConnection
262
+ )
263
+ )
264
+ throw new Error("Context sharing is unavailable on this machine");
265
+ await this.prepareContextRelay(name, runtime, client, ctx);
266
+ if (
267
+ this.context !== ctx ||
268
+ this.runtimes.get(name) !== runtime ||
269
+ runtime.client !== client
270
+ )
271
+ throw new Error(
272
+ "Session changed; retry sharing from the current session",
273
+ );
274
+ client.contextRelayPath();
275
+ },
276
+ machine,
277
+ );
278
+ }
279
+ private isCurrent(generation: number, ctx: ExtensionContext): boolean {
280
+ return generation === this.generation && ctx === this.context;
281
+ }
282
+
283
+ async snapshots(machine?: string): Promise<MachineSnapshot[]> {
284
+ return machineSnapshots(this.runtimes, machine);
285
+ }
286
+ connect(machine?: string): string {
287
+ return connectMachines(
288
+ this.runtimes,
289
+ machine,
290
+ (name, runtime) => this.retrySetup(name, runtime),
291
+ (name) => this.connectMachine(name, this.generation, false),
292
+ );
293
+ }
294
+ private createMonitor(
295
+ machine: string,
296
+ runtime: MachineRuntime,
297
+ client: HerdrConnection,
298
+ ): AgentMonitor {
299
+ return createMachineMonitor(machine, runtime, client, this.pi, {
300
+ isAttached: () => this.runtimes.get(machine) === runtime,
301
+ context: () => this.context,
302
+ changed: () => this.changed(),
303
+ refresh: () => this.refresh(),
304
+ disconnected: (reason) => this.disconnected(machine, runtime, reason),
305
+ });
306
+ }
307
+ private async prepareContextRelay(
308
+ name: string,
309
+ runtime: MachineRuntime,
310
+ client: RemoteHerdrClient | CoreConnection,
311
+ ctx: ExtensionContext,
312
+ ): Promise<void> {
313
+ return this.setup.prepareContextRelay(
314
+ name,
315
+ runtime,
316
+ client,
317
+ ctx,
318
+ () => this.context === ctx && this.runtimes.get(name) === runtime,
319
+ );
320
+ }
321
+ private async retrySetup(
322
+ name: string,
323
+ runtime: MachineRuntime,
324
+ ): Promise<void> {
325
+ const ctx = this.context;
326
+ const generation = this.generation;
327
+ return this.setup.retrySetup(
328
+ name,
329
+ runtime,
330
+ ctx,
331
+ () => ctx !== undefined && this.isCurrent(generation, ctx),
332
+ () => this.runtimes.get(name) === runtime,
333
+ () => this.context === ctx && this.runtimes.get(name) === runtime,
334
+ );
335
+ }
336
+ private async connectMachine(
337
+ name: string,
338
+ generation: number,
339
+ initial: boolean,
340
+ ): Promise<void> {
341
+ const runtime = this.runtimes.get(name);
342
+ const ctx = this.context;
343
+ if (!runtime || !ctx) return;
344
+ return connectMachine(this.runtimes, name, runtime, ctx, initial, {
345
+ isCurrent: () => this.isCurrent(generation, ctx),
346
+ refresh: () => this.refresh(),
347
+ createMonitor: (client) => this.createMonitor(name, runtime, client),
348
+ needsContextRelay: () => this.needsContextRelay(ctx, name),
349
+ prepareContextRelay: (client) =>
350
+ this.prepareContextRelay(name, runtime, client, ctx),
351
+ disconnected: (reason) => this.disconnected(name, runtime, reason),
352
+ });
353
+ }
354
+
355
+ private disconnected(
356
+ name: string,
357
+ runtime: MachineRuntime,
358
+ reason: string,
359
+ ): void {
360
+ reason = errorMessage(reason);
361
+ if (runtime.status === "unavailable" && runtime.reason === reason) return;
362
+ // Keep the stopped owner until reconnect so in-flight dispatch cleanup
363
+ // updates the state we persist, rather than a detached snapshot.
364
+ runtime.monitor?.deactivate();
365
+ if (
366
+ runtime.client instanceof RemoteHerdrClient ||
367
+ runtime.client instanceof CoreConnection
368
+ )
369
+ runtime.client.close();
370
+ delete runtime.client;
371
+ delete runtime.contextRelayError;
372
+ delete runtime.monitoringIssue;
373
+ runtime.status = "unavailable";
374
+ delete runtime.attempting;
375
+ runtime.reason = reason;
376
+ this.changed();
377
+ this.context?.ui.notify(
378
+ `Shepherdr unavailable on ${name}: ${reason}\nOpen /herdr → Status to reconnect`,
379
+ "warning",
380
+ );
381
+ }
382
+
383
+ private changed(): void {
384
+ if (!this.context) return;
385
+ const agents = this.persistedAgents();
386
+ this.pi.appendEntry(MONITOR_STATE_TYPE, {
387
+ version: 2,
388
+ agents,
389
+ ...(this.localCoreId ? { localCoreId: this.localCoreId } : {}),
390
+ });
391
+ this.refresh();
392
+ }
393
+ private async coreCatalog(): Promise<CoreMachine[]> {
394
+ const socket = process.env["HC_TERMINAL_SOCKET"];
395
+ if (!socket) return [];
396
+ const client = new CoreClient(socket);
397
+ try {
398
+ return await coreMachines(client);
399
+ } finally {
400
+ client.close();
401
+ }
402
+ }
403
+
404
+ private refresh(): void {
405
+ if (!this.context) return;
406
+ renderAgentWidget(this.context, this.list(), this.statuses());
407
+ for (const listener of this.listeners) listener();
408
+ }
409
+
410
+ private persistedAgents(): Array<MonitoredAgent & { machine: string }> {
411
+ return listAgents(this.runtimes);
412
+ }
413
+ }