@howaboua/pi-shepherdr 0.2.24 → 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 +13 -0
- package/README.md +17 -9
- package/index.ts +2 -0
- package/package.json +5 -5
- package/src/agents-contract.ts +9 -6
- package/src/agents-discovery.ts +41 -15
- package/src/agents-focus.ts +15 -9
- package/src/agents-spawn.ts +22 -6
- package/src/agents-tool.ts +24 -6
- package/src/agents-work.ts +2 -2
- package/src/attachment.ts +2 -0
- package/src/board/host.ts +3 -1
- package/src/close-idle.ts +89 -0
- package/src/control-panel/index.ts +3 -1
- package/src/control-panel/items.ts +14 -2
- package/src/control-panel/view.ts +6 -2
- package/src/controller.ts +11 -2
- 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 +151 -122
- package/src/fleet/inspection.ts +19 -1
- package/src/fleet/machine.ts +3 -0
- package/src/fleet/monitor.ts +18 -4
- package/src/fleet/persistence.ts +26 -3
- package/src/fleet/setup.ts +54 -13
- 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/attribution.ts +15 -6
- package/src/messages/events.ts +10 -4
- package/src/messages/focus.ts +11 -2
- package/src/monitor-record.ts +9 -6
- package/src/monitor.ts +31 -0
- 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 +126 -208
- package/src/remote/deployment.ts +1 -1
- 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/settlement/collector.ts +2 -2
- package/src/settlement/index.ts +12 -0
- package/src/shared-context-host.ts +7 -3
- package/src/shared-context.ts +34 -2
- package/src/spawn-context.ts +4 -0
- package/src/spawn-ownership.ts +91 -0
- package/src/types.ts +9 -5
- package/src/worker-ownership.ts +92 -0
- package/src/worker-service.ts +12 -81
|
@@ -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
|
+
}
|
|
@@ -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
|
+
}
|