@howaboua/pi-shepherdr 0.2.26 → 0.2.28-core.11.1.gc09f7abbc5a5

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 (97) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/README.md +40 -44
  3. package/index.ts +7 -1
  4. package/package.json +5 -5
  5. package/src/agent-identity.ts +3 -3
  6. package/src/agents-contract.ts +1 -5
  7. package/src/agents-discovery.ts +20 -46
  8. package/src/agents-focus.ts +21 -20
  9. package/src/agents-spawn.ts +4 -17
  10. package/src/agents-tool.ts +7 -20
  11. package/src/agents-work.ts +4 -3
  12. package/src/attachment-protocol.ts +1 -0
  13. package/src/attachment.ts +6 -2
  14. package/src/board/host.ts +1 -1
  15. package/src/close-idle.ts +2 -9
  16. package/src/control-panel/index.ts +2 -4
  17. package/src/control-panel/items.ts +1 -11
  18. package/src/control-panel/view.ts +3 -9
  19. package/src/controller.ts +1 -4
  20. package/src/core/AGENTS.md +8 -4
  21. package/src/core/admission-broker.mjs +235 -0
  22. package/src/core/admission-endpoint.ts +180 -0
  23. package/src/core/admission-owner.mjs +52 -0
  24. package/src/core/admission-startup.ts +130 -0
  25. package/src/core/admission.ts +181 -0
  26. package/src/core/agents.ts +102 -0
  27. package/src/core/backend.ts +116 -84
  28. package/src/core/client.ts +16 -0
  29. package/src/core/focus-channel-helper.mjs +6 -27
  30. package/src/core/focus-channel-wire.mjs +9 -6
  31. package/src/core/focus-channel.ts +5 -3
  32. package/src/core/focus-window.ts +15 -4
  33. package/src/core/helper-bootstrap.mjs +70 -0
  34. package/src/core/helper-context.mjs +98 -0
  35. package/src/core/helper-core.mjs +121 -0
  36. package/src/core/machines.ts +30 -0
  37. package/src/core/registration.ts +7 -2
  38. package/src/core/remote-endpoint.ts +80 -76
  39. package/src/core/remote-helper.ts +322 -0
  40. package/src/core/remote-reader.ts +3 -42
  41. package/src/core/remote-service.mjs +241 -0
  42. package/src/core/remote-transport.ts +290 -0
  43. package/src/core/spawn.ts +21 -21
  44. package/src/core/terminal-peer.mjs +57 -0
  45. package/src/core/terminal.ts +4 -2
  46. package/src/fleet/catalog.ts +16 -58
  47. package/src/fleet/connection.ts +9 -18
  48. package/src/fleet/index.ts +38 -76
  49. package/src/fleet/inspection.ts +9 -22
  50. package/src/fleet/machine.ts +28 -12
  51. package/src/fleet/monitor.ts +8 -29
  52. package/src/fleet/persistence.ts +2 -2
  53. package/src/fleet/reconnect.ts +5 -3
  54. package/src/fleet/setup.ts +6 -16
  55. package/src/launch-contract.ts +0 -3
  56. package/src/launch-location.ts +4 -132
  57. package/src/launch.ts +18 -144
  58. package/src/messages/attribution.ts +5 -13
  59. package/src/messages/events.ts +5 -9
  60. package/src/messages/focus.ts +2 -7
  61. package/src/monitor-events.ts +14 -43
  62. package/src/monitor-extension-messages.ts +5 -6
  63. package/src/monitor-record.ts +4 -0
  64. package/src/monitor-state.ts +1 -101
  65. package/src/monitor.ts +38 -66
  66. package/src/peer-inbox.ts +21 -27
  67. package/src/remote/context-relay.ts +25 -10
  68. package/src/remote/shepherdr-channel.mjs +1 -1
  69. package/src/remote/shepherdr-checkpoints.mjs +51 -102
  70. package/src/remote/shepherdr-context.mjs +1 -1
  71. package/src/remote/shepherdr-peer.mjs +19 -24
  72. package/src/saved-context.ts +62 -0
  73. package/src/settlement/collector.ts +29 -9
  74. package/src/settlement/index.ts +25 -6
  75. package/src/shared-context-host.ts +19 -3
  76. package/src/shared-context.ts +9 -3
  77. package/src/spawn-context.ts +9 -1
  78. package/src/spawn-ownership.ts +1 -1
  79. package/src/ssh-setup.ts +40 -73
  80. package/src/types.ts +4 -8
  81. package/src/widget.ts +7 -2
  82. package/src/worker-ownership.ts +2 -8
  83. package/src/worker-service.ts +3 -13
  84. package/src/core/context-relay.mjs +0 -111
  85. package/src/core/remote-exec.ts +0 -122
  86. package/src/core/remote-helper.mjs +0 -244
  87. package/src/core/remote-relay.ts +0 -191
  88. package/src/core/request.ts +0 -124
  89. package/src/herdr-client.ts +0 -364
  90. package/src/herdr.ts +0 -268
  91. package/src/machine-catalog.ts +0 -83
  92. package/src/monitor-event.ts +0 -84
  93. package/src/remote/client.ts +0 -127
  94. package/src/remote/deployment.ts +0 -179
  95. package/src/remote/focus-channels.ts +0 -89
  96. package/src/remote/shepherdr.mjs +0 -504
  97. package/src/remote/transport.ts +0 -369
