@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.
- package/CHANGELOG.md +20 -18
- package/README.md +80 -69
- package/biome.json +1 -1
- package/index.ts +4 -2
- package/package.json +14 -9
- package/src/agents-contract.ts +9 -6
- package/src/agents-discovery.ts +78 -37
- package/src/agents-focus.ts +17 -11
- package/src/agents-reply.ts +1 -1
- package/src/agents-spawn.ts +24 -8
- package/src/agents-tool.ts +26 -8
- package/src/agents-work.ts +5 -5
- package/src/attachment-notes.ts +14 -2
- package/src/attachment-protocol.ts +21 -4
- package/src/attachment-routing.ts +1 -1
- package/src/attachment-target.ts +5 -2
- package/src/attachment.ts +4 -3
- package/src/board/host.ts +5 -3
- package/src/board/membership.ts +1 -1
- package/src/close-idle.ts +89 -0
- package/src/{control-panel-actions.ts → control-panel/actions.ts} +2 -2
- package/src/{control-panel.ts → control-panel/index.ts} +7 -5
- package/src/{control-panel-items.ts → control-panel/items.ts} +17 -5
- package/src/{control-panel-view.ts → control-panel/view.ts} +9 -5
- package/src/controller.ts +17 -5
- package/src/core/AGENTS.md +5 -0
- package/src/core/backend.ts +266 -0
- package/src/core/client.ts +249 -0
- package/src/core/context-relay.mjs +111 -0
- package/src/core/focus-channel-helper.mjs +165 -0
- package/src/core/focus-channel-stream.ts +140 -0
- package/src/core/focus-channel-wire.mjs +160 -0
- package/src/core/focus-channel.ts +213 -0
- package/src/core/focus-window.ts +192 -0
- package/src/core/pi-executable.mjs +34 -0
- package/src/core/protocol.ts +116 -0
- package/src/core/registration.ts +51 -0
- package/src/core/remote-endpoint.ts +119 -0
- package/src/core/remote-exec.ts +122 -0
- package/src/core/remote-helper.mjs +244 -0
- package/src/core/remote-reader.ts +67 -0
- package/src/core/remote-relay.ts +191 -0
- package/src/core/request.ts +124 -0
- package/src/core/spawn.ts +177 -0
- package/src/core/status.ts +68 -0
- package/src/core/terminal.ts +103 -0
- package/src/fleet/catalog.ts +83 -0
- package/src/fleet/connection.ts +111 -0
- package/src/fleet/index.ts +413 -0
- package/src/fleet/inspection.ts +159 -0
- package/src/fleet/machine.ts +55 -0
- package/src/fleet/monitor.ts +85 -0
- package/src/fleet/persistence.ts +65 -0
- package/src/fleet/reconnect.ts +75 -0
- package/src/fleet/setup.ts +133 -0
- package/src/herdr.ts +25 -5
- package/src/launch-contract.ts +48 -0
- package/src/launch-location.ts +151 -0
- package/src/launch.ts +30 -183
- package/src/messages/attachments.ts +39 -0
- package/src/messages/attribution.ts +84 -0
- package/src/messages/event-details.ts +69 -0
- package/src/messages/events.ts +195 -0
- package/src/messages/focus.ts +47 -0
- package/src/messages/guidance.ts +83 -0
- package/src/messages/render.ts +89 -0
- package/src/messages/voice-announcements.ts +79 -0
- package/src/monitor-record.ts +9 -6
- package/src/monitor.ts +33 -2
- package/src/peer-commands.ts +11 -0
- package/src/peer-inbox-delivery.ts +171 -0
- package/src/peer-inbox-focus.ts +113 -0
- package/src/peer-inbox.ts +127 -209
- package/src/remote/client.ts +127 -0
- package/src/remote/context-relay.ts +84 -0
- package/src/remote/deployment.ts +179 -0
- package/src/remote/focus-channels.ts +89 -0
- package/src/remote/shepherdr-context.mjs +1 -1
- package/src/remote/shepherdr-peer.mjs +18 -5
- package/src/remote/shepherdr-session.mjs +9 -2
- package/src/remote/shepherdr.mjs +1 -1
- package/src/remote/transport.ts +369 -0
- package/src/settlement/collector.ts +122 -0
- package/src/settlement/delivery.ts +144 -0
- package/src/{settlement.ts → settlement/index.ts} +35 -233
- package/src/shared-context-host.ts +40 -14
- package/src/shared-context.ts +44 -6
- package/src/spawn-context.ts +24 -17
- package/src/spawn-ownership.ts +91 -0
- package/src/types.ts +9 -5
- package/src/voice-handoff.ts +1 -1
- package/src/worker-ownership.ts +92 -0
- package/src/worker-service.ts +14 -83
- package/src/fleet.ts +0 -702
- package/src/messages.ts +0 -637
- package/src/remote-client.ts +0 -761
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
import { Socket } from "node:net";
|
|
2
|
+
import {
|
|
3
|
+
type CoreNotification,
|
|
4
|
+
type CoreObject,
|
|
5
|
+
notification,
|
|
6
|
+
object,
|
|
7
|
+
response,
|
|
8
|
+
snapshot,
|
|
9
|
+
} from "./protocol.js";
|
|
10
|
+
|
|
11
|
+
export interface CoreRequestOptions {
|
|
12
|
+
signal?: AbortSignal;
|
|
13
|
+
/** Includes connection time. Default: 30 seconds. */
|
|
14
|
+
timeoutMs?: number;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface CoreEventFilter {
|
|
18
|
+
terminal?: string;
|
|
19
|
+
children_of?: string;
|
|
20
|
+
labels?: Record<string, string>;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface CoreSubscribeOptions extends CoreRequestOptions {
|
|
24
|
+
/** Maximum silence after the snapshot. Default: 45 seconds (Core heartbeats every 15). */
|
|
25
|
+
idleTimeoutMs?: number;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface CoreSubscription {
|
|
29
|
+
/** Resolves once: undefined for explicit close, otherwise the failure/abort reason. */
|
|
30
|
+
closed: Promise<Error | undefined>;
|
|
31
|
+
close(): void;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function timeout(value: number): number {
|
|
35
|
+
if (!Number.isSafeInteger(value) || value <= 0 || value > 2_147_483_647) {
|
|
36
|
+
throw new Error(
|
|
37
|
+
"Core timeout must be a positive integer below 2147483648 ms",
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
return value;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function failure(value: unknown): Error {
|
|
44
|
+
return value instanceof Error ? value : new Error(String(value));
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function timedOut(): Error {
|
|
48
|
+
const error = new Error("Core connection timed out");
|
|
49
|
+
error.name = "TimeoutError";
|
|
50
|
+
return error;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Plain NDJSON only. Core dedicates a connection to events after subscribing. */
|
|
54
|
+
class PlainConnection {
|
|
55
|
+
private readonly socket = new Socket();
|
|
56
|
+
private ended = false;
|
|
57
|
+
private buffer = "";
|
|
58
|
+
private timer: NodeJS.Timeout | undefined;
|
|
59
|
+
private readonly options: CoreRequestOptions;
|
|
60
|
+
private readonly onMessage: (message: CoreObject) => void;
|
|
61
|
+
private readonly onClose: (error: Error | undefined) => void;
|
|
62
|
+
private readonly abort = () => {
|
|
63
|
+
const error = new Error("Core connection cancelled", {
|
|
64
|
+
cause: this.options.signal?.reason,
|
|
65
|
+
});
|
|
66
|
+
error.name = "AbortError";
|
|
67
|
+
this.close(error);
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
constructor(
|
|
71
|
+
options: CoreRequestOptions,
|
|
72
|
+
onMessage: (message: CoreObject) => void,
|
|
73
|
+
onClose: (error: Error | undefined) => void,
|
|
74
|
+
) {
|
|
75
|
+
this.options = options;
|
|
76
|
+
this.onMessage = onMessage;
|
|
77
|
+
this.onClose = onClose;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
start(socketPath: string, payload: string): void {
|
|
81
|
+
this.socket.setEncoding("utf8");
|
|
82
|
+
this.socket.on("data", (chunk: string) => this.receive(chunk));
|
|
83
|
+
this.socket.on("error", (error) => this.close(error));
|
|
84
|
+
this.socket.on("close", () =>
|
|
85
|
+
this.close(new Error("Core connection closed")),
|
|
86
|
+
);
|
|
87
|
+
this.options.signal?.addEventListener("abort", this.abort, { once: true });
|
|
88
|
+
if (this.options.signal?.aborted) return this.abort();
|
|
89
|
+
this.setTimeout(this.options.timeoutMs ?? 30_000);
|
|
90
|
+
try {
|
|
91
|
+
this.socket.connect(socketPath, () => this.socket.write(payload));
|
|
92
|
+
} catch (error) {
|
|
93
|
+
this.close(failure(error));
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
setTimeout(ms: number): void {
|
|
98
|
+
if (this.timer) clearTimeout(this.timer);
|
|
99
|
+
this.timer = setTimeout(() => this.close(timedOut()), ms);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
close(error?: Error): void {
|
|
103
|
+
if (this.ended) return;
|
|
104
|
+
this.ended = true;
|
|
105
|
+
if (this.timer) clearTimeout(this.timer);
|
|
106
|
+
this.options.signal?.removeEventListener("abort", this.abort);
|
|
107
|
+
this.socket.destroy();
|
|
108
|
+
this.buffer = "";
|
|
109
|
+
this.onClose(error);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
private receive(chunk: string): void {
|
|
113
|
+
if (this.ended) return;
|
|
114
|
+
this.buffer += chunk;
|
|
115
|
+
try {
|
|
116
|
+
let end = this.buffer.indexOf("\n");
|
|
117
|
+
while (end !== -1 && !this.ended) {
|
|
118
|
+
const line = this.buffer.slice(0, end);
|
|
119
|
+
this.buffer = this.buffer.slice(end + 1);
|
|
120
|
+
this.checkSize(line);
|
|
121
|
+
if (line.trim()) this.onMessage(object(JSON.parse(line)));
|
|
122
|
+
end = this.buffer.indexOf("\n");
|
|
123
|
+
}
|
|
124
|
+
this.checkSize(this.buffer);
|
|
125
|
+
} catch (error) {
|
|
126
|
+
this.close(failure(error));
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
private checkSize(line: string): void {
|
|
131
|
+
// Released file/exec methods can return up to 8 MiB, base64 encoded.
|
|
132
|
+
if (Buffer.byteLength(line) > 32 * 1024 * 1024) {
|
|
133
|
+
throw new Error("Core JSON-RPC message exceeds 32 MiB");
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Connects only to the supplied local endpoint; never starts or reconnects Core.
|
|
140
|
+
* Cancellation/timeouts close the socket, not a rollback of already accepted work.
|
|
141
|
+
*/
|
|
142
|
+
export class CoreClient {
|
|
143
|
+
private readonly connections = new Set<PlainConnection>();
|
|
144
|
+
private ended = false;
|
|
145
|
+
private readonly socketPath: string;
|
|
146
|
+
|
|
147
|
+
constructor(socketPath: string) {
|
|
148
|
+
if (!socketPath) throw new Error("A Core socket path is required");
|
|
149
|
+
this.socketPath = socketPath;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Result payloads stay unknown: callers validate their chosen released API method. */
|
|
153
|
+
request(
|
|
154
|
+
method: string,
|
|
155
|
+
params: CoreObject = {},
|
|
156
|
+
options: CoreRequestOptions = {},
|
|
157
|
+
): Promise<unknown> {
|
|
158
|
+
if (method === "events.subscribe") {
|
|
159
|
+
return Promise.reject(new Error("Use CoreClient.subscribe for events"));
|
|
160
|
+
}
|
|
161
|
+
return new Promise((resolve, reject) => {
|
|
162
|
+
const connection = this.open(
|
|
163
|
+
method,
|
|
164
|
+
params,
|
|
165
|
+
options,
|
|
166
|
+
(message) => {
|
|
167
|
+
const result = response(message);
|
|
168
|
+
resolve(result);
|
|
169
|
+
connection.close();
|
|
170
|
+
},
|
|
171
|
+
(error) => reject(error ?? new Error("Core request closed")),
|
|
172
|
+
);
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* The callback receives the initial snapshot before live events. Replace terminal
|
|
178
|
+
* state on snapshot/missed; missed also requires refetching any watched documents.
|
|
179
|
+
* Old events at/below a snapshot are discarded. Sequence gaps are normal with
|
|
180
|
+
* filters, not proof of loss. No replay or continuity is promised across reconnects.
|
|
181
|
+
* Callbacks run synchronously; a thrown error closes the subscription.
|
|
182
|
+
*/
|
|
183
|
+
subscribe(
|
|
184
|
+
filter: CoreEventFilter,
|
|
185
|
+
onNotification: (message: CoreNotification) => void,
|
|
186
|
+
options: CoreSubscribeOptions = {},
|
|
187
|
+
): Promise<CoreSubscription> {
|
|
188
|
+
return new Promise((resolve, reject) => {
|
|
189
|
+
const idleTimeout = timeout(options.idleTimeoutMs ?? 45_000);
|
|
190
|
+
let initial = true;
|
|
191
|
+
let floor = 0;
|
|
192
|
+
let resolveClosed: (error: Error | undefined) => void = () => {};
|
|
193
|
+
const closed = new Promise<Error | undefined>((done) => {
|
|
194
|
+
resolveClosed = done;
|
|
195
|
+
});
|
|
196
|
+
const connection = this.open(
|
|
197
|
+
"events.subscribe",
|
|
198
|
+
{ ...filter },
|
|
199
|
+
options,
|
|
200
|
+
(message) => {
|
|
201
|
+
connection.setTimeout(idleTimeout);
|
|
202
|
+
if (initial) {
|
|
203
|
+
const result = object(response(message));
|
|
204
|
+
if (result["channel"] != null)
|
|
205
|
+
throw new Error("Expected a plain Core subscription");
|
|
206
|
+
const state = snapshot(result);
|
|
207
|
+
floor = state.seq;
|
|
208
|
+
initial = false;
|
|
209
|
+
onNotification({ method: "snapshot", ...state });
|
|
210
|
+
resolve({ closed, close: () => connection.close() });
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
const update = notification(message);
|
|
214
|
+
if (update.method === "missed") floor = update.seq;
|
|
215
|
+
if (update.method === "event" && update.event.seq <= floor) return;
|
|
216
|
+
onNotification(update);
|
|
217
|
+
},
|
|
218
|
+
(error) => {
|
|
219
|
+
reject(error ?? new Error("Core subscription closed before ready"));
|
|
220
|
+
resolveClosed(error);
|
|
221
|
+
},
|
|
222
|
+
);
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
close(): void {
|
|
227
|
+
this.ended = true;
|
|
228
|
+
for (const connection of this.connections) connection.close();
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
private open(
|
|
232
|
+
method: string,
|
|
233
|
+
params: CoreObject,
|
|
234
|
+
options: CoreRequestOptions,
|
|
235
|
+
onMessage: (message: CoreObject) => void,
|
|
236
|
+
onClose: (error: Error | undefined) => void,
|
|
237
|
+
): PlainConnection {
|
|
238
|
+
if (this.ended) throw new Error("Core client is closed");
|
|
239
|
+
timeout(options.timeoutMs ?? 30_000);
|
|
240
|
+
const payload = `${JSON.stringify({ jsonrpc: "2.0", id: 1, method, params })}\n`;
|
|
241
|
+
const connection = new PlainConnection(options, onMessage, (error) => {
|
|
242
|
+
this.connections.delete(connection);
|
|
243
|
+
onClose(error);
|
|
244
|
+
});
|
|
245
|
+
this.connections.add(connection);
|
|
246
|
+
connection.start(this.socketPath, payload);
|
|
247
|
+
return connection;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// Bounded machine.exec cannot stream. This leased mailbox retains requests only
|
|
2
|
+
// until their authenticated caller disconnects; a lost poll is never replayed.
|
|
3
|
+
// A 1,000,000-byte Notes file can expand sixfold in JSON (e.g. NULs).
|
|
4
|
+
// Leave room for Notes envelopes; context frames and raw exec stdin/stdout
|
|
5
|
+
// must remain below 8 MiB, and base64 Core frames below 16 MiB.
|
|
6
|
+
const RELAY_PAYLOAD_BYTES = 6_250_000;
|
|
7
|
+
const BATCH_BYTES = 7 * 1024 * 1024;
|
|
8
|
+
|
|
9
|
+
export async function serveRelay(input) {
|
|
10
|
+
const { listenContext, relayContextPath } = await import(
|
|
11
|
+
input.modules.context
|
|
12
|
+
);
|
|
13
|
+
const path = relayContextPath(input.threadId, input.routeId);
|
|
14
|
+
const pending = new Map();
|
|
15
|
+
let sequence = 0;
|
|
16
|
+
let wake;
|
|
17
|
+
let lastPoll = Date.now();
|
|
18
|
+
let closed = false;
|
|
19
|
+
const close = await listenContext(path, async (request, signal) => {
|
|
20
|
+
signal.throwIfAborted();
|
|
21
|
+
if (request?.relayToken === input.relayToken) {
|
|
22
|
+
if (request.action === "close") {
|
|
23
|
+
setImmediate(shutdown);
|
|
24
|
+
return true;
|
|
25
|
+
}
|
|
26
|
+
if (request.action === "reply") {
|
|
27
|
+
const entry = pending.get(request.id);
|
|
28
|
+
if (entry) {
|
|
29
|
+
pending.delete(request.id);
|
|
30
|
+
if (request.ok) entry.resolve(request.result);
|
|
31
|
+
else entry.reject(new Error(request.error));
|
|
32
|
+
}
|
|
33
|
+
return true;
|
|
34
|
+
}
|
|
35
|
+
if (request.action !== "poll") throw new Error("Invalid relay action");
|
|
36
|
+
lastPoll = Date.now();
|
|
37
|
+
if (![...pending.values()].some((entry) => !entry.sent))
|
|
38
|
+
await new Promise((resolve) => {
|
|
39
|
+
const timer = setTimeout(done, 8_000);
|
|
40
|
+
function done() {
|
|
41
|
+
clearTimeout(timer);
|
|
42
|
+
signal.removeEventListener("abort", done);
|
|
43
|
+
wake = undefined;
|
|
44
|
+
resolve();
|
|
45
|
+
}
|
|
46
|
+
wake = done;
|
|
47
|
+
signal.addEventListener("abort", done, { once: true });
|
|
48
|
+
});
|
|
49
|
+
const requests = [];
|
|
50
|
+
let bytes = 1024; // active IDs and RPC/receipt envelopes
|
|
51
|
+
for (const [id, entry] of pending) {
|
|
52
|
+
if (entry.sent) continue;
|
|
53
|
+
const value = { id, request: entry.request };
|
|
54
|
+
const size = Buffer.byteLength(JSON.stringify(value));
|
|
55
|
+
if (bytes + size > BATCH_BYTES) break;
|
|
56
|
+
requests.push(value);
|
|
57
|
+
bytes += size;
|
|
58
|
+
entry.sent = true;
|
|
59
|
+
}
|
|
60
|
+
return { requests, active: [...pending.keys()] };
|
|
61
|
+
}
|
|
62
|
+
if (closed) throw new Error("Shared context controller disconnected");
|
|
63
|
+
if (
|
|
64
|
+
pending.size >= 8 ||
|
|
65
|
+
Buffer.byteLength(JSON.stringify(request)) > RELAY_PAYLOAD_BYTES
|
|
66
|
+
)
|
|
67
|
+
throw new Error(
|
|
68
|
+
"Shared context relay is busy or request is too large; narrow the request and retry",
|
|
69
|
+
);
|
|
70
|
+
return new Promise((resolve, reject) => {
|
|
71
|
+
const id = String(++sequence);
|
|
72
|
+
const abort = () => {
|
|
73
|
+
pending.delete(id);
|
|
74
|
+
reject(new Error("Shared context caller disconnected"));
|
|
75
|
+
wake?.();
|
|
76
|
+
};
|
|
77
|
+
pending.set(id, {
|
|
78
|
+
request,
|
|
79
|
+
sent: false,
|
|
80
|
+
resolve: (value) => {
|
|
81
|
+
signal.removeEventListener("abort", abort);
|
|
82
|
+
resolve(value);
|
|
83
|
+
},
|
|
84
|
+
reject: (error) => {
|
|
85
|
+
signal.removeEventListener("abort", abort);
|
|
86
|
+
reject(error);
|
|
87
|
+
},
|
|
88
|
+
});
|
|
89
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
90
|
+
wake?.();
|
|
91
|
+
});
|
|
92
|
+
});
|
|
93
|
+
async function shutdown() {
|
|
94
|
+
if (closed) return;
|
|
95
|
+
closed = true;
|
|
96
|
+
clearInterval(lease);
|
|
97
|
+
wake?.();
|
|
98
|
+
for (const entry of pending.values())
|
|
99
|
+
entry.reject(
|
|
100
|
+
new Error(
|
|
101
|
+
"Shared context controller disconnected; reconnect its machine",
|
|
102
|
+
),
|
|
103
|
+
);
|
|
104
|
+
pending.clear();
|
|
105
|
+
await close();
|
|
106
|
+
}
|
|
107
|
+
const lease = setInterval(() => {
|
|
108
|
+
if (Date.now() - lastPoll > 30_000) void shutdown();
|
|
109
|
+
}, 1_000);
|
|
110
|
+
process.once("SIGTERM", () => void shutdown());
|
|
111
|
+
}
|
|
@@ -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
|
+
}
|