@howaboua/pi-shepherdr 0.2.24 → 0.2.26

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 (85) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +20 -12
  3. package/index.ts +2 -2
  4. package/package.json +10 -11
  5. package/src/agent-identity.ts +75 -0
  6. package/src/agents-contract.ts +20 -12
  7. package/src/agents-discovery.ts +79 -34
  8. package/src/agents-focus.ts +15 -9
  9. package/src/agents-spawn.ts +25 -7
  10. package/src/agents-tool.ts +35 -7
  11. package/src/agents-work.ts +2 -2
  12. package/src/attachment-notes.ts +25 -24
  13. package/src/attachment-protocol.ts +35 -15
  14. package/src/attachment-routing.ts +28 -24
  15. package/src/attachment-target.ts +58 -19
  16. package/src/attachment.ts +13 -17
  17. package/src/board/host.ts +19 -20
  18. package/src/board/membership.ts +49 -30
  19. package/src/close-idle.ts +89 -0
  20. package/src/context-routing.ts +196 -0
  21. package/src/control-panel/index.ts +3 -1
  22. package/src/control-panel/items.ts +14 -2
  23. package/src/control-panel/view.ts +6 -2
  24. package/src/controller.ts +11 -2
  25. package/src/core/AGENTS.md +5 -0
  26. package/src/core/backend.ts +266 -0
  27. package/src/core/client.ts +249 -0
  28. package/src/core/context-relay.mjs +111 -0
  29. package/src/core/focus-channel-helper.mjs +165 -0
  30. package/src/core/focus-channel-stream.ts +140 -0
  31. package/src/core/focus-channel-wire.mjs +160 -0
  32. package/src/core/focus-channel.ts +213 -0
  33. package/src/core/focus-window.ts +192 -0
  34. package/src/core/pi-executable.mjs +34 -0
  35. package/src/core/protocol.ts +116 -0
  36. package/src/core/registration.ts +51 -0
  37. package/src/core/remote-endpoint.ts +119 -0
  38. package/src/core/remote-exec.ts +122 -0
  39. package/src/core/remote-helper.mjs +244 -0
  40. package/src/core/remote-reader.ts +67 -0
  41. package/src/core/remote-relay.ts +191 -0
  42. package/src/core/request.ts +124 -0
  43. package/src/core/spawn.ts +177 -0
  44. package/src/core/status.ts +68 -0
  45. package/src/core/terminal.ts +103 -0
  46. package/src/fleet/catalog.ts +83 -0
  47. package/src/fleet/connection.ts +111 -0
  48. package/src/fleet/index.ts +161 -122
  49. package/src/fleet/inspection.ts +19 -1
  50. package/src/fleet/machine.ts +3 -0
  51. package/src/fleet/monitor.ts +18 -4
  52. package/src/fleet/persistence.ts +26 -3
  53. package/src/fleet/setup.ts +54 -13
  54. package/src/herdr.ts +25 -5
  55. package/src/launch-contract.ts +48 -0
  56. package/src/launch-location.ts +151 -0
  57. package/src/launch.ts +30 -183
  58. package/src/messages/attribution.ts +15 -6
  59. package/src/messages/events.ts +10 -4
  60. package/src/messages/focus.ts +11 -2
  61. package/src/messages/guidance.ts +22 -16
  62. package/src/monitor-extension-messages.ts +9 -2
  63. package/src/monitor-record.ts +13 -6
  64. package/src/monitor-state.ts +18 -4
  65. package/src/monitor.ts +31 -0
  66. package/src/peer-commands.ts +11 -0
  67. package/src/peer-inbox-delivery.ts +171 -0
  68. package/src/peer-inbox-focus.ts +113 -0
  69. package/src/peer-inbox.ts +126 -208
  70. package/src/remote/deployment.ts +1 -1
  71. package/src/remote/shepherdr-checkpoints.mjs +20 -2
  72. package/src/remote/shepherdr-context.mjs +15 -3
  73. package/src/remote/shepherdr-peer.mjs +18 -5
  74. package/src/remote/shepherdr-session.mjs +9 -2
  75. package/src/remote/shepherdr.mjs +1 -1
  76. package/src/settlement/collector.ts +2 -2
  77. package/src/settlement/index.ts +12 -0
  78. package/src/shared-context-host.ts +7 -18
  79. package/src/shared-context.ts +139 -12
  80. package/src/spawn-context.ts +10 -5
  81. package/src/spawn-ownership.ts +91 -0
  82. package/src/types.ts +10 -5
  83. package/src/worker-ownership.ts +92 -0
  84. package/src/worker-service.ts +13 -82
  85. package/changelog.ts +0 -337
