@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
@@ -0,0 +1,165 @@
1
+ import { createConnection } from "node:net";
2
+
3
+ // This source is supplied only to an isolated, rm:true helper terminal.
4
+ const argument = process.argv[1];
5
+ const socketPath = process.env["HC_TERMINAL_SOCKET"];
6
+ if (!argument || !socketPath)
7
+ throw new Error("Start focus from a private Core terminal");
8
+ const bootstrap = JSON.parse(Buffer.from(argument, "base64").toString());
9
+ const { focusWire } = /** @type {typeof import('./focus-channel-wire.mjs')} */ (
10
+ await import(bootstrap.wire)
11
+ );
12
+ const rpcSocket = createConnection(socketPath);
13
+ let rpcBuffer = "";
14
+ let id = 0;
15
+ /** @type {Map<number,{resolve:(value:unknown)=>void,reject:(error:Error)=>void}>} */
16
+ const pending = new Map();
17
+ /** @type {import('../types.js').PeerChannel | undefined} */
18
+ let peer;
19
+ let started = false;
20
+ let stopped = false;
21
+ /** @param {Error} [error] */
22
+ function stop(error) {
23
+ if (stopped) return;
24
+ stopped = true;
25
+ if (error) {
26
+ try {
27
+ wire.send({ type: "error", message: error.message });
28
+ } catch {}
29
+ }
30
+ wire.close();
31
+ peer?.close();
32
+ rpcSocket.destroy();
33
+ for (const entry of pending.values())
34
+ entry.reject(error || new Error("Remote focus closed"));
35
+ pending.clear();
36
+ // Bound a stalled PTY flush as well as normal exit; rm:true removes this terminal.
37
+ setTimeout(() => process.exit(error ? 1 : 0), 100).unref();
38
+ process.stdin.destroy();
39
+ process.stdout.end(() => process.exit(error ? 1 : 0));
40
+ }
41
+ const wire = focusWire(
42
+ bootstrap.nonce,
43
+ (bytes) => {
44
+ if (process.stdout.writableLength + bytes.length > 1024 * 1024)
45
+ throw new Error("Remote focus output exceeded its buffer");
46
+ process.stdout.write(bytes);
47
+ },
48
+ (value) => {
49
+ if (!value || typeof value !== "object" || !("type" in value))
50
+ throw new Error("Invalid remote focus message");
51
+ if (value.type === "close") return stop();
52
+ if (value.type === "start" && !started) {
53
+ started = true;
54
+ void admit(
55
+ /** @type {Parameters<typeof admit>[0]} */ (
56
+ object("input" in value ? value.input : undefined)
57
+ ),
58
+ ).catch((error) => stop(error));
59
+ } else if (value.type === "data" && peer && "message" in value)
60
+ peer.send(value.message);
61
+ else
62
+ throw new Error("Remote focus message before admission or out of order");
63
+ },
64
+ stop,
65
+ );
66
+ /** @param {string} method @param {object} [params] */
67
+ function rpc(method, params = {}) {
68
+ return new Promise((resolve, reject) => {
69
+ pending.set(++id, { resolve, reject });
70
+ rpcSocket.write(
71
+ `${JSON.stringify({ jsonrpc: "2.0", id, method, params })}\n`,
72
+ );
73
+ });
74
+ }
75
+ /** @param {unknown} value @returns {Record<string,unknown>} */
76
+ function object(value) {
77
+ if (!value || typeof value !== "object" || Array.isArray(value))
78
+ throw new Error("Invalid remote Core response");
79
+ return /** @type {Record<string,unknown>} */ (value);
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 */
106
+ async function admit(input) {
107
+ const hello = object(await rpc("hello"));
108
+ if (
109
+ object(hello["core"])["id"] !== input.coreId ||
110
+ process.env["HC_SESSION"] !== input.session
111
+ )
112
+ throw new Error(
113
+ "Remote Core identity/session changed; refresh machines before retrying",
114
+ );
115
+ const { openPeerChannel } =
116
+ /** @type {typeof import('../remote/shepherdr-channel.mjs')} */ (
117
+ await import(input.modules.channel)
118
+ );
119
+ const channel = await openPeerChannel(
120
+ nativeRequest,
121
+ input.expected,
122
+ input.focus,
123
+ );
124
+ if (stopped) {
125
+ channel.close();
126
+ return;
127
+ }
128
+ peer = channel;
129
+ wire.send({ type: "admitted" });
130
+ channel.onClose(stop);
131
+ channel.onMessage((message) => wire.send({ type: "data", message }));
132
+ }
133
+ rpcSocket.setEncoding("utf8");
134
+ rpcSocket.on("data", (chunk) => {
135
+ try {
136
+ rpcBuffer += chunk;
137
+ if (rpcBuffer.length > 1024 * 1024)
138
+ throw new Error("Remote focus Core response exceeded its buffer");
139
+ for (;;) {
140
+ const newline = rpcBuffer.indexOf("\n");
141
+ if (newline < 0) break;
142
+ const reply = JSON.parse(rpcBuffer.slice(0, newline));
143
+ rpcBuffer = rpcBuffer.slice(newline + 1);
144
+ const entry = pending.get(reply.id);
145
+ if (!entry) throw new Error("Unexpected remote focus Core response");
146
+ pending.delete(reply.id);
147
+ if (reply.error) entry.reject(new Error(reply.error.message));
148
+ else entry.resolve(reply.result);
149
+ }
150
+ } catch (error) {
151
+ stop(error instanceof Error ? error : new Error(String(error)));
152
+ }
153
+ });
154
+ rpcSocket.on("error", stop);
155
+ rpcSocket.on("close", () => stop(new Error("Remote Core disconnected")));
156
+ process.stdin.setRawMode(true);
157
+ process.stdin.on("data", (bytes) =>
158
+ wire.push(typeof bytes === "string" ? Buffer.from(bytes) : bytes),
159
+ );
160
+ process.stdin.on("error", stop);
161
+ process.stdin.on("end", () => stop(new Error("Remote focus input closed")));
162
+ process.stdout.on("error", stop);
163
+ process.on("SIGTERM", () => stop(new Error("Remote focus terminated")));
164
+ process.on("SIGHUP", () => stop(new Error("Remote focus disconnected")));
165
+ // No application bytes before the host attaches: the first screen paint is not data.
@@ -0,0 +1,140 @@
1
+ import { Socket } from "node:net";
2
+ import { object, response } from "./protocol.js";
3
+
4
+ /** Released Core generation 1 framed attachment. Only attach a private helper. */
5
+ export function attachCoreTerminal(
6
+ socketPath: string,
7
+ terminal: string,
8
+ onData: (bytes: Buffer) => void,
9
+ onClose: (error: Error) => void,
10
+ ): { ready: Promise<void>; write(bytes: Buffer): void; close(): void } {
11
+ const socket = new Socket();
12
+ let buffer = Buffer.alloc(0);
13
+ let framed = false;
14
+ let channel = 0;
15
+ let ended = false;
16
+ let resolveReady: () => void = () => {};
17
+ let rejectReady: (error: Error) => void = () => {};
18
+ const ready = new Promise<void>((resolve, reject) => {
19
+ resolveReady = resolve;
20
+ rejectReady = reject;
21
+ });
22
+ const timer = setTimeout(
23
+ () => fail(new Error("Remote focus connection timed out")),
24
+ 15_000,
25
+ );
26
+ function close(error = new Error("Remote focus connection closed")) {
27
+ ended = true;
28
+ clearTimeout(timer);
29
+ rejectReady(error);
30
+ socket.destroy();
31
+ buffer = Buffer.alloc(0);
32
+ }
33
+ function fail(error: Error) {
34
+ if (ended) return;
35
+ close(error);
36
+ onClose(error);
37
+ }
38
+ function send(ch: number, kind: number, payload: Buffer) {
39
+ if (ended) throw new Error("Remote focus connection closed");
40
+ if (socket.writableLength + payload.length > 1024 * 1024)
41
+ throw new Error("Remote focus output exceeded its buffer");
42
+ const header = Buffer.alloc(9);
43
+ header.writeUInt32LE(ch, 0);
44
+ header[4] = kind;
45
+ header.writeUInt32LE(payload.length, 5);
46
+ socket.write(Buffer.concat([header, payload]));
47
+ }
48
+ socket.on("error", fail);
49
+ socket.on("close", () =>
50
+ fail(new Error("Remote focus connection disconnected")),
51
+ );
52
+ socket.on("data", (bytes: Buffer) => {
53
+ try {
54
+ buffer = Buffer.concat([buffer, bytes]);
55
+ if (!framed) {
56
+ const newline = buffer.indexOf(10);
57
+ if (newline < 0) {
58
+ if (buffer.length > 64 * 1024)
59
+ throw new Error("Core handshake is too large");
60
+ return;
61
+ }
62
+ const hello = object(
63
+ response(object(JSON.parse(buffer.subarray(0, newline).toString()))),
64
+ );
65
+ if (hello["generation"] !== 1 || hello["framed"] !== true)
66
+ throw new Error("Core does not support generation 1 framed streams");
67
+ buffer = buffer.subarray(newline + 1);
68
+ framed = true;
69
+ send(
70
+ 0,
71
+ 0,
72
+ Buffer.from(
73
+ JSON.stringify({
74
+ jsonrpc: "2.0",
75
+ id: 1,
76
+ method: "terminal.attach",
77
+ params: { terminal, cols: 80, rows: 24, history: 0 },
78
+ }),
79
+ ),
80
+ );
81
+ }
82
+ while (buffer.length >= 9 && !ended) {
83
+ const ch = buffer.readUInt32LE(0);
84
+ const kind = buffer[4];
85
+ const length = buffer.readUInt32LE(5);
86
+ if (length > 1024 * 1024)
87
+ throw new Error("Remote focus frame exceeds 1 MiB");
88
+ if (buffer.length < length + 9) return;
89
+ const payload = buffer.subarray(9, length + 9);
90
+ buffer = buffer.subarray(length + 9);
91
+ if (ch === 0 && kind === 0) {
92
+ const result = object(
93
+ response(object(JSON.parse(payload.toString()))),
94
+ );
95
+ if (
96
+ channel ||
97
+ typeof result["channel"] !== "number" ||
98
+ !Number.isSafeInteger(result["channel"]) ||
99
+ result["channel"] <= 0 ||
100
+ result["channel"] > 0xffffffff
101
+ )
102
+ throw new Error("Core returned an invalid helper stream");
103
+ channel = result["channel"];
104
+ clearTimeout(timer);
105
+ resolveReady();
106
+ } else if (ch === channel && kind === 0) {
107
+ onData(payload);
108
+ if (ended) return;
109
+ const credit = Buffer.alloc(4);
110
+ credit.writeUInt32LE(length);
111
+ send(channel, 1, credit);
112
+ } else if (ch === channel && kind === 2)
113
+ throw new Error("Remote focus process ended");
114
+ else throw new Error("Unexpected Remote focus stream frame");
115
+ }
116
+ } catch (error) {
117
+ fail(error instanceof Error ? error : new Error(String(error)));
118
+ }
119
+ });
120
+ socket.connect(socketPath, () =>
121
+ socket.write(
122
+ `${JSON.stringify({ jsonrpc: "2.0", id: 1, method: "hello", params: { generation: 1, framed: true } })}\n`,
123
+ ),
124
+ );
125
+ return {
126
+ ready,
127
+ close,
128
+ write(bytes) {
129
+ if (!channel) throw new Error("Remote focus stream is not ready");
130
+ try {
131
+ send(channel, 0, bytes);
132
+ } catch (error) {
133
+ const reason =
134
+ error instanceof Error ? error : new Error(String(error));
135
+ fail(reason);
136
+ throw reason;
137
+ }
138
+ },
139
+ };
140
+ }
@@ -0,0 +1,160 @@
1
+ // End-to-end credit keeps Core's terminal repaint fallback out of this stream.
2
+ const LIMIT = 1024 * 1024;
3
+ const CHUNK = 8192;
4
+ // PeerChannel's 512KiB JSON plus the transport's data envelope.
5
+ const MAX_MESSAGE = 512 * 1024 + 128;
6
+ /**
7
+ * @param {string} nonce
8
+ * @param {(bytes:Buffer)=>void} write
9
+ * @param {(message:unknown)=>void} receive
10
+ * @param {(error:Error)=>void} fail
11
+ * @param {()=>void} [onLive]
12
+ */
13
+ export function focusWire(nonce, write, receive, fail, onLive) {
14
+ const prefix = `!${nonce}!`;
15
+ let buffer = "";
16
+ let ended = false;
17
+ let heard = Date.now();
18
+ let sent = 0;
19
+ let received = 0;
20
+ let acknowledged = 0;
21
+ let queuedBytes = 0;
22
+ /** @type {Buffer[]} */
23
+ let chunks = [];
24
+ let chunkBytes = 0;
25
+ /** @type {Array<{data:string,end:boolean}>} */
26
+ const queue = [];
27
+ /** @param {object} value */
28
+ const emit = (value) => {
29
+ if (!ended)
30
+ write(
31
+ Buffer.from(
32
+ `${prefix}${Buffer.from(JSON.stringify(value)).toString("base64")}!\n`,
33
+ ),
34
+ );
35
+ };
36
+ const flush = () => {
37
+ // Four 8KiB chunks, even after base64 twice, fit below Core's 256KiB credit.
38
+ while (!ended && queue.length && sent - acknowledged < 4) {
39
+ const frame = queue.shift();
40
+ if (!frame) break;
41
+ queuedBytes -= frame.data.length;
42
+ emit({ n: ++sent, ...frame });
43
+ }
44
+ };
45
+ /** @param {unknown} error */
46
+ const failed = (error) => {
47
+ if (ended) return;
48
+ const reason = error instanceof Error ? error : new Error(String(error));
49
+ // Error control bypasses a full data queue; never hide remote overflow as EOF.
50
+ try {
51
+ emit({ error: reason.message });
52
+ } catch {}
53
+ close();
54
+ fail(reason);
55
+ };
56
+ const timer = setInterval(() => {
57
+ try {
58
+ if (Date.now() - heard > 10_000)
59
+ throw new Error("Focus stream lease expired");
60
+ emit({ ping: true });
61
+ } catch (error) {
62
+ failed(error);
63
+ }
64
+ }, 1000);
65
+ function close() {
66
+ ended = true;
67
+ clearInterval(timer);
68
+ queue.length = 0;
69
+ chunks = [];
70
+ buffer = "";
71
+ }
72
+ return {
73
+ close,
74
+ /** @param {unknown} message */
75
+ send(message) {
76
+ if (ended) throw new Error("Focus stream is closed");
77
+ try {
78
+ const json = JSON.stringify(message);
79
+ if (json === undefined) throw new Error("Focus stream requires JSON");
80
+ 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
+ throw new Error("Focus stream output exceeded its buffer");
85
+ for (let at = 0; at < bytes.length; at += CHUNK) {
86
+ const data = bytes.subarray(at, at + CHUNK).toString("base64");
87
+ queuedBytes += data.length;
88
+ queue.push({ data, end: at + CHUNK >= bytes.length });
89
+ }
90
+ flush();
91
+ } catch (error) {
92
+ failed(error);
93
+ throw error;
94
+ }
95
+ },
96
+ /** @param {Buffer} bytes */
97
+ push(bytes) {
98
+ if (ended) return;
99
+ try {
100
+ buffer += bytes.toString("ascii");
101
+ if (buffer.length > LIMIT)
102
+ throw new Error("Focus stream input exceeded its buffer");
103
+ for (;;) {
104
+ const start = buffer.indexOf(prefix);
105
+ if (start < 0) {
106
+ buffer = buffer.slice(-prefix.length);
107
+ return;
108
+ }
109
+ const end = buffer.indexOf("!", start + prefix.length);
110
+ if (end < 0) {
111
+ buffer = buffer.slice(start);
112
+ return;
113
+ }
114
+ const frame = JSON.parse(
115
+ Buffer.from(
116
+ buffer.slice(start + prefix.length, end),
117
+ "base64",
118
+ ).toString(),
119
+ );
120
+ buffer = buffer.slice(end + 1);
121
+ heard = Date.now();
122
+ if (typeof frame.error === "string") throw new Error(frame.error);
123
+ if (frame.ping === true) {
124
+ onLive?.();
125
+ continue;
126
+ }
127
+ if (Number.isSafeInteger(frame.ack)) {
128
+ if (frame.ack !== acknowledged + 1 || frame.ack > sent)
129
+ throw new Error("Focus stream acknowledgement is out of order");
130
+ acknowledged = frame.ack;
131
+ flush();
132
+ continue;
133
+ }
134
+ if (
135
+ frame.n !== received + 1 ||
136
+ typeof frame.data !== "string" ||
137
+ frame.data.length > 11000 ||
138
+ typeof frame.end !== "boolean"
139
+ )
140
+ throw new Error("Focus stream data is out of order or invalid");
141
+ const chunk = Buffer.from(frame.data, "base64");
142
+ chunkBytes += chunk.length;
143
+ if (chunkBytes > MAX_MESSAGE)
144
+ throw new Error("Focus stream message exceeds 512 KiB");
145
+ chunks.push(chunk);
146
+ received++;
147
+ if (frame.end) {
148
+ const message = JSON.parse(Buffer.concat(chunks).toString());
149
+ chunks = [];
150
+ chunkBytes = 0;
151
+ receive(message);
152
+ }
153
+ emit({ ack: received });
154
+ }
155
+ } catch (error) {
156
+ failed(error);
157
+ }
158
+ },
159
+ };
160
+ }
@@ -0,0 +1,213 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { readFile } from "node:fs/promises";
3
+ import { createBufferedChannel } from "../remote/shepherdr-channel.mjs";
4
+ import type { FocusRequest, PaneInfo, PeerChannel } from "../types.js";
5
+ import type { CoreClient } from "./client.js";
6
+ import { attachCoreTerminal } from "./focus-channel-stream.js";
7
+ import { focusWire } from "./focus-channel-wire.mjs";
8
+ import { object } from "./protocol.js";
9
+ import type { CoreMachine } from "./remote-exec.js";
10
+
11
+ const moduleUrl = (text: string) =>
12
+ `data:text/javascript;base64,${Buffer.from(text).toString("base64")}`;
13
+ async function helperSources() {
14
+ const read = (name: string) =>
15
+ readFile(new URL(name, import.meta.url), "utf8");
16
+ const [helper, wire, channel, peer] = await Promise.all([
17
+ read("./focus-channel-helper.mjs"),
18
+ read("./focus-channel-wire.mjs"),
19
+ read("../remote/shepherdr-channel.mjs"),
20
+ read("../remote/shepherdr-peer.mjs"),
21
+ ]);
22
+ return {
23
+ helper,
24
+ modules: {
25
+ wire: moduleUrl(wire),
26
+ channel: moduleUrl(
27
+ channel.replace(
28
+ '"./shepherdr-peer.mjs"',
29
+ JSON.stringify(moduleUrl(peer)),
30
+ ),
31
+ ),
32
+ },
33
+ };
34
+ }
35
+
36
+ /** Private Core terminal, authenticated native peer admission, no relay agent. */
37
+ export async function openCoreFocusChannel(
38
+ client: CoreClient,
39
+ socketPath: string,
40
+ machine: CoreMachine,
41
+ expected: PaneInfo,
42
+ focus: FocusRequest,
43
+ options: { signal?: AbortSignal } = {},
44
+ ): Promise<PeerChannel> {
45
+ if (
46
+ !/^t[0-9a-z]+$/.test(expected.pane_id) ||
47
+ expected.pane_id !== expected.terminal_id ||
48
+ expected.agent_session?.kind !== "path"
49
+ )
50
+ throw new Error(
51
+ "Resolve an exact remote Pi terminal and saved session before focus",
52
+ );
53
+ options.signal?.throwIfAborted();
54
+ const { helper, modules } = await helperSources();
55
+ const nonce = randomBytes(8).toString("hex");
56
+ // Only the wire bootstrap belongs in argv; peer modules and focus data travel
57
+ // over its bounded, credited start frame, below Windows' CreateProcessW limit.
58
+ const argv = [
59
+ "node",
60
+ "--input-type=module",
61
+ "-e",
62
+ helper,
63
+ Buffer.from(JSON.stringify({ nonce, wire: modules.wire })).toString(
64
+ "base64",
65
+ ),
66
+ ];
67
+ // Worst-case Windows quoting, with room for the resolved Node executable path.
68
+ if (argv.reduce((size, arg) => size + arg.length * 2 + 3, 0) > 30_000)
69
+ throw new Error(
70
+ "Remote focus launcher is too large; update Shepherdr before retrying",
71
+ );
72
+ let terminal: string | undefined;
73
+ let stream: ReturnType<typeof attachCoreTerminal> | undefined;
74
+ let wire: ReturnType<typeof focusWire> | undefined;
75
+ let ended = false;
76
+ let started = false;
77
+ let admitted = false;
78
+ let resolveAdmission: () => void = () => {};
79
+ let rejectAdmission: (error: Error) => void = () => {};
80
+ const admission = new Promise<void>((resolve, reject) => {
81
+ resolveAdmission = resolve;
82
+ rejectAdmission = reject;
83
+ });
84
+ // Startup may fail before we reach await admission.
85
+ void admission.catch(() => {});
86
+ const state = createBufferedChannel(
87
+ (message) => {
88
+ if (!admitted || !wire) throw new Error("Focus channel is not admitted");
89
+ wire.send({ type: "data", message });
90
+ },
91
+ () => stop(new Error("Focus channel closed")),
92
+ );
93
+ const timer = setTimeout(
94
+ () =>
95
+ stop(
96
+ new Error(
97
+ "Remote focus admission timed out; inspect the destination before retrying",
98
+ ),
99
+ ),
100
+ 60_000,
101
+ );
102
+ function stop(error: Error) {
103
+ if (ended) return;
104
+ ended = true;
105
+ clearTimeout(timer);
106
+ options.signal?.removeEventListener("abort", abort);
107
+ rejectAdmission(error);
108
+ try {
109
+ wire?.send({ type: "close" });
110
+ } catch {}
111
+ wire?.close();
112
+ stream?.close();
113
+ state.fail(error);
114
+ // The remote lease also removes the rm:true terminal if this request cannot reach it.
115
+ if (terminal)
116
+ void client
117
+ .request("terminal.kill", { terminal }, { timeoutMs: 5000 })
118
+ .catch(() => {});
119
+ }
120
+ function abort() {
121
+ stop(
122
+ new Error("Remote focus channel cancelled", {
123
+ cause: options.signal?.reason,
124
+ }),
125
+ );
126
+ }
127
+ options.signal?.addEventListener("abort", abort, { once: true });
128
+ if (options.signal?.aborted) abort();
129
+ try {
130
+ if (ended) throw new Error("Remote focus channel cancelled during startup");
131
+ const created = object(
132
+ await client.request(
133
+ "terminal.run",
134
+ {
135
+ on: machine.id,
136
+ argv,
137
+ name: `focus-${nonce}`,
138
+ no_parent: true,
139
+ no_notify: true,
140
+ rm: true,
141
+ },
142
+ { timeoutMs: 20_000 },
143
+ ),
144
+ );
145
+ const address = created["address"];
146
+ if (
147
+ typeof address !== "string" ||
148
+ !address.startsWith(`${machine.name}/`) ||
149
+ !/^t[0-9a-z]+$/.test(address.slice(machine.name.length + 1))
150
+ )
151
+ throw new Error("Core returned an unexpected private focus terminal");
152
+ terminal = `${machine.id}/${address.slice(machine.name.length + 1)}`;
153
+ if (ended) {
154
+ void client
155
+ .request("terminal.kill", { terminal }, { timeoutMs: 5000 })
156
+ .catch(() => {});
157
+ throw new Error("Remote focus channel cancelled during startup");
158
+ }
159
+ wire = focusWire(
160
+ nonce,
161
+ (bytes) => {
162
+ if (!stream) throw new Error("Remote focus stream is unavailable");
163
+ stream.write(bytes);
164
+ },
165
+ (value) => {
166
+ const frame = object(value);
167
+ if (frame["type"] === "admitted" && !admitted) {
168
+ admitted = true;
169
+ clearTimeout(timer);
170
+ resolveAdmission();
171
+ } else if (frame["type"] === "data" && admitted && "message" in frame)
172
+ state.receive(frame["message"]);
173
+ else if (frame["type"] === "error")
174
+ throw new Error(
175
+ typeof frame["message"] === "string"
176
+ ? frame["message"]
177
+ : "Remote focus failed",
178
+ );
179
+ else
180
+ throw new Error("Remote focus connection sent an invalid response");
181
+ },
182
+ stop,
183
+ () => {
184
+ if (!started) {
185
+ started = true;
186
+ wire?.send({
187
+ type: "start",
188
+ input: {
189
+ coreId: machine.id,
190
+ session: machine.session,
191
+ expected,
192
+ focus,
193
+ modules: { channel: modules.channel },
194
+ },
195
+ });
196
+ }
197
+ },
198
+ );
199
+ stream = attachCoreTerminal(
200
+ socketPath,
201
+ terminal,
202
+ (bytes) => wire?.push(bytes),
203
+ stop,
204
+ );
205
+ await stream.ready;
206
+ await admission;
207
+ return state.channel;
208
+ } catch (error) {
209
+ const reason = error instanceof Error ? error : new Error(String(error));
210
+ stop(reason);
211
+ throw reason;
212
+ }
213
+ }