@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
@@ -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(
@@ -0,0 +1,89 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { CoreConnection } from "./core/backend.js";
3
+ import type { AgentFleet } from "./fleet/index.js";
4
+ import { getSnapshot, sessionPath } from "./herdr.js";
5
+ import { spawnedChildren } from "./spawn-ownership.js";
6
+
7
+ export async function closeIdleChildren(
8
+ fleet: AgentFleet,
9
+ ctx: ExtensionContext,
10
+ current: () => boolean,
11
+ ): Promise<string> {
12
+ let closed = 0;
13
+ let skipped = 0;
14
+ const failures: string[] = [];
15
+ for (const child of spawnedChildren(ctx)) {
16
+ if (!current()) break;
17
+ try {
18
+ const status = fleet
19
+ .statuses()
20
+ .find((value) => value.id === child.machine);
21
+ if (!status || status.status !== "connected" || status.monitoringIssue) {
22
+ skipped += 1;
23
+ continue;
24
+ }
25
+ const runtime = fleet.connected(child.machine);
26
+ const identity = await runtime.client.machineIdentity();
27
+ const snapshot = await getSnapshot(runtime.client);
28
+ const panel = snapshot.agents.find(
29
+ (value) => value.pane_id === child.pane,
30
+ );
31
+ const record = runtime.monitor
32
+ .list()
33
+ .find((value) => value.terminalId === child.terminal);
34
+ if (
35
+ !current() ||
36
+ !spawnedChildren(ctx).some(
37
+ (value) =>
38
+ value.machine === child.machine &&
39
+ value.pane === child.pane &&
40
+ value.terminal === child.terminal &&
41
+ value.sessionFile === child.sessionFile,
42
+ ) ||
43
+ identity.host !== child.host ||
44
+ identity.session !== child.session ||
45
+ !panel ||
46
+ panel.agent !== "pi" ||
47
+ panel.terminal_id !== child.terminal ||
48
+ sessionPath(panel) !== child.sessionFile ||
49
+ (runtime.local &&
50
+ panel.pane_id ===
51
+ process.env[
52
+ runtime.client instanceof CoreConnection
53
+ ? "HC_TERMINAL_ID"
54
+ : "HERDR_PANE_ID"
55
+ ]) ||
56
+ snapshot.agents.some(
57
+ (value) =>
58
+ value.pane_id !== child.pane &&
59
+ sessionPath(value) === child.sessionFile,
60
+ ) ||
61
+ panel.interactive_ready !== true ||
62
+ panel.launch_pending === true ||
63
+ (panel.agent_status !== "idle" && panel.agent_status !== "done") ||
64
+ !record ||
65
+ record.paneId !== child.pane ||
66
+ record.activity.phase !== "settled" ||
67
+ (record.activity.status !== "idle" && record.activity.status !== "done")
68
+ ) {
69
+ skipped += 1;
70
+ continue;
71
+ }
72
+ await runtime.client.sendMessage(panel, {
73
+ text: "/quit",
74
+ sender: '<herdr_sender kind="idle-close" />',
75
+ closeIfIdle: true,
76
+ });
77
+ closed += 1;
78
+ } catch (error) {
79
+ skipped += 1;
80
+ failures.push(
81
+ `${child.machine}:${child.pane}: ${error instanceof Error ? error.message : String(error)}`,
82
+ );
83
+ }
84
+ }
85
+ return [
86
+ `Closed ${closed} idle child sessions; skipped ${skipped}.`,
87
+ ...failures,
88
+ ].join("\n");
89
+ }
@@ -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 [
@@ -18,7 +18,9 @@ export function controlPanelStatus(options: PanelOptions): string {
18
18
  "Fleet inactive. Run Pi inside Herdr; open /herdr → Status to reconnect.",
19
19
  ]
20
20
  : []),
21
- "Open /herdr in TUI for Settings, Status and SSH Connections.",
21
+ process.env["HC_TERMINAL_SOCKET"]
22
+ ? "Open /herdr in TUI for Settings and Status. Manage machines in Herdr or with hc machine add."
23
+ : "Open /herdr in TUI for Settings, Status and SSH Connections.",
22
24
  ].join("\n");