@@ -2,6 +2,9 @@ import type {
2
2
  ExtensionAPI,
3
3
  ExtensionContext,
4
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";
5
8
  import { HerdrClient, type HerdrConnection } from "../herdr-client.js";
6
9
  import { LOCAL_MACHINE, readMachineCatalog } from "../machine-catalog.js";
7
10
  import { AgentMonitor } from "../monitor.js";
@@ -12,6 +15,8 @@ import type {
12
15
  ScopedMonitoredAgent,
13
16
  } from "../types.js";
14
17
  import { renderAgentWidget } from "../widget.js";
18
+ import { reloadCoreCatalog, reloadSshCatalog } from "./catalog.js";
19
+ import { connectMachine } from "./connection.js";
15
20
  import {
16
21
  connectedMachine,
17
22
  listAgents,
@@ -40,35 +45,82 @@ export class AgentFleet {
40
45
  };
41
46
  }
42
47
  private readonly setup = new FleetSetup(() => this.refresh());
48
+ private needsContextRelay: (
49
+ ctx: ExtensionContext,
50
+ machine: string,
51
+ ) => boolean = () => false;
43
52
  setContextRelay(
44
53
  handler: (
45
54
  ctx: ExtensionContext,
46
55
  request: unknown,
47
56
  signal: AbortSignal,
48
57
  ) => Promise<unknown>,
58
+ needsRelay: (ctx: ExtensionContext, machine: string) => boolean,
49
59
  ): void {
50
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
+ );
51
79
  }
52
80
  private context: ExtensionContext | undefined;
53
81
  private generation = 0;
54
82
  private readonly pi: ExtensionAPI;
55
83
  private readonly runtimes = new Map<string, MachineRuntime>();
84
+ private localCoreId: string | undefined;
85
+ private lastPersistedState: string | undefined;
56
86
 
57
87
  constructor(pi: ExtensionAPI) {
58
88
  this.pi = pi;
89
+ pi.on("session_tree", () => {
90
+ this.lastPersistedState = undefined;
91
+ });
59
92
  }
60
93
 
61
94
  async activate(ctx: ExtensionContext): Promise<void> {
62
95
  this.deactivate();
63
96
  const generation = this.generation;
64
97
  this.context = ctx;
65
- const catalog = await readMachineCatalog();
98
+ const catalog = process.env["HC_TERMINAL_SOCKET"]
99
+ ? {}
100
+ : await readMachineCatalog();
66
101
  if (!this.isCurrent(generation, ctx)) return;
67
102
  const machines = Object.entries(catalog).filter(
68
103
  ([, machine]) => machine.enabled,
69
104
  );
70
- const grouped = groupSaved(savedAgents(ctx));
71
- const known = new Set([LOCAL_MACHINE, ...machines.map(([id]) => id)]);
105
+ if (process.env["HC_TERMINAL_SOCKET"]) {
106
+ const identityClient = new CoreConnection();
107
+ let coreId: string;
108
+ try {
109
+ coreId = (await identityClient.machineIdentity()).session;
110
+ } finally {
111
+ identityClient.close();
112
+ }
113
+ if (!this.isCurrent(generation, ctx)) return;
114
+ this.localCoreId = coreId;
115
+ }
116
+ const grouped = groupSaved(savedAgents(ctx, this.localCoreId));
117
+ const coreCatalog = await this.coreCatalog();
118
+ if (!this.isCurrent(generation, ctx)) return;
119
+ const known = new Set([
120
+ LOCAL_MACHINE,
121
+ ...machines.map(([id]) => id),
122
+ ...coreCatalog.map((machine) => machine.id),
123
+ ]);
72
124
  const orphaned = [...grouped.entries()]
73
125
  .filter(([machine]) => !known.has(machine))
74
126
  .reduce((count, [, records]) => count + records.length, 0);
@@ -93,10 +145,22 @@ export class AgentFleet {
93
145
  status: "connecting",
94
146
  });