@@ -1,5 +1,4 @@
1
1
  import { hostname } from "node:os";
2
- import type { HerdrConnection } from "../herdr-client.js";
3
2
  import { openPeerChannel } from "../remote/shepherdr-channel.mjs";
4
3
  import { requestContext } from "../remote/shepherdr-context.mjs";
5
4
  import {
@@ -12,28 +11,30 @@ import {
12
11
  import type {
13
12
  ExtensionReply,
14
13
  FocusRequest,
15
- HerdrEvent,
16
14
  PaneInfo,
17
15
  PeerChannel,
18
16
  PeerMessage,
19
17
  } from "../types.js";
18
+ import { CoreAdmission } from "./admission.js";
20
19
  import { CoreClient } from "./client.js";
21
20
  import { openCoreFocusChannel } from "./focus-channel.js";
21
+ import type { CoreMachine } from "./machines.js";
22
22
  import { object } from "./protocol.js";
23
23
  import { RemoteCoreEndpoint } from "./remote-endpoint.js";
24
- import { type CoreMachine, remoteExec } from "./remote-exec.js";
25
24
  import { CoreRemoteReader } from "./remote-reader.js";
26
- import { CoreContextRelay } from "./remote-relay.js";
27
- import { dispatchCoreRequest } from "./request.js";
25
+ import { terminalPeer } from "./terminal-peer.mjs";
28
26
 
29
- export class CoreConnection implements HerdrConnection {
27
+ export class CoreConnection {
28
+ private readonly peer = terminalPeer((method, params) =>
29
+ this.core.request(method, params),
30
+ );
30
31
  private readonly lifetime = new AbortController();
31
32
  private readonly focusChannels = new Set<PeerChannel>();
32
- private relay: CoreContextRelay | undefined;
33
33
  private readonly socketPath: string;
34
34
  readonly core: CoreClient | RemoteCoreEndpoint;
35
35
  readonly remote: CoreMachine | undefined;
36
36
  readonly reader: CoreRemoteReader | undefined;
37
+ readonly admission: CoreAdmission;
37
38
  constructor(
38
39
  socketPath = process.env["HC_TERMINAL_SOCKET"],
39
40
  remote?: CoreMachine,
@@ -42,8 +43,9 @@ export class CoreConnection implements HerdrConnection {
42
43
  throw new Error("Run Pi inside a Core terminal to connect Shepherdr");
43
44
  this.remote = remote;
44
45
  this.socketPath = socketPath;
46
+ this.admission = new CoreAdmission(socketPath, remote?.id);
45
47
  this.core = remote
46
- ? new RemoteCoreEndpoint(socketPath, remote)
48
+ ? new RemoteCoreEndpoint(socketPath, remote, this.admission)
47
49
  : new CoreClient(socketPath);
48
50
  this.reader =
49
51
  this.core instanceof RemoteCoreEndpoint
@@ -52,13 +54,28 @@ export class CoreConnection implements HerdrConnection {
52
54
  }
53
55
  close(): void {
54
56
  this.lifetime.abort();
57
+ this.admission.close();
55
58
  for (const channel of this.focusChannels) channel.close();
56
59
  this.focusChannels.clear();
57
- void this.relay?.close();
58
60
  this.core.close();
59
61
  }
60
62
  async machineIdentity() {
61
63
  const hello = object(await this.core.request("hello"));
64
+ const version =
65
+ typeof hello["version"] === "string"
66
+ ? /^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(hello["version"])
67
+ : null;
68
+ if (
69
+ !version ||
70
+ !(
71
+ Number(version[1]) > 0 ||
72
+ Number(version[2]) > 1 ||
73
+ (Number(version[2]) === 1 && Number(version[3]) >= 18)
74
+ )
75
+ )
76
+ throw new Error(
77
+ "Shepherdr requires Herdr Core 0.1.18 or newer; update Core on this machine and reconnect",
78
+ );
62
79
  const core = object(hello["core"]);
63
80
  if (typeof core["id"] !== "string" || !core["id"])
64
81
  throw new Error("Core returned no stable identity");
@@ -72,40 +89,71 @@ export class CoreConnection implements HerdrConnection {
72
89
  }
73
90
  requestContext(path: string, request: unknown, signal?: AbortSignal) {
74
91
  if (this.core instanceof RemoteCoreEndpoint)
75
- return remoteExec(
76
- this.core.host,
77
- this.core.machine,
92
+ return this.core.call(
78
93
  { op: "context", path, request },
79
- signal ? { signal } : {},
94
+ { timeoutMs: 36_000, ...(signal ? { signal } : {}) },
80
95
  );
81
96
  return requestContext(path, request, signal);
82
97
  }
98
+ async readSavedSession(
99
+ path: string,
100
+ history: boolean,
101
+ signal?: AbortSignal,
102
+ ): Promise<unknown> {
103
+ if (this.core instanceof RemoteCoreEndpoint)
104
+ return this.core.call(
105
+ { op: "saved_session", path, history },
106
+ { ...(signal ? { signal } : {}) },
107
+ );
108
+ return this.admission.run(
109
+ "bulk",
110
+ async () => {
111
+ const { readSavedNotesSession } = await import(
112
+ "@howaboua/pi-notes-compaction/saved-session"
113
+ );
114
+ return readSavedNotesSession(path, signal, history);
115
+ },
116
+ signal,
117
+ );
118
+ }
119
+ async findSavedSessions(
120
+ threadId: string,
121
+ signal?: AbortSignal,
122
+ ): Promise<unknown> {
123
+ signal?.throwIfAborted();
124
+ if (this.core instanceof RemoteCoreEndpoint)
125
+ return this.core.call(
126
+ { op: "find_saved_sessions", threadId },
127
+ { ...(signal ? { signal } : {}) },
128
+ );
129
+ return this.admission.run(
130
+ "bulk",
131
+ async () => {
132
+ const { findSavedNotesSessions } = await import(
133
+ "@howaboua/pi-notes-compaction/saved-session-index"
134
+ );
135
+ return findSavedNotesSessions(threadId, undefined, signal);
136
+ },
137
+ signal,
138
+ );
139
+ }
83
140
  async startContextRelay(
84
141
  threadId: string,
85
142
  _routeId: string,
86
143
  handler: (request: unknown, signal: AbortSignal) => Promise<unknown>,
87
144
  onFailure: (error: Error) => void = () => {},
88
145
  ): Promise<void> {
89
- if (!this.remote)
146
+ if (!(this.core instanceof RemoteCoreEndpoint))
90
147
  throw new Error("Local context routes use the controller session");
91
148
  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
- }
149
+ await this.core.bridge.startContextRelay(threadId, handler, onFailure);
102
150
  }
103
151
  contextRelayPath(): string {
104
- if (!this.relay)
152
+ if (!(this.core instanceof RemoteCoreEndpoint))
105
153
  throw new Error(
106
154
  "Shared context relay is unavailable; open /herdr → Status to retry sharing",
107
155
  );
108
- return this.relay.path();
156
+ return this.core.bridge.contextRelayPath();
109
157
  }
110
158
  async directory(
111
159
  value: string | undefined,
@@ -113,7 +161,7 @@ export class CoreConnection implements HerdrConnection {
113
161
  ): Promise<string> {
114
162
  if (!(this.core instanceof RemoteCoreEndpoint))
115
163
  throw new Error("Use local directory resolution on the local Core");
116
- const result = await remoteExec(this.core.host, this.core.machine, {
164
+ const result = await this.core.call({
117
165
  op: "directory",
118
166
  value,
119
167
  fallback,
@@ -125,11 +173,14 @@ export class CoreConnection implements HerdrConnection {
125
173
  async sendMessage(agent: PaneInfo, message: PeerMessage) {
126
174
  if (this.core instanceof RemoteCoreEndpoint) {
127
175
  const result = object(
128
- await remoteExec(this.core.host, this.core.machine, {
129
- op: "message",
130
- agent,
131
- message,
132
- }),
176
+ await this.core.call(
177
+ {
178
+ op: "message",
179
+ agent,
180
+ message,
181
+ },
182
+ { timeoutMs: message.text.trim() === "/quit" ? 0 : 36_000 },
183
+ ),
133
184
  );
134
185
  if (
135
186
  typeof result["command"] !== "boolean" ||
@@ -148,56 +199,47 @@ export class CoreConnection implements HerdrConnection {
148
199
  : {}),
149
200
  };
150
201
  }
151
- return sendPeerMessage(
152
- (method, params) => this.request(method, params),
153
- agent,
154
- message,
155
- );
202
+ return sendPeerMessage(this.peer, agent, message);
156
203
  }
157
204
  async commands(agent: PaneInfo) {
158
205
  if (this.core instanceof RemoteCoreEndpoint)
159
206
  return readPeerCommands(
160
- await remoteExec(this.core.host, this.core.machine, {
207
+ await this.core.call({
161
208
  op: "commands",
162
209
  agent,
163
210
  }),
164
211
  );
165
- return sendPeerCommands(
166
- (method, params) => this.request(method, params),
167
- agent,
168
- );
212
+ return sendPeerCommands(this.peer, agent);
169
213
  }
170
214
  async replyExtension(agent: PaneInfo, reply: ExtensionReply) {
171
215
  if (this.core instanceof RemoteCoreEndpoint) {
172
- const result = await remoteExec(this.core.host, this.core.machine, {
173
- op: "reply",
174
- agent,
175
- reply,
176
- });
216
+ const result = await this.core.call(
217
+ {
218
+ op: "reply",
219
+ agent,
220
+ reply,
221
+ },
222
+ { timeoutMs: 60_000 },
223
+ );
177
224
  if (typeof result !== "string")
178
225
  throw new Error(
179
226
  "Remote extension reply was not acknowledged; inspect the target before retrying",
180
227
  );
181
228
  return result;
182
229
  }
183
- return sendPeerExtensionReply(
184
- (method, params) => this.request(method, params),
185
- agent,
186
- reply,
187
- );
230
+ return sendPeerExtensionReply(this.peer, agent, reply);
188
231
  }
189
232
  focus(agent: PaneInfo, request: FocusRequest): Promise<unknown> {
190
233
  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
- );
234
+ return this.core.call(
235
+ {
236
+ op: "focus",
237
+ agent,
238
+ focus: request,
239
+ },
240
+ { timeoutMs: 60_000 },
241
+ );
242
+ return sendPeerFocus(this.peer, agent, request);
201
243
  }
202
244
  async openFocusChannel(
203
245
  agent: PaneInfo,
@@ -214,11 +256,7 @@ export class CoreConnection implements HerdrConnection {
214
256
  request,
215
257
  { signal: this.lifetime.signal },
216
258
  )
217
- : await openPeerChannel(
218
- (method, params) => this.request(method, params),
219
- agent,
220
- request,
221
- );
259
+ : await openPeerChannel(this.peer, agent, request);
222
260
  if (this.lifetime.signal.aborted) {
223
261
  channel.close();
224
262
  this.lifetime.signal.throwIfAborted();
@@ -227,31 +265,25 @@ export class CoreConnection implements HerdrConnection {
227
265
  channel.onClose(() => this.focusChannels.delete(channel));
228
266
  return channel;
229
267
  }
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
268
  async subscribe(
244
- _subscriptions: object[],
245
- onEvent: (event: HerdrEvent) => void,
269
+ targets: string[],
270
+ onChange: () => void,
246
271
  onDisconnect: (error?: Error) => void,
247
272
  signal?: AbortSignal,
248
273
  ): Promise<() => void> {
249
274
  let closed = false;
275
+ const watched = new Set(targets);
250
276
  const subscription = await this.core.subscribe(
251
277
  {},
252
278
  (notification) => {
253
- if (notification.method !== "heartbeat")
254
- onEvent({ event: "core.reconcile", data: {} });
279
+ if (
280
+ notification.method === "snapshot" ||
281
+ notification.method === "missed" ||
282
+ (notification.method === "event" &&
283
+ notification.event.terminal &&
284
+ watched.has(notification.event.terminal))
285
+ )
286
+ onChange();
255
287
  },
256
288
  { ...(signal ? { signal } : {}) },
257
289
  );
@@ -228,6 +228,22 @@ export class CoreClient {
228
228
  for (const connection of this.connections) connection.close();
229
229
  }
230
230
 
231
+ /** Local snapshot avoids aggregate terminal.list's remote timeout/omission policy. */
232
+ async localSnapshot(): Promise<{ terminals: CoreObject[] }> {
233
+ let terminals: CoreObject[] | undefined;
234
+ const subscription = await this.subscribe({}, (event) => {
235
+ if (event.method === "snapshot")
236
+ terminals = event.terminals.filter(
237
+ (terminal) =>
238
+ typeof terminal["address"] === "string" &&
239
+ !terminal["address"].includes("/"),
240
+ );
241
+ });
242
+ subscription.close();
243
+ if (!terminals) throw new Error("Core returned no local terminal snapshot");
244
+ return { terminals };
245
+ }
246
+
231
247
  private open(
232
248
  method: string,
233
249
  params: CoreObject,
@@ -78,36 +78,12 @@ function object(value) {
78
78
  throw new Error("Invalid remote Core response");
79
79
  return /** @type {Record<string,unknown>} */ (value);
80
80
  }
81
- /** @param {string} method @param {object} params */
82
- async function nativeRequest(method, params) {
83
- const target = object(params)["target"];
84
- if (
85
- method !== "agent.get" ||
86
- typeof target !== "string" ||
87
- !/^t[0-9a-z]+$/.test(target)
88
- )
89
- throw new Error("Use an exact remote terminal identity");
90
- const record = object(await rpc("terminal.get", { terminal: target }));
91
- if (record["address"] !== target || record["state"] !== "live")
92
- throw new Error("Remote target changed or exited");
93
- const path = object(record["labels"])["pi.session_file"];
94
- if (typeof path !== "string" || !path)
95
- throw new Error("Remote target has no saved Pi session");
96
- return {
97
- agent: {
98
- pane_id: target,
99
- terminal_id: target,
100
- agent: path ? "pi" : null,
101
- agent_session: { kind: "path", value: path },
102
- },
103
- };
104
- }
105
- /** @param {{coreId:string, session:string, modules:{channel:string}, expected:import('../types.js').PaneInfo, focus:import('../types.js').FocusRequest}} input */
81
+ /** @param {{coreId:string, session:string, modules:{channel:string,terminal:string}, expected:import('../types.js').PaneInfo, focus:import('../types.js').FocusRequest}} input */
106
82
  async function admit(input) {
107
83
  const hello = object(await rpc("hello"));
108
84
  if (
109
85
  object(hello["core"])["id"] !== input.coreId ||
110
- process.env["HC_SESSION"] !== input.session
86
+ (process.env["HC_SESSION"] ?? "default") !== input.session
111
87
  )
112
88
  throw new Error(
113
89
  "Remote Core identity/session changed; refresh machines before retrying",
@@ -116,8 +92,11 @@ async function admit(input) {
116
92
  /** @type {typeof import('../remote/shepherdr-channel.mjs')} */ (
117
93
  await import(input.modules.channel)
118
94
  );
95
+ const { terminalPeer } = /** @type {typeof import('./terminal-peer.mjs')} */ (
96
+ await import(input.modules.terminal)
97
+ );
119
98
  const channel = await openPeerChannel(
120
- nativeRequest,
99
+ terminalPeer(rpc),
121
100
  input.expected,
122
101
  input.focus,
123
102
  );
@@ -9,8 +9,11 @@ const MAX_MESSAGE = 512 * 1024 + 128;
9
9
  * @param {(message:unknown)=>void} receive
10
10
  * @param {(error:Error)=>void} fail
11
11
  * @param {()=>void} [onLive]
12
+ * @param {{maxMessageBytes?:number,maxQueuedBytes?:number}} [limits]
12
13
  */
13
- export function focusWire(nonce, write, receive, fail, onLive) {
14
+ export function focusWire(nonce, write, receive, fail, onLive, limits = {}) {
15
+ const maxMessage = limits.maxMessageBytes ?? MAX_MESSAGE;
16
+ const maxQueued = limits.maxQueuedBytes ?? LIMIT;
14
17
  const prefix = `!${nonce}!`;
15
18
  let buffer = "";
16
19
  let ended = false;
@@ -78,9 +81,9 @@ export function focusWire(nonce, write, receive, fail, onLive) {
78
81
  const json = JSON.stringify(message);
79
82
  if (json === undefined) throw new Error("Focus stream requires JSON");
80
83
  const bytes = Buffer.from(json);
81
- if (bytes.length > MAX_MESSAGE)
82
- throw new Error("Focus stream message exceeds 512 KiB");
83
- if (queuedBytes + Math.ceil(bytes.length / 3) * 4 > LIMIT)
84
+ if (bytes.length > maxMessage)
85
+ throw new Error("Remote message exceeds its size limit");
86
+ if (queuedBytes + Math.ceil(bytes.length / 3) * 4 > maxQueued)
84
87
  throw new Error("Focus stream output exceeded its buffer");
85
88
  for (let at = 0; at < bytes.length; at += CHUNK) {
86
89
  const data = bytes.subarray(at, at + CHUNK).toString("base64");
@@ -140,8 +143,8 @@ export function focusWire(nonce, write, receive, fail, onLive) {
140
143
  throw new Error("Focus stream data is out of order or invalid");
141
144
  const chunk = Buffer.from(frame.data, "base64");
142
145
  chunkBytes += chunk.length;
143
- if (chunkBytes > MAX_MESSAGE)
144
- throw new Error("Focus stream message exceeds 512 KiB");
146
+ if (chunkBytes > maxMessage)
147
+ throw new Error("Remote message exceeds its size limit");
145
148
  chunks.push(chunk);
146
149
  received++;
147
150
  if (frame.end) {
@@ -5,23 +5,25 @@ import type { FocusRequest, PaneInfo, PeerChannel } from "../types.js";
5
5
  import type { CoreClient } from "./client.js";
6
6
  import { attachCoreTerminal } from "./focus-channel-stream.js";
7
7
  import { focusWire } from "./focus-channel-wire.mjs";
8
+ import type { CoreMachine } from "./machines.js";
8
9
  import { object } from "./protocol.js";
9
- import type { CoreMachine } from "./remote-exec.js";
10
10
 
11
11
  const moduleUrl = (text: string) =>
12
12
  `data:text/javascript;base64,${Buffer.from(text).toString("base64")}`;
13
13
  async function helperSources() {
14
14
  const read = (name: string) =>
15
15
  readFile(new URL(name, import.meta.url), "utf8");
16
- const [helper, wire, channel, peer] = await Promise.all([
16
+ const [helper, wire, channel, peer, terminal] = await Promise.all([
17
17
  read("./focus-channel-helper.mjs"),
18
18
  read("./focus-channel-wire.mjs"),
19
19
  read("../remote/shepherdr-channel.mjs"),
20
20
  read("../remote/shepherdr-peer.mjs"),
21
+ read("./terminal-peer.mjs"),
21
22
  ]);
22
23
  return {
23
24
  helper,
24
25
  modules: {
26
+ terminal: moduleUrl(terminal),
25
27
  wire: moduleUrl(wire),
26
28
  channel: moduleUrl(
27
29
  channel.replace(
@@ -190,7 +192,7 @@ export async function openCoreFocusChannel(
190
192
  session: machine.session,
191
193
  expected,
192
194
  focus,
193
- modules: { channel: modules.channel },
195
+ modules: { channel: modules.channel, terminal: modules.terminal },
194
196
  },
195
197
  });
196
198
  }
@@ -11,6 +11,13 @@ const exec = promisify(execFile);
11
11
  const delay = (ms: number) =>
12
12
  new Promise<void>((resolve) => setTimeout(resolve, ms));
13
13
 
14
+ function rejected(cause: unknown): Error {
15
+ return Object.assign(
16
+ cause instanceof Error ? cause : new Error(String(cause)),
17
+ { code: "SHEPHERDR_DELIVERY_REJECTED" },
18
+ );
19
+ }
20
+
14
21
  function appSocket(): string {
15
22
  return join(
16
23
  process.env["HERDR_APP_HOME"] ||
@@ -79,10 +86,10 @@ export async function focusCoreWindow(
79
86
  target: string,
80
87
  ): Promise<void> {
81
88
  if (!/^t[0-9a-z]+$/.test(target))
82
- throw new Error("Use the exact local terminal address");
89
+ throw rejected("Use the exact local terminal address");
83
90
  const socket = appSocket();
84
91
  const original = await stat(socket).catch(() => {
85
- throw new Error("Open the Herdr window on this machine and retry focus");
92
+ throw rejected("Open the Herdr window on this machine and retry focus");
86
93
  });
87
94
  const token = randomBytes(12).toString("hex");
88
95
  const name = `probe-${token}`;
@@ -90,6 +97,7 @@ export async function focusCoreWindow(
90
97
  const tab = `tb${token}`;
91
98
  let probe: string | undefined;
92
99
  let focused = false;
100
+ let dispatched = false;
93
101
  let failed = false;
94
102
  let failure: unknown;
95
103
  try {
@@ -148,6 +156,7 @@ export async function focusCoreWindow(
148
156
  };
149
157
  await checkWindow();
150
158
  if (!world.some((entry) => entry.terminal === target)) {
159
+ dispatched = true;
151
160
  await app(["do", "space.select", JSON.stringify({ id: space })]);
152
161
  await checkWindow();
153
162
  await app(["do", "terminal.keep", JSON.stringify({ terminal: target })]);
@@ -163,11 +172,12 @@ export async function focusCoreWindow(
163
172
  );
164
173
  }
165
174
  await checkWindow();
175
+ dispatched = true;
166
176
  await app(["do", "pane.focus", JSON.stringify({ terminal: target })]);
167
177
  focused = true;
168
178
  } catch (error) {
169
179
  failed = true;
170
- failure = error;
180
+ failure = dispatched ? error : rejected(error);
171
181
  } finally {
172
182
  if (probe) {
173
183
  try {
@@ -181,10 +191,11 @@ export async function focusCoreWindow(
181
191
  if (failed) throw failure;
182
192
  return;
183
193
  }
184
- throw new Error(
194
+ const cleanupFailure = new Error(
185
195
  `${focused ? "Focus succeeded" : `Focus failed: ${String(failure)}`} but its temporary terminal could not be closed: ${String(error)}`,
186
196
  { cause: failure ?? error },
187
197
  );
198
+ throw dispatched ? cleanupFailure : rejected(cleanupFailure);
188
199
  }
189
200
  }
190
201
  }
@@ -0,0 +1,70 @@
1
+ // Core owns this private terminal. Nothing touches stdout before attachment.
2
+ const bootstrap = JSON.parse(Buffer.from(process.argv[1], "base64").toString());
3
+ const { focusWire } = await import(bootstrap.wire);
4
+ let runtime;
5
+ let starting = false;
6
+ let stopped = false;
7
+ async function stop(error) {
8
+ if (stopped) return;
9
+ stopped = true;
10
+ if (error) {
11
+ try {
12
+ wire.send({ type: "error", message: error.message });
13
+ } catch {}
14
+ }
15
+ // Cleanup must finish before a replacement publishes the same context path.
16
+ const deadline = setTimeout(() => process.exit(1), 2000);
17
+ deadline.unref();
18
+ try {
19
+ await runtime?.close();
20
+ try {
21
+ wire.send({ type: "closed" });
22
+ } catch {}
23
+ } finally {
24
+ wire.close();
25
+ process.stdin.destroy();
26
+ process.stdout.end(() => process.exit(error ? 1 : 0));
27
+ }
28
+ }
29
+ const wire = focusWire(
30
+ bootstrap.nonce,
31
+ (bytes) => {
32
+ if (process.stdout.writableLength + bytes.length > 1024 * 1024)
33
+ throw new Error("Remote connection output exceeded its buffer");
34
+ process.stdout.write(bytes);
35
+ },
36
+ (value) => {
37
+ if (value?.type === "close") {
38
+ void stop();
39
+ return;
40
+ }
41
+ if (value?.type === "start" && !starting) {
42
+ starting = true;
43
+ void import(value.input.modules.helper)
44
+ .then(async ({ serve }) => {
45
+ runtime = await serve(
46
+ value.input,
47
+ (message) => wire.send(message),
48
+ stop,
49
+ );
50
+ if (stopped) {
51
+ await runtime.close();
52
+ return;
53
+ }
54
+ wire.send({ type: "ready" });
55
+ })
56
+ .catch(stop);
57
+ } else if (runtime) runtime.receive(value);
58
+ else throw new Error("Remote connection is not ready");
59
+ },
60
+ stop,
61
+ undefined,
62
+ { maxMessageBytes: 8 * 1024 * 1024, maxQueuedBytes: 24 * 1024 * 1024 },
63
+ );
64
+ process.stdin.setRawMode(true);
65
+ process.stdin.on("data", (bytes) => wire.push(bytes));
66
+ process.stdin.on("error", stop);
67
+ process.stdin.on("end", () => void stop());
68
+ process.stdout.on("error", stop);
69
+ process.on("SIGTERM", () => void stop());
70
+ process.on("SIGHUP", () => void stop());