23
25
  }
24
26
 
@@ -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];
@@ -15,7 +15,17 @@ export function buildPanelItems(
15
15
  tab: PanelTab,
16
16
  draft: SshSetupDraft,
17
17
  ): SettingItem[] {
18
- if (tab === "Connections") return sshSetupItems(draft);
18
+ if (tab === "Connections") {
19
+ if (process.env["HC_TERMINAL_SOCKET"])
20
+ return [
21
+ {
22
+ id: "core-machines",
23
+ label: "Manage machines in Herdr or with hc machine add",
24
+ currentValue: "",
25
+ },
26
+ ];
27
+ return sshSetupItems(draft);
28
+ }
19
29
  if (tab === "Status")
20
30
  return [
21
31
  {
@@ -23,7 +33,9 @@ export function buildPanelItems(
23
33
  label: "Refresh and reconnect",
24
34
  currentValue: "Enter",
25
35
  values: ["Enter"],
26
- description: "Reload Herdr profiles and retry connections.",
36
+ description: process.env["HC_TERMINAL_SOCKET"]
37
+ ? "Refresh Core machines and retry connections."
38
+ : "Reload Herdr profiles and retry connections.",
27
39
  },
28
40
  ...options.fleet.statuses().map((machine) => ({
29
41
  id: `machine:${machine.id}`,
@@ -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
 
@@ -150,8 +150,12 @@ export class PanelView {
150
150
  this.tab === "Settings"
151
151
  ? ""
152
152
  : this.tab === "Connections"
153
- ? "Remote needs Node on SSH PATH and Pi with Herdr integration. Herdr prepares its server before saving."
154
- : `${this.owners.fleet.isActive() ? "" : "Run Pi inside Herdr. "}Add SSH targets in Connections; select a machine here to reconnect.`,
153
+ ? process.env["HC_TERMINAL_SOCKET"]
154
+ ? ""
155
+ : "Remote needs Node on SSH PATH and Pi with Herdr integration. Herdr prepares its server before saving."
156
+ : process.env["HC_TERMINAL_SOCKET"]
157
+ ? "Select a machine to reconnect."
158
+ : `${this.owners.fleet.isActive() ? "" : "Run Pi inside Herdr. "}Add SSH targets in Connections; select a machine here to reconnect.`,
155
159
  ).filter((line) => line.trim()),
156
160
  "",
157
161
  ];
package/src/controller.ts CHANGED
@@ -8,10 +8,14 @@ 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 { closeIdleChildren } from "./close-idle.js";
12
+ import { controlPanelStatus, openControlPanel } from "./control-panel/index.js";
12
13
  import { sendPolicyMessage } from "./delivery.js";
13
- import type { AgentFleet } from "./fleet.js";
14
- import { activeAgentsBriefing, orchestrationGuidance } from "./messages.js";
14
+ import type { AgentFleet } from "./fleet/index.js";
15
+ import {
16
+ activeAgentsBriefing,
17
+ orchestrationGuidance,
18
+ } from "./messages/guidance.js";
15
19
  import type { createPeerCommands } from "./peer-commands.js";
16
20
  import { loadAgentProfiles } from "./profiles.js";
17
21
 
@@ -125,7 +129,7 @@ export function registerAgentController(
125
129
  },
126
130
  );
127
131
  pi.registerCommand("herdr", {
128
- description: "Shepherdr settings, status and SSH setup",
132
+ description: "Shepherdr settings, status, SSH setup and close-idle",
129
133
  handler: async (args, ctx) => {
130
134
  if (await peerCommands.handle(args, ctx)) return;
131
135
  const commandSignal = sessionLifetime.signal;
@@ -133,6 +137,11 @@ export function registerAgentController(
133
137
  const current = () =>
134
138
  !commandSignal.aborted &&
135
139
  ctx.sessionManager.getSessionId() === commandSessionId;
140
+ if (args.trim() === "close-idle") {
141
+ const result = await closeIdleChildren(fleet, ctx, current);
142
+ if (current()) ctx.ui.notify(result, "info");
143
+ return;
144
+ }
136
145
  if (args.trim()) {
137
146
  ctx.ui.notify("Open /herdr, then choose a tab.", "warning");
138
147
  return;
@@ -215,7 +224,10 @@ async function activateController(
215
224
  fleet: AgentFleet,
216
225
  ctx: ExtensionContext,
217
226
  ): Promise<boolean> {
218
- if (process.env["HERDR_ENV"] !== "1" || !process.env["HERDR_SOCKET_PATH"]) {
227
+ if (
228
+ !(process.env["HC_TERMINAL_ID"] && process.env["HC_TERMINAL_SOCKET"]) &&
229
+ (process.env["HERDR_ENV"] !== "1" || !process.env["HERDR_SOCKET_PATH"])
230
+ ) {
219
231
  ctx.ui.notify("Shepherdr requires Pi to run inside Herdr", "error");
220
232
  return false;
221
233
  }
@@ -0,0 +1,5 @@
1
+ - Shared `pane_id` is an internal address key here, not a window pane identity. Emit terminal identity; never manufacture layout/focus IDs. Scope remote addresses by permanent Core ID, not session names or mutable machine aliases.
2
+ - Remote subscriptions are invalidations: Core 0.1.14 retains old aliases after rename. Host aggregate lists omit slow machines, so supervision reads the selected Core's own list through the verified helper. An empty startup mirror requires a direct get, not rollback.
3
+ - Remote helper bundling reuses the unchanged native peer/session/context readers. Keep its data-URL relative-import map complete when those helpers gain dependencies; never edit or deploy over the legacy bridge.
4
+ - Closing a plain Core request does not cancel accepted remote execution. Keep remote watches and exec watchdogs bounded; abort local callbacks before releasing their monitor/client owner.
5
+ - Fleet teardown is synchronous. Context relay route ownership spans replacement connections: fence startup behind the previous owner's completed close, including accepted startup, and release route entries after bounded cleanup. Keep relay payload limits aligned in remote-relay.ts and context-relay.mjs; poll batches must fit raw exec/context limits after JSON escaping, not just each request.
@@ -0,0 +1,266 @@
1
+ import { hostname } from "node:os";
2
+ import type { HerdrConnection } from "../herdr-client.js";
3
+ import { openPeerChannel } from "../remote/shepherdr-channel.mjs";
4
+ import { requestContext } from "../remote/shepherdr-context.mjs";
5
+ import {
6
+ readPeerCommands,
7
+ sendPeerCommands,
8
+ sendPeerExtensionReply,
9
+ sendPeerFocus,
10
+ sendPeerMessage,
11
+ } from "../remote/shepherdr-peer.mjs";
12
+ import type {
13
+ ExtensionReply,
14
+ FocusRequest,
15
+ HerdrEvent,
16
+ PaneInfo,
17
+ PeerChannel,
18
+ PeerMessage,
19
+ } from "../types.js";
20
+ import { CoreClient } from "./client.js";
21
+ import { openCoreFocusChannel } from "./focus-channel.js";
22
+ import { object } from "./protocol.js";
23
+ import { RemoteCoreEndpoint } from "./remote-endpoint.js";
24
+ import { type CoreMachine, remoteExec } from "./remote-exec.js";
25
+ import { CoreRemoteReader } from "./remote-reader.js";
26
+ import { CoreContextRelay } from "./remote-relay.js";
27
+ import { dispatchCoreRequest } from "./request.js";
28
+
29
+ export class CoreConnection implements HerdrConnection {
30
+ private readonly lifetime = new AbortController();
31
+ private readonly focusChannels = new Set<PeerChannel>();
32
+ private relay: CoreContextRelay | undefined;
33
+ private readonly socketPath: string;
34
+ readonly core: CoreClient | RemoteCoreEndpoint;
35
+ readonly remote: CoreMachine | undefined;
36
+ readonly reader: CoreRemoteReader | undefined;
37
+ constructor(
38
+ socketPath = process.env["HC_TERMINAL_SOCKET"],
39
+ remote?: CoreMachine,
40
+ ) {
41
+ if (!socketPath)
42
+ throw new Error("Run Pi inside a Core terminal to connect Shepherdr");
43
+ this.remote = remote;
44
+ this.socketPath = socketPath;
45
+ this.core = remote
46
+ ? new RemoteCoreEndpoint(socketPath, remote)
47
+ : new CoreClient(socketPath);
48
+ this.reader =
49
+ this.core instanceof RemoteCoreEndpoint
50
+ ? new CoreRemoteReader(this.core)
51
+ : undefined;
52
+ }
53
+ close(): void {
54
+ this.lifetime.abort();
55
+ for (const channel of this.focusChannels) channel.close();
56
+ this.focusChannels.clear();
57
+ void this.relay?.close();
58
+ this.core.close();
59
+ }
60
+ async machineIdentity() {
61
+ const hello = object(await this.core.request("hello"));
62
+ const core = object(hello["core"]);
63
+ if (typeof core["id"] !== "string" || !core["id"])
64
+ throw new Error("Core returned no stable identity");
65
+ return {
66
+ host:
67
+ this.remote && typeof core["name"] === "string"
68
+ ? core["name"]
69
+ : hostname(),
70
+ session: core["id"],
71
+ };
72
+ }
73
+ requestContext(path: string, request: unknown, signal?: AbortSignal) {
74
+ if (this.core instanceof RemoteCoreEndpoint)
75
+ return remoteExec(
76
+ this.core.host,
77
+ this.core.machine,
78
+ { op: "context", path, request },
79
+ signal ? { signal } : {},
80
+ );
81
+ return requestContext(path, request, signal);
82
+ }
83
+ async startContextRelay(
84
+ threadId: string,
85
+ _routeId: string,
86
+ handler: (request: unknown, signal: AbortSignal) => Promise<unknown>,
87
+ onFailure: (error: Error) => void = () => {},
88
+ ): Promise<void> {
89
+ if (!this.remote)
90
+ throw new Error("Local context routes use the controller session");
91
+ this.lifetime.signal.throwIfAborted();
92
+ await this.relay?.close();
93
+ this.lifetime.signal.throwIfAborted();
94
+ const relay = new CoreContextRelay(this.socketPath, this.remote);
95
+ this.relay = relay;
96
+ try {
97
+ await relay.start(threadId, handler, onFailure);
98
+ } catch (error) {
99
+ await relay.close();
100
+ throw error;
101
+ }
102
+ }
103
+ contextRelayPath(): string {
104
+ if (!this.relay)
105
+ throw new Error(
106
+ "Shared context relay is unavailable; open /herdr → Status to retry sharing",
107
+ );
108
+ return this.relay.path();
109
+ }
110
+ async directory(
111
+ value: string | undefined,
112
+ fallback: string,
113
+ ): Promise<string> {
114
+ if (!(this.core instanceof RemoteCoreEndpoint))
115
+ throw new Error("Use local directory resolution on the local Core");
116
+ const result = await remoteExec(this.core.host, this.core.machine, {
117
+ op: "directory",
118
+ value,
119
+ fallback,
120
+ });
121
+ if (typeof result !== "string")
122
+ throw new Error("Remote directory returned no path");
123
+ return result;
124
+ }
125
+ async sendMessage(agent: PaneInfo, message: PeerMessage) {
126
+ if (this.core instanceof RemoteCoreEndpoint) {
127
+ const result = object(
128
+ await remoteExec(this.core.host, this.core.machine, {
129
+ op: "message",
130
+ agent,
131
+ message,
132
+ }),
133
+ );
134
+ if (
135
+ typeof result["command"] !== "boolean" ||
136
+ (result["result"] !== undefined && typeof result["result"] !== "string")
137
+ )
138
+ throw new Error(
139
+ "Remote delivery was not acknowledged; inspect the target before retrying",
140
+ );
141
+ return {
142
+ command: result["command"],
143
+ ...(typeof result["result"] === "string"
144
+ ? { result: result["result"] }
145
+ : {}),
146
+ ...(result["commands"] !== undefined
147
+ ? { commands: readPeerCommands(result["commands"]) }
148
+ : {}),
149
+ };
150
+ }
151
+ return sendPeerMessage(
152
+ (method, params) => this.request(method, params),
153
+ agent,
154
+ message,
155
+ );
156
+ }
157
+ async commands(agent: PaneInfo) {
158
+ if (this.core instanceof RemoteCoreEndpoint)
159
+ return readPeerCommands(
160
+ await remoteExec(this.core.host, this.core.machine, {
161
+ op: "commands",
162
+ agent,
163
+ }),
164
+ );
165
+ return sendPeerCommands(
166
+ (method, params) => this.request(method, params),
167
+ agent,
168
+ );
169
+ }
170
+ async replyExtension(agent: PaneInfo, reply: ExtensionReply) {
171
+ if (this.core instanceof RemoteCoreEndpoint) {
172
+ const result = await remoteExec(this.core.host, this.core.machine, {
173
+ op: "reply",
174
+ agent,
175
+ reply,
176
+ });
177
+ if (typeof result !== "string")
178
+ throw new Error(
179
+ "Remote extension reply was not acknowledged; inspect the target before retrying",
180
+ );
181
+ return result;
182
+ }
183
+ return sendPeerExtensionReply(
184
+ (method, params) => this.request(method, params),
185
+ agent,
186
+ reply,
187
+ );
188
+ }
189
+ focus(agent: PaneInfo, request: FocusRequest): Promise<unknown> {
190
+ if (this.core instanceof RemoteCoreEndpoint)
191
+ return remoteExec(this.core.host, this.core.machine, {
192
+ op: "focus",
193
+ agent,
194
+ focus: request,
195
+ });
196
+ return sendPeerFocus(
197
+ (method, params) => this.request(method, params),
198
+ agent,
199
+ request,
200
+ );
201
+ }
202
+ async openFocusChannel(
203
+ agent: PaneInfo,
204
+ request: FocusRequest,
205
+ ): Promise<PeerChannel> {
206
+ this.lifetime.signal.throwIfAborted();
207
+ const channel =
208
+ this.core instanceof RemoteCoreEndpoint
209
+ ? await openCoreFocusChannel(
210
+ this.core.host,
211
+ this.socketPath,
212
+ this.core.machine,
213
+ agent,
214
+ request,
215
+ { signal: this.lifetime.signal },
216
+ )
217
+ : await openPeerChannel(
218
+ (method, params) => this.request(method, params),
219
+ agent,
220
+ request,
221
+ );
222
+ if (this.lifetime.signal.aborted) {
223
+ channel.close();
224
+ this.lifetime.signal.throwIfAborted();
225
+ }
226
+ this.focusChannels.add(channel);
227
+ channel.onClose(() => this.focusChannels.delete(channel));
228
+ return channel;
229
+ }
230
+ async request<T>(
231
+ method: string,
232
+ params: object = {},
233
+ timeoutMs = 30_000,
234
+ ): Promise<T> {
235
+ return (await dispatchCoreRequest(
236
+ this.core,
237
+ method,
238
+ object(params),
239
+ timeoutMs,
240
+ )) as T;
241
+ }
242
+
243
+ async subscribe(
244
+ _subscriptions: object[],
245
+ onEvent: (event: HerdrEvent) => void,
246
+ onDisconnect: (error?: Error) => void,
247
+ signal?: AbortSignal,
248
+ ): Promise<() => void> {
249
+ let closed = false;
250
+ const subscription = await this.core.subscribe(
251
+ {},
252
+ (notification) => {
253
+ if (notification.method !== "heartbeat")
254
+ onEvent({ event: "core.reconcile", data: {} });
255
+ },
256
+ { ...(signal ? { signal } : {}) },
257
+ );
258
+ void subscription.closed.then((error) => {
259
+ if (!closed && !signal?.aborted) onDisconnect(error);
260
+ });
261
+ return () => {
262
+ closed = true;
263
+ subscription.close();
264
+ };
265
+ }
266
+ }