95
147
  }
148
+ for (const machine of coreCatalog)
149
+ this.runtimes.set(machine.id, {
150
+ coreMachine: machine,
151
+ local: false,
152
+ pending: grouped.get(machine.id) ?? [],
153
+ status: "connecting",
154
+ });
96
155
 
97
- const localClient = new HerdrClient();
156
+ const localClient = process.env["HC_TERMINAL_SOCKET"]
157
+ ? new CoreConnection()
158
+ : new HerdrClient();
98
159
  await localClient.request("ping");
99
- if (!this.isCurrent(generation, ctx)) return;
160
+ if (!this.isCurrent(generation, ctx)) {
161
+ if (localClient instanceof CoreConnection) localClient.close();
162
+ return;
163
+ }
100
164
  const localMonitor = this.createMonitor(
101
165
  LOCAL_MACHINE,
102
166
  localRuntime,
@@ -121,13 +185,21 @@ export class AgentFleet {
121
185
  for (const [name] of machines) {
122
186
  void this.connectMachine(name, generation, true);
123
187
  }
188
+ for (const machine of coreCatalog)
189
+ void this.connectMachine(machine.id, generation, true);
124
190
  }
125
191
 
126
192
  deactivate(): void {
127
193
  this.generation += 1;
194
+ this.localCoreId = undefined;
195
+ this.lastPersistedState = undefined;
128
196
  for (const runtime of this.runtimes.values()) {
129
197
  runtime.monitor?.deactivate();
130
- if (runtime.client instanceof RemoteHerdrClient) runtime.client.close();
198
+ if (
199
+ runtime.client instanceof RemoteHerdrClient ||
200
+ runtime.client instanceof CoreConnection
201
+ )
202
+ runtime.client.close();
131
203
  }
132
204
  this.runtimes.clear();
133
205
  renderAgentWidget(this.context, [], []);
@@ -143,38 +215,20 @@ export class AgentFleet {
143
215
  const ctx = this.context;
144
216
  if (!ctx) return;
145
217
  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",
218
+ if (process.env["HC_TERMINAL_SOCKET"]) {
219
+ const catalog = await this.coreCatalog();
220
+ if (!this.isCurrent(generation, ctx)) return;
221
+ reloadCoreCatalog(this.runtimes, catalog, (id) => {
222
+ void this.connectMachine(id, generation, true);
175
223
  });
176
- reconnect.push(name);
224
+ this.changed();
225
+ return;
177
226
  }
227
+ const catalog = process.env["HC_TERMINAL_SOCKET"]
228
+ ? {}
229
+ : await readMachineCatalog();
230
+ if (!this.isCurrent(generation, ctx)) return;
231
+ const reconnect = reloadSshCatalog(this.runtimes, catalog);
178
232
  this.changed();
179
233
  for (const name of reconnect) {
180
234
  void this.connectMachine(name, generation, true);
@@ -191,7 +245,41 @@ export class AgentFleet {
191
245
  return listAgents(this.runtimes);
192
246
  }
193
247
  connected(machine?: string): ConnectedMachine {
194
- return connectedMachine(this.runtimes, this.context, machine);
248
+ const ctx = this.context;
249
+ return connectedMachine(
250
+ this.runtimes,
251
+ ctx,
252
+ async (name, runtime, client) => {
253
+ if (
254
+ !ctx ||
255
+ this.context !== ctx ||
256
+ this.runtimes.get(name) !== runtime ||
257
+ runtime.client !== client
258
+ )
259
+ throw new Error(
260
+ "Session changed; retry sharing from the current session",
261
+ );
262
+ if (runtime.local) return;
263
+ if (
264
+ !(
265
+ client instanceof RemoteHerdrClient ||
266
+ client instanceof CoreConnection
267
+ )
268
+ )
269
+ throw new Error("Context sharing is unavailable on this machine");
270
+ await this.prepareContextRelay(name, runtime, client, ctx);
271
+ if (
272
+ this.context !== ctx ||
273
+ this.runtimes.get(name) !== runtime ||
274
+ runtime.client !== client
275
+ )
276
+ throw new Error(
277
+ "Session changed; retry sharing from the current session",
278
+ );
279
+ client.contextRelayPath();
280
+ },
281
+ machine,
282
+ );
195
283
  }
196
284
  private isCurrent(generation: number, ctx: ExtensionContext): boolean {
197
285
  return generation === this.generation && ctx === this.context;
@@ -224,7 +312,7 @@ export class AgentFleet {
224
312
  private async prepareContextRelay(
225
313
  name: string,
226
314
  runtime: MachineRuntime,
227
- client: RemoteHerdrClient,
315
+ client: RemoteHerdrClient | CoreConnection,
228
316
  ctx: ExtensionContext,
229
317
  ): Promise<void> {
230
318
  return this.setup.prepareContextRelay(
@@ -257,88 +345,16 @@ export class AgentFleet {
257
345
  ): Promise<void> {
258
346
  const runtime = this.runtimes.get(name);
259
347
  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
- }
348
+ if (!runtime || !ctx) return;
349
+ return connectMachine(this.runtimes, name, runtime, ctx, initial, {
350
+ isCurrent: () => this.isCurrent(generation, ctx),
351
+ refresh: () => this.refresh(),
352
+ createMonitor: (client) => this.createMonitor(name, runtime, client),
353
+ needsContextRelay: () => this.needsContextRelay(ctx, name),
354
+ prepareContextRelay: (client) =>
355
+ this.prepareContextRelay(name, runtime, client, ctx),
356
+ disconnected: (reason) => this.disconnected(name, runtime, reason),
357
+ });
342
358
  }
343
359
 
344
360
  private disconnected(
@@ -351,7 +367,11 @@ export class AgentFleet {
351
367
  // Keep the stopped owner until reconnect so in-flight dispatch cleanup
352
368
  // updates the state we persist, rather than a detached snapshot.
353
369
  runtime.monitor?.deactivate();
354
- if (runtime.client instanceof RemoteHerdrClient) runtime.client.close();
370
+ if (
371
+ runtime.client instanceof RemoteHerdrClient ||
372
+ runtime.client instanceof CoreConnection
373
+ )
374
+ runtime.client.close();
355
375
  delete runtime.client;
356
376
  delete runtime.contextRelayError;
357
377
  delete runtime.monitoringIssue;
@@ -368,9 +388,28 @@ export class AgentFleet {
368
388
  private changed(): void {
369
389
  if (!this.context) return;
370
390
  const agents = this.persistedAgents();
371
- this.pi.appendEntry(MONITOR_STATE_TYPE, { version: 2, agents });
391
+ const data = {
392
+ version: 2,
393
+ agents,
394
+ ...(this.localCoreId ? { localCoreId: this.localCoreId } : {}),
395
+ };
396
+ const serialized = JSON.stringify(data);
397
+ if (serialized !== this.lastPersistedState) {
398
+ this.pi.appendEntry(MONITOR_STATE_TYPE, data);
399
+ this.lastPersistedState = serialized;
400
+ }
372
401
  this.refresh();
373
402
  }
403
+ private async coreCatalog(): Promise<CoreMachine[]> {
404
+ const socket = process.env["HC_TERMINAL_SOCKET"];
405
+ if (!socket) return [];
406
+ const client = new CoreClient(socket);
407
+ try {
408
+ return await coreMachines(client);
409
+ } finally {
410
+ client.close();
411
+ }
412
+ }
374
413
 
375
414
  private refresh(): void {
376
415
  if (!this.context) return;
@@ -1,4 +1,5 @@
1
1
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { CoreConnection } from "../core/backend.js";
2
3
  import { getSnapshot } from "../herdr.js";
3
4
  import { LOCAL_MACHINE } from "../machine-catalog.js";
4
5
  import { parseMonitoredAgent } from "../monitor-record.js";
@@ -30,6 +31,11 @@ export function listAgents(
30
31
  export function connectedMachine(
31
32
  runtimes: ReadonlyMap<string, MachineRuntime>,
32
33
  context: ExtensionContext | undefined,
34
+ prepareSharing: (
35
+ machine: string,
36
+ runtime: MachineRuntime,
37
+ client: NonNullable<MachineRuntime["client"]>,
38
+ ) => Promise<void>,
33
39
  machine?: string,
34
40
  ): ConnectedMachine {
35
41
  const name = machine?.trim() || LOCAL_MACHINE;
@@ -45,8 +51,13 @@ export function connectedMachine(
45
51
  );
46
52
  }
47
53
  const remote =
48
- runtime.client instanceof RemoteHerdrClient ? runtime.client : undefined;
54
+ runtime.client instanceof RemoteHerdrClient ||
55
+ (runtime.client instanceof CoreConnection && runtime.client.remote)
56
+ ? runtime.client
57
+ : undefined;
58
+ const client = runtime.client;
49
59
  return {
60
+ prepareSharing: () => prepareSharing(name, runtime, client),
50
61
  machine: name,
51
62
  local: runtime.local,
52
63
  client: runtime.client,
@@ -128,6 +139,13 @@ export function statusFor(
128
139
  session: runtime.config.session,
129
140
  }
130
141
  : {}),
142
+ ...(runtime.coreMachine
143
+ ? {
144
+ label: runtime.coreMachine.name,
145
+ target: runtime.coreMachine.host,
146
+ session: runtime.coreMachine.id,
147
+ }
148
+ : {}),
131
149
  status: runtime.status,
132
150
  ...(runtime.monitoringIssue
133
151
  ? { monitoringIssue: runtime.monitoringIssue }
@@ -1,3 +1,4 @@
1
+ import type { CoreMachine } from "../core/remote-exec.js";
1
2
  import type { HerdrConnection } from "../herdr-client.js";
2
3
  import type { SshMachine } from "../machine-catalog.js";
3
4
  import type { AgentMonitor } from "../monitor.js";
@@ -11,6 +12,7 @@ export interface MachineRuntime {
11
12
  attempting?: boolean;
12
13
  client?: HerdrConnection;
13
14
  config?: SshMachine;
15
+ coreMachine?: CoreMachine;
14
16
  contextRelayError?: string;
15
17
  local: boolean;
16
18
  monitor?: AgentMonitor;
@@ -21,6 +23,7 @@ export interface MachineRuntime {
21
23
  }
22
24
 
23
25
  export interface ConnectedMachine {
26
+ prepareSharing: () => Promise<void>;
24
27
  client: HerdrConnection;
25
28
  fallbackCwd: string;
26
29
  local: boolean;
@@ -2,6 +2,7 @@ import type {
2
2
  ExtensionAPI,
3
3
  ExtensionContext,
4
4
  } from "@earendil-works/pi-coding-agent";
5
+ import { CoreConnection } from "../core/backend.js";
5
6
  import type { HerdrConnection } from "../herdr-client.js";
6
7
  import { LOCAL_MACHINE } from "../machine-catalog.js";
7
8
  import { AgentMonitor } from "../monitor.js";
@@ -28,13 +29,25 @@ export function createMachineMonitor(
28
29
  pi: ExtensionAPI,
29
30
  events: FleetMonitorEvents,
30
31
  ): AgentMonitor {
32
+ const selfPaneId = runtime.local
33
+ ? process.env[
34
+ client instanceof CoreConnection ? "HC_TERMINAL_ID" : "HERDR_PANE_ID"
35
+ ]
36
+ : undefined;
31
37
  return new AgentMonitor(pi, {
32
38
  client,
33
39
  machine,
34
- machineLabel: () => runtime.config?.label ?? LOCAL_MACHINE,
40
+ machineLabel: () =>
41
+ runtime.coreMachine?.name ?? runtime.config?.label ?? LOCAL_MACHINE,
35
42
  onChange: () => events.changed(),
36
43
  onRefresh: () => events.refresh(),
37
- operatorPrefix: runtime.local ? "herdr" : operatorPrefix(runtime.config!),
44
+ operatorPrefix: runtime.coreMachine
45
+ ? "hc"
46
+ : runtime.local
47
+ ? client instanceof CoreConnection
48
+ ? "hc"
49
+ : "herdr"
50
+ : operatorPrefix(runtime.config!),
38
51
  onWarning: (issue) => {
39
52
  if (!events.isAttached()) return;
40
53
  if (!runtime.local && issue.state === "unavailable") {
@@ -64,8 +77,9 @@ export function createMachineMonitor(
64
77
  },
65
78
  reconnect: runtime.local,
66
79
  ...(client instanceof RemoteHerdrClient ? { reader: client } : {}),
67
- ...(runtime.local && process.env["HERDR_PANE_ID"]
68
- ? { selfPaneId: process.env["HERDR_PANE_ID"] }
80
+ ...(client instanceof CoreConnection && client.reader
81
+ ? { reader: client.reader }
69
82
  : {}),
83
+ ...(selfPaneId ? { selfPaneId } : {}),
70
84
  });
71
85
  }
@@ -2,16 +2,25 @@ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { LOCAL_MACHINE } from "../machine-catalog.js";
3
3
  export const MONITOR_STATE_TYPE = "herdr-agents-monitor-state";
4
4
 
5
- export function savedAgents(ctx: ExtensionContext): unknown[] {
5
+ export function savedAgents(
6
+ ctx: ExtensionContext,
7
+ localCoreId?: string,
8
+ ): unknown[] {
6
9
  let latest: unknown[] = [];
7
10
  let version: unknown;
11
+ let savedCoreId: unknown;
8
12
  for (const entry of ctx.sessionManager.getBranch()) {
9
13
  if (entry.type !== "custom" || entry.customType !== MONITOR_STATE_TYPE)
10
14
  continue;
11
- const data = entry.data as { version?: unknown; agents?: unknown };
15
+ const data = entry.data as {
16
+ version?: unknown;
17
+ agents?: unknown;
18
+ localCoreId?: unknown;
19
+ };
12
20
  if (Array.isArray(data?.agents)) {
13
21
  latest = data.agents;
14
22
  version = data.version;
23
+ savedCoreId = data.localCoreId;
15
24
  }
16
25
  }
17
26
  if (latest.length > 0 && version !== 2) {
@@ -21,7 +30,21 @@ export function savedAgents(ctx: ExtensionContext): unknown[] {
21
30
  );
22
31
  return [];
23
32
  }
24
- return latest;
33
+ if (savedCoreId === localCoreId) return latest;
34
+ const retained = latest.filter(
35
+ (value) =>
36
+ typeof value === "object" &&
37
+ value !== null &&
38
+ "machine" in value &&
39
+ typeof value.machine === "string" &&
40
+ value.machine !== LOCAL_MACHINE,
41
+ );
42
+ if (retained.length !== latest.length)
43
+ ctx.ui.notify(
44
+ "Ignored saved local agent watches from another Herdr session; watch them again in this session.",
45
+ "warning",
46
+ );
47
+ return retained;
25
48
  }
26
49
 
27
50
  export function groupSaved(values: unknown[]): Map<string, unknown[]> {
@@ -1,9 +1,15 @@
1
1
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { CoreConnection } from "../core/backend.js";
2
3
  import { RemoteHerdrClient } from "../remote/client.js";
3
4
  import { errorMessage, type MachineRuntime } from "./machine.js";
4
5
 
5
6
  /** Explicitly requested sharing/monitor readiness; fleet supplies current-selection leases. */
6
7
  export class FleetSetup {
8
+ // Concurrent publishers share one start; existing children retain its route.
9
+ private readonly relays = new WeakMap<
10
+ RemoteHerdrClient | CoreConnection,
11
+ Promise<void>
12
+ >();
7
13
  private readonly refresh: () => void;
8
14
  constructor(refresh: () => void) {
9
15
  this.refresh = refresh;
@@ -24,29 +30,63 @@ export class FleetSetup {
24
30
  ): void {
25
31
  this.contextRelay = handler;
26
32
  }
27
- async prepareContextRelay(
33
+ prepareContextRelay(
28
34
  name: string,
29
35
  runtime: MachineRuntime,
30
- client: RemoteHerdrClient,
36
+ client: RemoteHerdrClient | CoreConnection,
31
37
  ctx: ExtensionContext,
32
38
  isSelected: () => boolean,
33
39
  ): Promise<void> {
34
- if (!this.contextRelay) return;
35
- try {
36
- await client.startContextRelay(
37
- ctx.sessionManager.getSessionId(),
38
- name,
39
- (request, signal) => this.contextRelay!(ctx, request, signal),
40
+ if (!this.contextRelay)
41
+ return Promise.reject(
42
+ new Error("Context sharing is unavailable in this session"),
40
43
  );
41
- if (!isSelected()) return;
42
- delete runtime.contextRelayError;
43
- } catch (error) {
44
+ const ready = this.relays.get(client);
45
+ if (ready) return ready;
46
+ const starting = this.openContextRelay(
47
+ name,
48
+ runtime,
49
+ client,
50
+ ctx,
51
+ isSelected,
52
+ );
53
+ this.relays.set(client, starting);
54
+ return starting;
55
+ }
56
+ private async openContextRelay(
57
+ name: string,
58
+ runtime: MachineRuntime,
59
+ client: RemoteHerdrClient | CoreConnection,
60
+ ctx: ExtensionContext,
61
+ isSelected: () => boolean,
62
+ ): Promise<void> {
63
+ if (!this.contextRelay)
64
+ throw new Error("Context sharing is unavailable in this session");
65
+ const failed = (error: unknown) => {
66
+ this.relays.delete(client);
44
67
  if (!isSelected()) return;
45
68
  runtime.contextRelayError = errorMessage(error);
46
69
  ctx.ui.notify(
47
70
  `Context sharing unavailable on ${name}: ${runtime.contextRelayError}\nOpen /herdr → Status to retry sharing.`,
48
71
  "warning",
49
72
  );
73
+ this.refresh();
74
+ };
75
+ try {
76
+ const args = [
77
+ ctx.sessionManager.getSessionId(),
78
+ name,
79
+ (request: unknown, signal: AbortSignal) =>
80
+ this.contextRelay!(ctx, request, signal),
81
+ ] as const;
82
+ if (client instanceof CoreConnection)
83
+ await client.startContextRelay(...args, failed);
84
+ else await client.startContextRelay(...args);
85
+ if (!isSelected()) return;
86
+ delete runtime.contextRelayError;
87
+ } catch (error) {
88
+ failed(error);
89
+ throw error;
50
90
  }
51
91
  }
52
92
 
@@ -65,7 +105,8 @@ export class FleetSetup {
65
105
  try {
66
106
  if (
67
107
  runtime.contextRelayError &&
68
- runtime.client instanceof RemoteHerdrClient
108
+ (runtime.client instanceof RemoteHerdrClient ||
109
+ runtime.client instanceof CoreConnection)
69
110
  )
70
111
  await this.prepareContextRelay(
71
112
  name,
@@ -73,7 +114,7 @@ export class FleetSetup {
73
114
  runtime.client,
74
115
  ctx,
75
116
  isSelected,
76
- );
117
+ ).catch(() => {});
77
118
  if (isCurrent() && isRegistered() && runtime.monitoringIssue)
78
119
  await monitor.retryMonitoring();
79
120
  } catch (error) {