@firstpick/pi-package-webui 0.7.6 → 0.7.7
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/README.md +37 -4
- package/bin/pi-webui-rpc-supervisor.mjs +518 -0
- package/bin/pi-webui.mjs +1003 -82
- package/lib/WEBUI_TUI_NATIVE_PARITY.json +13 -0
- package/lib/rpc-supervisor-client.mjs +301 -0
- package/lib/rpc-supervisor-protocol.mjs +236 -0
- package/lib/rpc-supervisor-state.mjs +165 -0
- package/lib/trust-boundaries.mjs +1 -0
- package/package.json +2 -2
- package/public/app.js +1237 -82
- package/public/index.html +334 -25
- package/public/service-worker.js +6 -1
- package/public/styles.css +366 -52
- package/public/subagent-gate-visibility.mjs +36 -0
- package/public/workflow-status-stack.mjs +69 -0
- package/tests/app-runner-process-tree-harness.test.mjs +37 -3
- package/tests/boot-failure-diagnostics.test.mjs +180 -0
- package/tests/durable-rpc-supervisor-harness.test.mjs +252 -0
- package/tests/fast-mode-client-static.test.mjs +2 -2
- package/tests/fixtures/compacting-pi.mjs +0 -0
- package/tests/fixtures/fake-pi.mjs +81 -2
- package/tests/git-panel-file-preview-static.test.mjs +221 -0
- package/tests/http-endpoints-harness.test.mjs +458 -33
- package/tests/mobile-static.test.mjs +74 -12
- package/tests/native-parity-harness.test.mjs +2 -1
- package/tests/native-parity.test.mjs +11 -0
- package/tests/numpad-decimal-input-static.test.mjs +128 -0
- package/tests/prompt-routing-input-clear-static.test.mjs +34 -0
- package/tests/prompt-routing-tab-status.test.mjs +103 -0
- package/tests/rpc-supervisor-host.test.mjs +275 -0
- package/tests/rpc-supervisor-protocol.test.mjs +67 -0
- package/tests/rpc-supervisor-state.test.mjs +62 -0
- package/tests/run-all.mjs +4 -1
- package/tests/streaming-ui-coupling.test.mjs +15 -0
- package/tests/subagent-gate-visibility.test.mjs +66 -0
- package/tests/subagent-launch-slots-static.test.mjs +1 -1
- package/tests/subagents-helper.test.mjs +136 -0
- package/tests/workflow-status-stack.test.mjs +87 -0
- package/webui-rpc-helper.mjs +160 -2
|
@@ -43,6 +43,19 @@
|
|
|
43
43
|
"currentBehavior": "Browser-native dialog and Pi TUI wizard edit one persisted global Guided Git profile, including generation model/effort and safety-oriented workflow defaults.",
|
|
44
44
|
"targetBehavior": "Keep the Pi TUI and browser-native setup surfaces aligned with the shared persisted preference schema."
|
|
45
45
|
},
|
|
46
|
+
{
|
|
47
|
+
"id": "/workflow-setup",
|
|
48
|
+
"kind": "slash-command",
|
|
49
|
+
"category": "native-command",
|
|
50
|
+
"title": "Workflow permission ceiling setup",
|
|
51
|
+
"command": { "name": "workflow-setup", "description": "Review and save the global workflow permission ceiling" },
|
|
52
|
+
"webStatus": "implemented",
|
|
53
|
+
"priority": "P1",
|
|
54
|
+
"sensitive": true,
|
|
55
|
+
"guards": ["localhost", "confirmation"],
|
|
56
|
+
"currentBehavior": "Catalog-gated exact command routing and the Options menu open a browser-native reviewed policy editor backed by localhost-only revision-protected GET/POST routes; it never starts an agent turn.",
|
|
57
|
+
"targetBehavior": "Keep browser and Pi TUI setup aligned with the canonical strict policy validator, deny defaults, explicit normalized review, and stale-write protection."
|
|
58
|
+
},
|
|
46
59
|
{
|
|
47
60
|
"id": "/model",
|
|
48
61
|
"kind": "slash-command",
|
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { createConnection } from "node:net";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
5
|
+
import {
|
|
6
|
+
RPC_SUPERVISOR_PROTOCOL,
|
|
7
|
+
RpcSupervisorProtocolError,
|
|
8
|
+
assertProtocolCompatible,
|
|
9
|
+
encodeFrame,
|
|
10
|
+
frameReader,
|
|
11
|
+
newRequestId,
|
|
12
|
+
} from "./rpc-supervisor-protocol.mjs";
|
|
13
|
+
import {
|
|
14
|
+
acquireStartupLock,
|
|
15
|
+
defaultAgentDir,
|
|
16
|
+
readSupervisorState,
|
|
17
|
+
removeSupervisorState,
|
|
18
|
+
sanitizedSupervisorEnvironment,
|
|
19
|
+
supervisorPaths,
|
|
20
|
+
supervisorPidIsAlive,
|
|
21
|
+
waitForSupervisorState,
|
|
22
|
+
} from "./rpc-supervisor-state.mjs";
|
|
23
|
+
|
|
24
|
+
const DEFAULT_CONNECT_TIMEOUT_MS = 2_500;
|
|
25
|
+
const DEFAULT_ATTACH_TIMEOUT_MS = 2_500;
|
|
26
|
+
const DEFAULT_STARTUP_TIMEOUT_MS = 8_000;
|
|
27
|
+
const supervisorScript = fileURLToPath(new URL("../bin/pi-webui-rpc-supervisor.mjs", import.meta.url));
|
|
28
|
+
|
|
29
|
+
function deferred() {
|
|
30
|
+
let resolve;
|
|
31
|
+
let reject;
|
|
32
|
+
const promise = new Promise((onResolve, onReject) => { resolve = onResolve; reject = onReject; });
|
|
33
|
+
return { promise, resolve, reject };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function replacementConnectionError(error) {
|
|
37
|
+
return error?.code === "ECONNREFUSED" || error?.code === "ENOENT";
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function transientConnectionError(error) {
|
|
41
|
+
return error?.code === "EPIPE" || error?.code === "ECONNRESET";
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function liveStateError(state) {
|
|
45
|
+
return Object.assign(new Error(`Refusing to replace RPC supervisor ${state.pid}: its recorded PID is still alive`), {
|
|
46
|
+
code: "RPC_SUPERVISOR_LIVE_STATE",
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function openSocket(socketPath, timeoutMs = DEFAULT_CONNECT_TIMEOUT_MS) {
|
|
51
|
+
return new Promise((resolve, reject) => {
|
|
52
|
+
const socket = createConnection(socketPath);
|
|
53
|
+
const timer = setTimeout(() => {
|
|
54
|
+
socket.destroy();
|
|
55
|
+
reject(new Error(`Timed out connecting to RPC supervisor after ${timeoutMs}ms`));
|
|
56
|
+
}, timeoutMs);
|
|
57
|
+
socket.once("connect", () => { clearTimeout(timer); resolve(socket); });
|
|
58
|
+
socket.once("error", (error) => { clearTimeout(timer); reject(error); });
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export class RpcSupervisorClient {
|
|
63
|
+
constructor({ socket, state, controllerId = randomUUID(), cursor, paths, attachTimeoutMs = DEFAULT_ATTACH_TIMEOUT_MS }) {
|
|
64
|
+
this.socket = socket;
|
|
65
|
+
this.state = state;
|
|
66
|
+
this.paths = paths;
|
|
67
|
+
this.controllerId = controllerId;
|
|
68
|
+
this.cursor = cursor;
|
|
69
|
+
this.attachTimeoutMs = attachTimeoutMs;
|
|
70
|
+
this.connected = true;
|
|
71
|
+
this.attached = false;
|
|
72
|
+
this.pending = new Map();
|
|
73
|
+
this.events = new Set();
|
|
74
|
+
this.startupEvents = [];
|
|
75
|
+
this.startupBuffering = true;
|
|
76
|
+
this.snapshot = null;
|
|
77
|
+
this.attachTimer = null;
|
|
78
|
+
this.attachDeferred = deferred();
|
|
79
|
+
this.attachDeferred.promise.catch(() => {});
|
|
80
|
+
this.#listen();
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
#listen() {
|
|
84
|
+
const consume = frameReader((frame) => this.#receive(frame), (error) => this.#fail(error));
|
|
85
|
+
this.socket.on("data", consume);
|
|
86
|
+
this.socket.on("error", (error) => this.#fail(error));
|
|
87
|
+
this.socket.on("close", () => this.#fail(new Error("RPC supervisor connection closed")));
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
#dispatchEvent(frame) {
|
|
91
|
+
for (const listener of this.events) {
|
|
92
|
+
try { listener(frame); } catch { /* listeners are server-owned */ }
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
#receive(frame) {
|
|
97
|
+
if (frame.type === "attached") {
|
|
98
|
+
try { assertProtocolCompatible(frame.version); } catch (error) { this.#fail(error); return; }
|
|
99
|
+
if (this.attachTimer) clearTimeout(this.attachTimer);
|
|
100
|
+
this.attachTimer = null;
|
|
101
|
+
this.attached = true;
|
|
102
|
+
this.snapshot = frame;
|
|
103
|
+
this.attachDeferred.resolve(frame);
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
if (frame.type === "result" && typeof frame.requestId === "string") {
|
|
107
|
+
const pending = this.pending.get(frame.requestId);
|
|
108
|
+
if (!pending) return;
|
|
109
|
+
this.pending.delete(frame.requestId);
|
|
110
|
+
if (frame.ok === false) pending.reject(Object.assign(new Error(frame.error || "Supervisor operation failed"), { code: frame.code }));
|
|
111
|
+
else pending.resolve(frame.data);
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
// Authentication, version, and other attach failures are intentionally
|
|
115
|
+
// untagged because no requestId exists before attachment completes.
|
|
116
|
+
if (!this.attached && frame.type === "result" && frame.ok === false) {
|
|
117
|
+
this.#fail(Object.assign(new Error(frame.error || "RPC supervisor attach failed"), { code: frame.code || "RPC_SUPERVISOR_ATTACH" }));
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
if (frame.type === "event") {
|
|
121
|
+
this.cursor = { epoch: frame.epoch, seq: frame.seq };
|
|
122
|
+
if (this.startupBuffering) this.startupEvents.push(frame);
|
|
123
|
+
else this.#dispatchEvent(frame);
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
if (frame.type === "fenced") this.#fail(Object.assign(new Error("RPC supervisor controller was fenced by a newer server"), { code: "RPC_SUPERVISOR_FENCED" }));
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
#fail(error) {
|
|
130
|
+
if (!this.connected) return;
|
|
131
|
+
this.connected = false;
|
|
132
|
+
this.attached = false;
|
|
133
|
+
if (this.attachTimer) clearTimeout(this.attachTimer);
|
|
134
|
+
this.attachTimer = null;
|
|
135
|
+
this.attachDeferred.reject(error);
|
|
136
|
+
for (const pending of this.pending.values()) pending.reject(error);
|
|
137
|
+
this.pending.clear();
|
|
138
|
+
if (!this.socket.destroyed) this.socket.destroy();
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
#write(frame) {
|
|
142
|
+
if (!this.connected || this.socket.destroyed) throw new Error("RPC supervisor is not connected");
|
|
143
|
+
this.socket.write(encodeFrame(frame));
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
async attach() {
|
|
147
|
+
if (!this.attachTimer) {
|
|
148
|
+
this.attachTimer = setTimeout(() => {
|
|
149
|
+
this.#fail(Object.assign(new Error(`Timed out attaching to RPC supervisor after ${this.attachTimeoutMs}ms`), { code: "RPC_SUPERVISOR_ATTACH_TIMEOUT" }));
|
|
150
|
+
}, this.attachTimeoutMs);
|
|
151
|
+
this.attachTimer.unref?.();
|
|
152
|
+
}
|
|
153
|
+
try {
|
|
154
|
+
this.#write({
|
|
155
|
+
type: "attach",
|
|
156
|
+
version: RPC_SUPERVISOR_PROTOCOL,
|
|
157
|
+
scopeId: this.state.scopeId,
|
|
158
|
+
token: this.state.token,
|
|
159
|
+
controllerId: this.controllerId,
|
|
160
|
+
...(this.cursor ? { cursor: this.cursor } : {}),
|
|
161
|
+
});
|
|
162
|
+
} catch (error) {
|
|
163
|
+
this.#fail(error);
|
|
164
|
+
}
|
|
165
|
+
return this.attachDeferred.promise;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
onEvent(listener) {
|
|
169
|
+
this.events.add(listener);
|
|
170
|
+
return () => this.events.delete(listener);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Deliver live events received after `attached` only after the caller has
|
|
175
|
+
* hydrated snapshot/replay state. This preserves ordering without dropping
|
|
176
|
+
* events for tabs whose listener did not exist during attachment.
|
|
177
|
+
*/
|
|
178
|
+
drainStartupEvents() {
|
|
179
|
+
const events = this.startupEvents;
|
|
180
|
+
this.startupEvents = [];
|
|
181
|
+
this.startupBuffering = false;
|
|
182
|
+
for (const event of events) this.#dispatchEvent(event);
|
|
183
|
+
return events;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
isConnected() { return this.connected && this.attached; }
|
|
187
|
+
|
|
188
|
+
request(type, payload = {}, { requestId = newRequestId() } = {}) {
|
|
189
|
+
if (!this.attached) return Promise.reject(new Error("RPC supervisor client is not attached"));
|
|
190
|
+
if (this.pending.has(requestId)) return this.pending.get(requestId).promise;
|
|
191
|
+
const result = deferred();
|
|
192
|
+
this.pending.set(requestId, result);
|
|
193
|
+
try {
|
|
194
|
+
this.#write({ type, requestId, ...payload });
|
|
195
|
+
} catch (error) {
|
|
196
|
+
this.pending.delete(requestId);
|
|
197
|
+
result.reject(error);
|
|
198
|
+
}
|
|
199
|
+
return result.promise;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
createTab({ tabId, metadata, child }, options) { return this.request("create", { tabId, metadata, child }, options); }
|
|
203
|
+
updateTab(tabId, metadata, options) { return this.request("update", { tabId, metadata }, options); }
|
|
204
|
+
replaceTab({ tabId, metadata, child }, options) { return this.request("replace", { tabId, metadata, child }, options); }
|
|
205
|
+
closeTab(tabId, options) { return this.request("close", { tabId }, options); }
|
|
206
|
+
command(tabId, command, { requestId = newRequestId(), timeoutMs } = {}) {
|
|
207
|
+
return this.request("command", { tabId, command, ...(timeoutMs ? { timeoutMs } : {}) }, { requestId });
|
|
208
|
+
}
|
|
209
|
+
// Resolves when the supervisor has written the raw object to Pi stdin; it
|
|
210
|
+
// deliberately never waits for a Pi response frame.
|
|
211
|
+
write(tabId, command, { requestId = newRequestId() } = {}) {
|
|
212
|
+
return this.request("write", { tabId, command }, { requestId });
|
|
213
|
+
}
|
|
214
|
+
ack(cursor = this.cursor, options) { return this.request("ack", { cursor }, options); }
|
|
215
|
+
prepareHandoff(options) { return this.request("prepare_handoff", {}, options); }
|
|
216
|
+
detach(options) { return this.request("detach", {}, options); }
|
|
217
|
+
shutdown(options) { return this.request("shutdown", {}, options); }
|
|
218
|
+
|
|
219
|
+
close() {
|
|
220
|
+
if (!this.connected) return;
|
|
221
|
+
this.socket.end();
|
|
222
|
+
this.socket.destroy();
|
|
223
|
+
this.#fail(new Error("RPC supervisor client closed"));
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
export async function connectRpcSupervisor({ agentDir = defaultAgentDir(), port, controllerId, cursor, connectTimeoutMs = DEFAULT_CONNECT_TIMEOUT_MS, runtimeDir } = {}) {
|
|
228
|
+
const paths = await supervisorPaths({ agentDir, port, runtimeDir });
|
|
229
|
+
const state = await readSupervisorState(paths);
|
|
230
|
+
if (!state) return null;
|
|
231
|
+
assertProtocolCompatible(state.version);
|
|
232
|
+
const socket = await openSocket(state.socketPath, connectTimeoutMs);
|
|
233
|
+
const client = new RpcSupervisorClient({ socket, state, controllerId, cursor, paths });
|
|
234
|
+
await client.attach();
|
|
235
|
+
return client;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async function startSupervisor({ agentDir, port, runtimeDir, startupTimeoutMs, environment, script }) {
|
|
239
|
+
const paths = await supervisorPaths({ agentDir, port, runtimeDir });
|
|
240
|
+
const release = await acquireStartupLock(paths);
|
|
241
|
+
if (!release) return false;
|
|
242
|
+
try {
|
|
243
|
+
// A reset or a stale pathname is not proof that its recorded owner died.
|
|
244
|
+
// Under the exclusive lock, replace only a descriptor whose PID is known
|
|
245
|
+
// dead; a live owner must be repaired rather than split into two hosts.
|
|
246
|
+
const already = await readSupervisorState(paths);
|
|
247
|
+
if (already) {
|
|
248
|
+
if (supervisorPidIsAlive(already.pid)) throw liveStateError(already);
|
|
249
|
+
const removed = await removeSupervisorState(paths, { removeSocket: true, instanceId: already.instanceId });
|
|
250
|
+
if (!removed) throw new Error("RPC supervisor state changed while replacing a confirmed-dead owner");
|
|
251
|
+
}
|
|
252
|
+
const child = spawn(process.execPath, [script || supervisorScript, "--agent-dir", agentDir, "--port", String(port), ...(runtimeDir ? ["--runtime-dir", runtimeDir] : [])], {
|
|
253
|
+
detached: true,
|
|
254
|
+
stdio: "ignore",
|
|
255
|
+
windowsHide: true,
|
|
256
|
+
env: sanitizedSupervisorEnvironment(environment || process.env),
|
|
257
|
+
});
|
|
258
|
+
child.unref();
|
|
259
|
+
const state = await waitForSupervisorState(paths, { timeoutMs: startupTimeoutMs });
|
|
260
|
+
if (!state) throw new Error(`RPC supervisor did not publish state within ${startupTimeoutMs}ms`);
|
|
261
|
+
assertProtocolCompatible(state.version);
|
|
262
|
+
return true;
|
|
263
|
+
} finally {
|
|
264
|
+
await release();
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** Discover, attach, or atomically launch a detached owner for one agent-dir/port scope. */
|
|
269
|
+
export async function discoverStartAttachRpcSupervisor(options = {}) {
|
|
270
|
+
const settings = {
|
|
271
|
+
agentDir: options.agentDir || defaultAgentDir(),
|
|
272
|
+
port: Number(options.port),
|
|
273
|
+
runtimeDir: options.runtimeDir,
|
|
274
|
+
controllerId: options.controllerId || randomUUID(),
|
|
275
|
+
cursor: options.cursor,
|
|
276
|
+
connectTimeoutMs: options.connectTimeoutMs || DEFAULT_CONNECT_TIMEOUT_MS,
|
|
277
|
+
startupTimeoutMs: options.startupTimeoutMs || DEFAULT_STARTUP_TIMEOUT_MS,
|
|
278
|
+
};
|
|
279
|
+
try {
|
|
280
|
+
const existing = await connectRpcSupervisor(settings);
|
|
281
|
+
if (existing) return existing;
|
|
282
|
+
} catch (error) {
|
|
283
|
+
// A live pipe reset is ambiguous. Starting another detached owner could
|
|
284
|
+
// duplicate a command or strand the original Pi child, so fail closed.
|
|
285
|
+
if (transientConnectionError(error) || !replacementConnectionError(error)) throw error;
|
|
286
|
+
}
|
|
287
|
+
await startSupervisor({ ...settings, environment: options.environment, script: options.supervisorScript });
|
|
288
|
+
const deadline = Date.now() + settings.startupTimeoutMs;
|
|
289
|
+
let lastError;
|
|
290
|
+
while (Date.now() < deadline) {
|
|
291
|
+
try {
|
|
292
|
+
const client = await connectRpcSupervisor(settings);
|
|
293
|
+
if (client) return client;
|
|
294
|
+
} catch (error) {
|
|
295
|
+
lastError = error;
|
|
296
|
+
if (transientConnectionError(error) || !replacementConnectionError(error)) throw error;
|
|
297
|
+
}
|
|
298
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
299
|
+
}
|
|
300
|
+
throw lastError || new Error("RPC supervisor state was not available after startup");
|
|
301
|
+
}
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import { randomUUID, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { StringDecoder } from "node:string_decoder";
|
|
3
|
+
|
|
4
|
+
export const RPC_SUPERVISOR_PROTOCOL = Object.freeze({ major: 1, minor: 0 });
|
|
5
|
+
// Pi permits one bounded JSONL record this large. IPC envelopes need a small
|
|
6
|
+
// additional allowance so a single valid Pi record can always be forwarded.
|
|
7
|
+
export const PI_RPC_JSONL_LINE_MAX_BYTES = 32 * 1024 * 1024;
|
|
8
|
+
export const RPC_SUPERVISOR_MAX_FRAME_BYTES = PI_RPC_JSONL_LINE_MAX_BYTES + 1024 * 1024;
|
|
9
|
+
export const RPC_SUPERVISOR_EVENT_RING_LIMIT = 512;
|
|
10
|
+
// Retained replay must fit comfortably inside one attach frame even alongside
|
|
11
|
+
// tab snapshots. A live record larger than this is forwarded but omitted from
|
|
12
|
+
// replay, which produces an explicit gap for affected cursors.
|
|
13
|
+
export const RPC_SUPERVISOR_EVENT_RING_MAX_BYTES = 4 * 1024 * 1024;
|
|
14
|
+
export const RPC_SUPERVISOR_REQUEST_DEDUPE_LIMIT = 2048;
|
|
15
|
+
export const RPC_SUPERVISOR_TAB_LIMIT = 64;
|
|
16
|
+
export const RPC_SUPERVISOR_METADATA_MAX_BYTES = 64 * 1024;
|
|
17
|
+
export const RPC_SUPERVISOR_ID_MAX_LENGTH = 128;
|
|
18
|
+
// This applies only to persisted metadata, state, and journals. Live Pi RPC
|
|
19
|
+
// command, response, and event payloads are byte-faithful transport data.
|
|
20
|
+
export const RPC_SUPERVISOR_SECRET_KEY = /(token|secret|password|authorization|api.?key|credential|cookie)/i;
|
|
21
|
+
|
|
22
|
+
const REQUEST_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
|
|
23
|
+
const TAB_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
|
|
24
|
+
const SCOPE_ID = /^[a-f0-9]{64}$/;
|
|
25
|
+
const SEQ = /^(?:0|[1-9][0-9]{0,19})$/;
|
|
26
|
+
const OPERATION_TYPES = new Set(["create", "update", "replace", "close", "command", "write", "ack", "prepare_handoff", "detach", "shutdown"]);
|
|
27
|
+
|
|
28
|
+
export class RpcSupervisorProtocolError extends Error {
|
|
29
|
+
constructor(message, code = "RPC_SUPERVISOR_PROTOCOL") {
|
|
30
|
+
super(message);
|
|
31
|
+
this.name = "RpcSupervisorProtocolError";
|
|
32
|
+
this.code = code;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function fail(message) {
|
|
37
|
+
throw new RpcSupervisorProtocolError(message);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function object(value, label) {
|
|
41
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) fail(`${label} must be an object`);
|
|
42
|
+
return value;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function onlyKeys(value, allowed, label) {
|
|
46
|
+
const unknown = Object.keys(value).filter((key) => !allowed.has(key));
|
|
47
|
+
if (unknown.length) fail(`${label} contains unsupported field${unknown.length === 1 ? "" : "s"}: ${unknown.join(", ")}`);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function string(value, label, { min = 1, max = RPC_SUPERVISOR_ID_MAX_LENGTH, pattern } = {}) {
|
|
51
|
+
if (typeof value !== "string" || value.length < min || value.length > max) fail(`${label} must be a string between ${min} and ${max} characters`);
|
|
52
|
+
if (pattern && !pattern.test(value)) fail(`${label} has an invalid format`);
|
|
53
|
+
return value;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function optionalString(value, label, options) {
|
|
57
|
+
if (value === undefined) return undefined;
|
|
58
|
+
return string(value, label, options);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function boundedJson(value, label, maximum = RPC_SUPERVISOR_METADATA_MAX_BYTES) {
|
|
62
|
+
let encoded;
|
|
63
|
+
try {
|
|
64
|
+
encoded = JSON.stringify(value);
|
|
65
|
+
} catch {
|
|
66
|
+
fail(`${label} must be JSON-serializable`);
|
|
67
|
+
}
|
|
68
|
+
if (encoded === undefined || Buffer.byteLength(encoded) > maximum) fail(`${label} exceeds the ${maximum}-byte limit`);
|
|
69
|
+
return value;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function version(value) {
|
|
73
|
+
object(value, "version");
|
|
74
|
+
onlyKeys(value, new Set(["major", "minor"]), "version");
|
|
75
|
+
if (!Number.isInteger(value.major) || value.major < 0 || !Number.isInteger(value.minor) || value.minor < 0) fail("version must contain non-negative integer major and minor values");
|
|
76
|
+
return { major: value.major, minor: value.minor };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function protocolCompatible(remote) {
|
|
80
|
+
const parsed = version(remote);
|
|
81
|
+
return parsed.major === RPC_SUPERVISOR_PROTOCOL.major;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function assertProtocolCompatible(remote) {
|
|
85
|
+
if (!protocolCompatible(remote)) {
|
|
86
|
+
const parsed = version(remote);
|
|
87
|
+
throw new RpcSupervisorProtocolError(`RPC supervisor protocol major ${parsed.major} is incompatible with ${RPC_SUPERVISOR_PROTOCOL.major}`, "RPC_SUPERVISOR_VERSION_MISMATCH");
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function constantTimeTokenEqual(actual, expected) {
|
|
92
|
+
if (typeof actual !== "string" || typeof expected !== "string") return false;
|
|
93
|
+
const left = Buffer.from(actual);
|
|
94
|
+
const right = Buffer.from(expected);
|
|
95
|
+
if (left.length !== right.length) return false;
|
|
96
|
+
return timingSafeEqual(left, right);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function newRequestId() {
|
|
100
|
+
return randomUUID();
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function sanitizeSupervisorData(value, { depth = 0 } = {}) {
|
|
104
|
+
if (depth > 16) return "[truncated]";
|
|
105
|
+
if (Array.isArray(value)) return value.slice(0, 256).map((item) => sanitizeSupervisorData(item, { depth: depth + 1 }));
|
|
106
|
+
if (!value || typeof value !== "object") return typeof value === "string" && value.length > 64 * 1024 ? `${value.slice(0, 64 * 1024)}…` : value;
|
|
107
|
+
const result = {};
|
|
108
|
+
for (const [key, item] of Object.entries(value)) {
|
|
109
|
+
if (RPC_SUPERVISOR_SECRET_KEY.test(key)) continue;
|
|
110
|
+
result[key] = sanitizeSupervisorData(item, { depth: depth + 1 });
|
|
111
|
+
}
|
|
112
|
+
return result;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function encodeFrame(frame) {
|
|
116
|
+
// Authentication frames contain the private bearer token. Secret stripping is
|
|
117
|
+
// deliberately applied at persistence and event/publication boundaries, not
|
|
118
|
+
// here, otherwise an attach could never authenticate.
|
|
119
|
+
const line = JSON.stringify(frame);
|
|
120
|
+
if (Buffer.byteLength(line) > RPC_SUPERVISOR_MAX_FRAME_BYTES) fail(`frame exceeds the ${RPC_SUPERVISOR_MAX_FRAME_BYTES}-byte limit`);
|
|
121
|
+
return `${line}\n`;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export function parseFrame(line) {
|
|
125
|
+
if (typeof line !== "string" || Buffer.byteLength(line) > RPC_SUPERVISOR_MAX_FRAME_BYTES) fail(`frame exceeds the ${RPC_SUPERVISOR_MAX_FRAME_BYTES}-byte limit`);
|
|
126
|
+
let parsed;
|
|
127
|
+
try {
|
|
128
|
+
parsed = JSON.parse(line);
|
|
129
|
+
} catch {
|
|
130
|
+
fail("frame is not valid JSON");
|
|
131
|
+
}
|
|
132
|
+
return object(parsed, "frame");
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function validateCursor(cursor, { optional = true } = {}) {
|
|
136
|
+
if (cursor === undefined && optional) return undefined;
|
|
137
|
+
object(cursor, "cursor");
|
|
138
|
+
onlyKeys(cursor, new Set(["epoch", "seq"]), "cursor");
|
|
139
|
+
return {
|
|
140
|
+
epoch: string(cursor.epoch, "cursor.epoch", { max: RPC_SUPERVISOR_ID_MAX_LENGTH, pattern: REQUEST_ID }),
|
|
141
|
+
seq: string(cursor.seq, "cursor.seq", { max: 20, pattern: SEQ }),
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function validateTabId(value, label = "tabId") {
|
|
146
|
+
return string(value, label, { pattern: TAB_ID });
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function validateMetadata(value, label = "metadata") {
|
|
150
|
+
object(value, label);
|
|
151
|
+
boundedJson(value, label);
|
|
152
|
+
return sanitizeSupervisorData(value);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function validateChild(value, label = "child") {
|
|
156
|
+
object(value, label);
|
|
157
|
+
onlyKeys(value, new Set(["command", "args", "cwd"]), label);
|
|
158
|
+
const command = string(value.command, `${label}.command`, { max: 4096 });
|
|
159
|
+
if (!Array.isArray(value.args) || value.args.length > 256) fail(`${label}.args must be an array with at most 256 entries`);
|
|
160
|
+
const args = value.args.map((arg, index) => string(arg, `${label}.args[${index}]`, { min: 0, max: 64 * 1024 }));
|
|
161
|
+
const cwd = string(value.cwd, `${label}.cwd`, { max: 16 * 1024 });
|
|
162
|
+
return { command, args, cwd };
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export function validateClientFrame(frame) {
|
|
166
|
+
const value = object(frame, "frame");
|
|
167
|
+
const type = string(value.type, "frame.type", { max: 40 });
|
|
168
|
+
if (type === "attach") {
|
|
169
|
+
onlyKeys(value, new Set(["type", "version", "scopeId", "token", "controllerId", "cursor"]), "attach");
|
|
170
|
+
return {
|
|
171
|
+
type,
|
|
172
|
+
version: version(value.version),
|
|
173
|
+
scopeId: string(value.scopeId, "scopeId", { max: 64, pattern: SCOPE_ID }),
|
|
174
|
+
token: string(value.token, "token", { max: 512 }),
|
|
175
|
+
controllerId: string(value.controllerId, "controllerId", { pattern: REQUEST_ID }),
|
|
176
|
+
cursor: validateCursor(value.cursor),
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
if (!OPERATION_TYPES.has(type)) fail(`unsupported operation: ${type}`);
|
|
180
|
+
const common = new Set(["type", "requestId", "tabId", "metadata", "child", "command", "timeoutMs", "cursor"]);
|
|
181
|
+
onlyKeys(value, common, type);
|
|
182
|
+
const requestId = string(value.requestId, "requestId", { pattern: REQUEST_ID });
|
|
183
|
+
if (type === "create") {
|
|
184
|
+
return { type, requestId, tabId: validateTabId(value.tabId), metadata: validateMetadata(value.metadata), child: validateChild(value.child) };
|
|
185
|
+
}
|
|
186
|
+
if (type === "update") return { type, requestId, tabId: validateTabId(value.tabId), metadata: validateMetadata(value.metadata) };
|
|
187
|
+
if (type === "replace") return { type, requestId, tabId: validateTabId(value.tabId), metadata: value.metadata === undefined ? undefined : validateMetadata(value.metadata), child: validateChild(value.child) };
|
|
188
|
+
if (type === "close") return { type, requestId, tabId: validateTabId(value.tabId) };
|
|
189
|
+
if (type === "command" || type === "write") {
|
|
190
|
+
const command = object(value.command, "command");
|
|
191
|
+
// This validates size without altering a live Pi RPC object. In particular,
|
|
192
|
+
// token-named keys, long strings, and large arrays are legitimate payload.
|
|
193
|
+
boundedJson(command, "command", PI_RPC_JSONL_LINE_MAX_BYTES);
|
|
194
|
+
if (typeof command.type !== "string" || !command.type) fail("command.type must be a non-empty string");
|
|
195
|
+
if (type === "command" && value.timeoutMs !== undefined && (!Number.isInteger(value.timeoutMs) || value.timeoutMs < 1 || value.timeoutMs > 24 * 60 * 60_000)) fail("timeoutMs must be an integer between 1 and 86400000");
|
|
196
|
+
if (type === "write" && value.timeoutMs !== undefined) fail("write does not accept timeoutMs");
|
|
197
|
+
return { type, requestId, tabId: validateTabId(value.tabId), command, ...(type === "command" ? { timeoutMs: value.timeoutMs } : {}) };
|
|
198
|
+
}
|
|
199
|
+
if (type === "ack") return { type, requestId, cursor: validateCursor(value.cursor, { optional: false }) };
|
|
200
|
+
return { type, requestId };
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
export function frameReader(onFrame, onError) {
|
|
204
|
+
const decoder = new StringDecoder("utf8");
|
|
205
|
+
let buffer = "";
|
|
206
|
+
let discarding = false;
|
|
207
|
+
return (chunk) => {
|
|
208
|
+
let input = Buffer.isBuffer(chunk) ? decoder.write(chunk) : String(chunk);
|
|
209
|
+
while (input) {
|
|
210
|
+
if (discarding) {
|
|
211
|
+
const newline = input.indexOf("\n");
|
|
212
|
+
if (newline < 0) return;
|
|
213
|
+
input = input.slice(newline + 1);
|
|
214
|
+
discarding = false;
|
|
215
|
+
continue;
|
|
216
|
+
}
|
|
217
|
+
const newline = input.indexOf("\n");
|
|
218
|
+
const piece = newline < 0 ? input : input.slice(0, newline);
|
|
219
|
+
if (Buffer.byteLength(buffer) + Buffer.byteLength(piece) > RPC_SUPERVISOR_MAX_FRAME_BYTES) {
|
|
220
|
+
buffer = "";
|
|
221
|
+
onError?.(new RpcSupervisorProtocolError(`frame exceeds the ${RPC_SUPERVISOR_MAX_FRAME_BYTES}-byte limit`));
|
|
222
|
+
if (newline < 0) { discarding = true; return; }
|
|
223
|
+
input = input.slice(newline + 1);
|
|
224
|
+
continue;
|
|
225
|
+
}
|
|
226
|
+
buffer += piece;
|
|
227
|
+
if (newline < 0) return;
|
|
228
|
+
const line = buffer.endsWith("\r") ? buffer.slice(0, -1) : buffer;
|
|
229
|
+
buffer = "";
|
|
230
|
+
if (line.trim()) {
|
|
231
|
+
try { onFrame(parseFrame(line)); } catch (error) { onError?.(error); }
|
|
232
|
+
}
|
|
233
|
+
input = input.slice(newline + 1);
|
|
234
|
+
}
|
|
235
|
+
};
|
|
236
|
+
}
|