@firstpick/pi-package-webui 0.7.6 → 0.7.8

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 (48) hide show
  1. package/README.md +60 -4
  2. package/bin/pi-webui-rpc-supervisor.mjs +612 -0
  3. package/bin/pi-webui.mjs +1051 -95
  4. package/lib/WEBUI_TUI_NATIVE_PARITY.json +13 -0
  5. package/lib/rpc-supervisor-client.mjs +317 -0
  6. package/lib/rpc-supervisor-protocol.mjs +245 -0
  7. package/lib/rpc-supervisor-state.mjs +165 -0
  8. package/lib/trust-boundaries.mjs +1 -0
  9. package/package.json +4 -4
  10. package/public/app.js +1986 -170
  11. package/public/index.html +388 -25
  12. package/public/issue-bot-client.mjs +344 -0
  13. package/public/issue-wizard-state.mjs +443 -0
  14. package/public/service-worker.js +8 -1
  15. package/public/styles.css +578 -52
  16. package/public/subagent-gate-visibility.mjs +36 -0
  17. package/public/workflow-status-stack.mjs +69 -0
  18. package/tests/app-runner-process-tree-harness.test.mjs +37 -3
  19. package/tests/boot-failure-diagnostics.test.mjs +180 -0
  20. package/tests/completion-signal-contract.test.mjs +156 -0
  21. package/tests/cwd-footer-reliability-static.test.mjs +107 -0
  22. package/tests/durable-rpc-supervisor-harness.test.mjs +275 -0
  23. package/tests/fast-mode-client-static.test.mjs +2 -2
  24. package/tests/fixtures/fake-pi.mjs +90 -6
  25. package/tests/footer-context-contrast-static.test.mjs +10 -0
  26. package/tests/git-panel-file-preview-static.test.mjs +221 -0
  27. package/tests/git-panel-render-stability-static.test.mjs +11 -1
  28. package/tests/http-endpoints-harness.test.mjs +458 -33
  29. package/tests/issue-bot-client.test.mjs +135 -0
  30. package/tests/issue-wizard-state.test.mjs +126 -0
  31. package/tests/mobile-static.test.mjs +79 -16
  32. package/tests/native-parity-harness.test.mjs +2 -1
  33. package/tests/native-parity.test.mjs +13 -2
  34. package/tests/numpad-decimal-input-static.test.mjs +128 -0
  35. package/tests/open-issue-wizard-static.test.mjs +75 -0
  36. package/tests/prompt-routing-input-clear-static.test.mjs +34 -0
  37. package/tests/prompt-routing-tab-status.test.mjs +108 -0
  38. package/tests/rpc-supervisor-host.test.mjs +408 -0
  39. package/tests/rpc-supervisor-protocol.test.mjs +93 -0
  40. package/tests/rpc-supervisor-state.test.mjs +62 -0
  41. package/tests/run-all.mjs +4 -1
  42. package/tests/streaming-ui-coupling.test.mjs +18 -2
  43. package/tests/subagent-gate-visibility.test.mjs +66 -0
  44. package/tests/subagent-launch-slots-static.test.mjs +1 -1
  45. package/tests/subagents-helper.test.mjs +136 -0
  46. package/tests/terminal-tab-workspace-static.test.mjs +99 -0
  47. package/tests/workflow-status-stack.test.mjs +87 -0
  48. package/webui-rpc-helper.mjs +160 -2
@@ -0,0 +1,612 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from "node:child_process";
3
+ import { randomUUID } from "node:crypto";
4
+ import { createServer } from "node:net";
5
+ import { rm, realpath } from "node:fs/promises";
6
+ import { StringDecoder } from "node:string_decoder";
7
+ import { terminateProcessTree } from "../lib/process-tree.mjs";
8
+ import {
9
+ PI_RPC_JSONL_LINE_MAX_BYTES,
10
+ RPC_SUPERVISOR_EVENT_RING_LIMIT,
11
+ RPC_SUPERVISOR_EVENT_RING_MAX_BYTES,
12
+ RPC_SUPERVISOR_PROTOCOL,
13
+ RPC_SUPERVISOR_REQUEST_DEDUPE_LIMIT,
14
+ RPC_SUPERVISOR_TAB_LIMIT,
15
+ RpcSupervisorProtocolError,
16
+ assertProtocolCompatible,
17
+ constantTimeTokenEqual,
18
+ encodeFrame,
19
+ frameReader,
20
+ validateClientFrame,
21
+ } from "../lib/rpc-supervisor-protocol.mjs";
22
+ import {
23
+ appendSupervisorJournal,
24
+ defaultAgentDir,
25
+ ensureSupervisorRuntime,
26
+ newSupervisorToken,
27
+ readSupervisorState,
28
+ removeSupervisorState,
29
+ sanitizedSupervisorEnvironment,
30
+ supervisorPaths,
31
+ supervisorPidIsAlive,
32
+ writeSupervisorState,
33
+ } from "../lib/rpc-supervisor-state.mjs";
34
+
35
+ const ATTACH_TIMEOUT_MS = 2_500;
36
+ const EMPTY_IDLE_GRACE_MS = 1_500;
37
+ const CHILD_STOP_GRACE_MS = 3_000;
38
+ const CHILD_STDIN_WRITE_TIMEOUT_MS = 2_000;
39
+ const REQUEST_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
40
+
41
+ function requestIdForErrorFrame(frame) {
42
+ return typeof frame?.requestId === "string" && REQUEST_ID_PATTERN.test(frame.requestId) ? frame.requestId : undefined;
43
+ }
44
+
45
+ function cliOptions(argv) {
46
+ const options = { agentDir: defaultAgentDir(), port: undefined, runtimeDir: undefined };
47
+ for (let index = 0; index < argv.length; index += 1) {
48
+ const value = argv[index];
49
+ if (value === "--agent-dir") options.agentDir = argv[++index];
50
+ else if (value === "--port") options.port = Number(argv[++index]);
51
+ else if (value === "--runtime-dir") options.runtimeDir = argv[++index];
52
+ else throw new Error(`Unknown option: ${value}`);
53
+ }
54
+ if (!options.agentDir || !Number.isInteger(options.port) || options.port < 1 || options.port > 65535) {
55
+ throw new Error("Usage: pi-webui-rpc-supervisor --agent-dir <private-agent-dir> --port <1-65535> [--runtime-dir <private-dir>]");
56
+ }
57
+ return options;
58
+ }
59
+
60
+ function tabSnapshot(tab) {
61
+ return {
62
+ id: tab.id,
63
+ metadata: tab.metadata,
64
+ pid: tab.child?.pid,
65
+ startedAt: tab.startedAt,
66
+ running: tabRunning(tab),
67
+ };
68
+ }
69
+
70
+ function tabRunning(tab) {
71
+ return !!tab?.child && tab.child.exitCode === null && tab.child.signalCode === null;
72
+ }
73
+
74
+ function publicError(error) {
75
+ if (error instanceof RpcSupervisorProtocolError) return error.message;
76
+ return String(error?.message || error || "Supervisor operation failed").replace(/(?:token|secret|password)=[^\s]+/gi, "$1=[redacted]");
77
+ }
78
+
79
+ function exitPromise(child, timeoutMs = CHILD_STOP_GRACE_MS) {
80
+ if (!child || child.exitCode !== null || child.signalCode !== null) return Promise.resolve();
81
+ return new Promise((resolve) => {
82
+ const timer = setTimeout(resolve, timeoutMs);
83
+ timer.unref?.();
84
+ child.once("exit", () => { clearTimeout(timer); resolve(); });
85
+ });
86
+ }
87
+
88
+ class SupervisorHost {
89
+ constructor(paths) {
90
+ this.paths = paths;
91
+ this.token = newSupervisorToken();
92
+ this.instanceId = randomUUID();
93
+ this.epoch = randomUUID();
94
+ this.sequence = 0n;
95
+ this.tabs = new Map();
96
+ this.events = [];
97
+ this.retainedEventBytes = 0;
98
+ this.requests = new Map();
99
+ this.clients = new Set();
100
+ this.controller = null;
101
+ this.server = null;
102
+ this.closing = false;
103
+ this.idleTimer = null;
104
+ this.persistQueue = Promise.resolve();
105
+ }
106
+
107
+ async start() {
108
+ await ensureSupervisorRuntime(this.paths);
109
+ const current = await readSupervisorState(this.paths);
110
+ if (current) {
111
+ if (supervisorPidIsAlive(current.pid)) {
112
+ throw Object.assign(new Error(`Refusing to replace live RPC supervisor ${current.pid}`), { code: "RPC_SUPERVISOR_LIVE_STATE" });
113
+ }
114
+ // A direct supervisor launch is still constrained to the same stale-state
115
+ // rule as the client launcher. The normal replacement path also holds
116
+ // the startup lock before reaching here.
117
+ const removed = await removeSupervisorState(this.paths, { removeSocket: true, instanceId: current.instanceId });
118
+ if (!removed) throw new Error("RPC supervisor state changed while removing a confirmed-dead owner");
119
+ } else if (process.platform !== "win32") {
120
+ // No descriptor exists to identify an incumbent. This can only clean an
121
+ // orphaned local socket; a recorded live supervisor is never removed.
122
+ await rm(this.paths.socketPath, { force: true }).catch(() => {});
123
+ }
124
+ this.server = createServer((socket) => this.accept(socket));
125
+ this.server.on("error", (error) => {
126
+ console.error(`RPC supervisor listener error: ${publicError(error)}`);
127
+ this.shutdown("listener error").catch(() => process.exitCode = 1);
128
+ });
129
+ await new Promise((resolve, reject) => {
130
+ const onError = (error) => { this.server.off("listening", onListening); reject(error); };
131
+ const onListening = () => { this.server.off("error", onError); resolve(); };
132
+ this.server.once("error", onError);
133
+ this.server.once("listening", onListening);
134
+ this.server.listen(this.paths.socketPath);
135
+ });
136
+ await this.persist("started");
137
+ this.scheduleIdleExit();
138
+ }
139
+
140
+ persist(reason) {
141
+ const operation = this.persistQueue.catch(() => {}).then(async () => {
142
+ if (this.closing) return;
143
+ const tabs = [...this.tabs.values()].map(tabSnapshot);
144
+ await writeSupervisorState(this.paths, {
145
+ token: this.token,
146
+ instanceId: this.instanceId,
147
+ pid: process.pid,
148
+ startedAt: new Date().toISOString(),
149
+ epoch: this.epoch,
150
+ tabs,
151
+ });
152
+ await appendSupervisorJournal(this.paths, { type: "snapshot", reason, epoch: this.epoch, tabs }).catch(() => {});
153
+ });
154
+ this.persistQueue = operation;
155
+ return operation;
156
+ }
157
+
158
+ accept(socket) {
159
+ socket.setNoDelay(true);
160
+ const client = { socket, attached: false, controllerId: null, attachTimer: null };
161
+ client.attachTimer = setTimeout(() => {
162
+ if (client.attached) return;
163
+ this.sendError(client, undefined, Object.assign(new Error(`Timed out waiting for RPC supervisor attach after ${ATTACH_TIMEOUT_MS}ms`), { code: "RPC_SUPERVISOR_ATTACH_TIMEOUT" }));
164
+ socket.destroy();
165
+ }, ATTACH_TIMEOUT_MS);
166
+ client.attachTimer.unref?.();
167
+ this.clients.add(client);
168
+ this.cancelIdleExit();
169
+ const consume = frameReader(
170
+ // Validation can fail before handleFrame has a normalized request. Echo a
171
+ // syntactically safe raw request ID so the client rejects the matching
172
+ // promise instead of leaving create/replace requests pending forever.
173
+ (frame) => this.handleFrame(client, frame).catch((error) => this.sendError(client, requestIdForErrorFrame(frame), error)),
174
+ (error) => { this.sendError(client, undefined, error); socket.destroy(); },
175
+ );
176
+ socket.on("data", consume);
177
+ socket.on("error", () => {});
178
+ socket.on("close", () => {
179
+ if (client.attachTimer) clearTimeout(client.attachTimer);
180
+ client.attachTimer = null;
181
+ this.clients.delete(client);
182
+ if (this.controller?.client === client) this.controller = null;
183
+ this.scheduleIdleExit();
184
+ });
185
+ }
186
+
187
+ send(client, frame) {
188
+ if (!client?.socket || client.socket.destroyed) return;
189
+ // Frames from Pi are local transport data, not persisted metadata. Never
190
+ // strip or truncate them here; explicit frame-size validation rejects an
191
+ // oversized record instead of silently changing it.
192
+ try { client.socket.write(encodeFrame(frame)); } catch { client.socket.destroy(); }
193
+ }
194
+
195
+ sendError(client, requestId, error) {
196
+ this.send(client, { type: "result", ...(requestId ? { requestId } : {}), ok: false, code: error?.code || "RPC_SUPERVISOR_ERROR", error: publicError(error) });
197
+ }
198
+
199
+ async handleFrame(client, frame) {
200
+ const request = validateClientFrame(frame);
201
+ if (request.type === "attach") return this.attach(client, request);
202
+ if (!client.attached || this.controller?.client !== client || this.controller?.controllerId !== client.controllerId) {
203
+ throw Object.assign(new Error("This RPC supervisor connection is not the active controller"), { code: "RPC_SUPERVISOR_FENCED" });
204
+ }
205
+ await this.operation(client, request);
206
+ }
207
+
208
+ attach(client, request) {
209
+ assertProtocolCompatible(request.version);
210
+ if (request.scopeId !== this.paths.scopeId || !constantTimeTokenEqual(request.token, this.token)) {
211
+ throw Object.assign(new Error("RPC supervisor authentication failed"), { code: "RPC_SUPERVISOR_AUTH" });
212
+ }
213
+ if (this.controller && this.controller.client !== client) {
214
+ this.send(this.controller.client, { type: "fenced", reason: "A newer server controller attached" });
215
+ this.controller.client.attached = false;
216
+ }
217
+ if (client.attachTimer) clearTimeout(client.attachTimer);
218
+ client.attachTimer = null;
219
+ client.attached = true;
220
+ client.controllerId = request.controllerId;
221
+ this.controller = { client, controllerId: request.controllerId, attachedAt: Date.now() };
222
+ const replay = this.replayFor(request.cursor);
223
+ this.send(client, {
224
+ type: "attached",
225
+ version: RPC_SUPERVISOR_PROTOCOL,
226
+ scopeId: this.paths.scopeId,
227
+ epoch: this.epoch,
228
+ tabs: [...this.tabs.values()].map(tabSnapshot),
229
+ earliestSeq: this.events.length ? this.events[0].seq : this.sequence.toString(),
230
+ latestSeq: this.sequence.toString(),
231
+ gap: replay.gap,
232
+ replay: replay.events,
233
+ });
234
+ }
235
+
236
+ replayFor(cursor) {
237
+ // A controller without a persisted handoff cursor cannot know which prior
238
+ // output it observed. Replay the retained suffix and require authoritative
239
+ // refresh whenever a live tab or retained history exists.
240
+ if (!cursor) return { gap: this.tabs.size > 0 || this.events.length > 0, events: [...this.events] };
241
+ if (cursor.epoch !== this.epoch) return { gap: true, events: [...this.events] };
242
+ const sequence = BigInt(cursor.seq);
243
+ const earliest = this.events.length ? BigInt(this.events[0].seq) : this.sequence + 1n;
244
+ const gap = sequence + 1n < earliest;
245
+ return { gap, events: this.events.filter((event) => BigInt(event.seq) > sequence) };
246
+ }
247
+
248
+ retainEvent(event) {
249
+ const bytes = Buffer.byteLength(JSON.stringify(event));
250
+ // Keep a contiguous retained suffix. An oversized live event is forwarded
251
+ // but clears prior history so cursors before it report an honest gap.
252
+ if (bytes > RPC_SUPERVISOR_EVENT_RING_MAX_BYTES) {
253
+ this.events = [];
254
+ this.retainedEventBytes = 0;
255
+ return;
256
+ }
257
+ this.events.push(event);
258
+ this.retainedEventBytes += bytes;
259
+ while (this.events.length > RPC_SUPERVISOR_EVENT_RING_LIMIT || this.retainedEventBytes > RPC_SUPERVISOR_EVENT_RING_MAX_BYTES) {
260
+ const evicted = this.events.shift();
261
+ this.retainedEventBytes -= Buffer.byteLength(JSON.stringify(evicted));
262
+ }
263
+ }
264
+
265
+ emit(tabId, payload) {
266
+ this.sequence += 1n;
267
+ const event = { type: "event", epoch: this.epoch, seq: this.sequence.toString(), scopeId: this.paths.scopeId, tabId, at: new Date().toISOString(), payload };
268
+ this.retainEvent(event);
269
+ for (const client of this.clients) if (client.attached && this.controller?.client === client) this.send(client, event);
270
+ return event;
271
+ }
272
+
273
+ pruneSettledRequests() {
274
+ for (const [requestId, entry] of this.requests) {
275
+ if (entry.settled) this.requests.delete(requestId);
276
+ }
277
+ }
278
+
279
+ async operation(client, request) {
280
+ const prior = this.requests.get(request.requestId);
281
+ if (prior) {
282
+ try { this.send(client, { type: "result", requestId: request.requestId, ok: true, data: await prior.promise }); }
283
+ catch (error) { this.sendError(client, request.requestId, error); }
284
+ return;
285
+ }
286
+ this.pruneSettledRequests();
287
+ if (this.requests.size >= RPC_SUPERVISOR_REQUEST_DEDUPE_LIMIT) {
288
+ this.sendError(client, request.requestId, Object.assign(new Error("RPC supervisor request dedupe capacity is occupied by unresolved work"), { code: "RPC_SUPERVISOR_DEDUPE_CAPACITY" }));
289
+ return;
290
+ }
291
+ const entry = { settled: false, promise: null };
292
+ entry.promise = Promise.resolve().then(() => this.perform(request));
293
+ entry.promise.then(() => { entry.settled = true; }, () => { entry.settled = true; });
294
+ this.requests.set(request.requestId, entry);
295
+ try { this.send(client, { type: "result", requestId: request.requestId, ok: true, data: await entry.promise }); }
296
+ catch (error) { this.sendError(client, request.requestId, error); }
297
+ }
298
+
299
+ queueTabMutation(tabId, operation) {
300
+ const tab = this.requireTab(tabId);
301
+ const previous = tab.mutationTail || Promise.resolve();
302
+ const result = previous.catch(() => {}).then(() => {
303
+ if (this.tabs.get(tabId) !== tab) throw new Error(`Managed tab is no longer available: ${tabId}`);
304
+ return operation();
305
+ });
306
+ tab.mutationTail = result.catch(() => {});
307
+ return result;
308
+ }
309
+
310
+ queueTabCommand(tabId, operation) {
311
+ const tab = this.requireTab(tabId);
312
+ const previous = tab.mutationTail || Promise.resolve();
313
+ let response;
314
+ const admission = previous.catch(() => {}).then(() => {
315
+ if (this.tabs.get(tabId) !== tab) throw new Error(`Managed tab is no longer available: ${tabId}`);
316
+ // command() registers the pending response and writes to stdin
317
+ // synchronously before returning its response promise. Release the FIFO
318
+ // barrier at that point so extension-ui writes and later bounded probes
319
+ // are not blocked by the full Pi response lifetime.
320
+ response = operation();
321
+ });
322
+ tab.mutationTail = admission.catch(() => {});
323
+ return admission.then(() => response);
324
+ }
325
+
326
+ async perform(request) {
327
+ switch (request.type) {
328
+ case "create": return this.create(request);
329
+ case "update": return this.queueTabMutation(request.tabId, () => this.update(request));
330
+ case "replace": return this.queueTabMutation(request.tabId, () => this.replace(request));
331
+ case "close": return this.queueTabMutation(request.tabId, () => this.closeTab(request.tabId));
332
+ // Commands take a FIFO admission position, but their full response must
333
+ // not hold the queue: prompts can wait for extension-ui writes. Metadata
334
+ // refreshes can also arrive continuously, so chasing a moving tail would
335
+ // starve get_state and leave a CWD PATCH permanently in progress.
336
+ case "command": return this.queueTabCommand(request.tabId, () => this.command(request));
337
+ case "write": return this.queueTabMutation(request.tabId, () => this.write(request));
338
+ case "ack": return { cursor: request.cursor };
339
+ case "prepare_handoff": return { epoch: this.epoch, latestSeq: this.sequence.toString(), tabs: [...this.tabs.values()].map(tabSnapshot) };
340
+ case "detach": return { detached: true };
341
+ case "shutdown":
342
+ setImmediate(() => this.shutdown("explicit shutdown"));
343
+ return { shuttingDown: true };
344
+ default: throw new Error(`Unsupported supervisor operation ${request.type}`);
345
+ }
346
+ }
347
+
348
+ async create({ tabId, metadata, child }) {
349
+ if (this.tabs.has(tabId)) throw new Error(`Managed tab already exists: ${tabId}`);
350
+ if (this.tabs.size >= RPC_SUPERVISOR_TAB_LIMIT) throw new Error(`Managed tab limit is ${RPC_SUPERVISOR_TAB_LIMIT}`);
351
+ const tab = { id: tabId, metadata, child: null, pending: new Map(), startedAt: new Date().toISOString(), mutationTail: Promise.resolve() };
352
+ this.tabs.set(tabId, tab);
353
+ try {
354
+ const candidate = await this.spawnChildCandidate(child);
355
+ this.commitChild(tab, candidate);
356
+ } catch (error) {
357
+ this.tabs.delete(tabId);
358
+ throw error;
359
+ }
360
+ await this.persist("create");
361
+ return tabSnapshot(tab);
362
+ }
363
+
364
+ async update({ tabId, metadata }) {
365
+ const tab = this.requireTab(tabId);
366
+ tab.metadata = metadata;
367
+ await this.persist("update");
368
+ return tabSnapshot(tab);
369
+ }
370
+
371
+ async replace({ tabId, metadata, child }) {
372
+ const tab = this.requireTab(tabId);
373
+ await this.stopChild(tab, "replace");
374
+ const candidate = await this.spawnChildCandidate(child);
375
+ if (metadata !== undefined) tab.metadata = metadata;
376
+ this.commitChild(tab, candidate);
377
+ await this.persist("replace");
378
+ return tabSnapshot(tab);
379
+ }
380
+
381
+ async closeTab(tabId) {
382
+ const tab = this.requireTab(tabId);
383
+ await this.stopChild(tab, "close");
384
+ this.tabs.delete(tabId);
385
+ await this.persist("close");
386
+ this.scheduleIdleExit();
387
+ return { id: tabId, closed: true };
388
+ }
389
+
390
+ requireTab(tabId) {
391
+ const tab = this.tabs.get(tabId);
392
+ if (!tab) throw new Error(`Managed tab not found: ${tabId}`);
393
+ return tab;
394
+ }
395
+
396
+ async spawnChildCandidate(child) {
397
+ const cwd = await realpath(child.cwd).catch(() => child.cwd);
398
+ const processChild = spawn(child.command, child.args, {
399
+ cwd,
400
+ env: sanitizedSupervisorEnvironment(process.env),
401
+ stdio: ["pipe", "pipe", "pipe"],
402
+ detached: process.platform !== "win32",
403
+ windowsHide: true,
404
+ });
405
+ await new Promise((resolve, reject) => {
406
+ processChild.once("spawn", resolve);
407
+ processChild.once("error", reject);
408
+ });
409
+ return { processChild, cwd, startedAt: new Date().toISOString() };
410
+ }
411
+
412
+ commitChild(tab, { processChild, cwd, startedAt }) {
413
+ tab.child = processChild;
414
+ tab.startedAt = startedAt;
415
+ processChild.on("error", (error) => {
416
+ if (tab.child !== processChild) return;
417
+ this.emit(tab.id, { type: "pi_process_error", error: publicError(error) });
418
+ this.rejectPending(tab, error);
419
+ });
420
+ processChild.on("exit", (code, signal) => {
421
+ if (tab.child !== processChild) return;
422
+ this.emit(tab.id, { type: "pi_process_exit", code, signal });
423
+ this.rejectPending(tab, new Error(`Pi RPC process exited${code === null ? "" : ` with code ${code}`}${signal ? ` (${signal})` : ""}`));
424
+ if (!this.closing) this.persist("child exit").catch(() => {});
425
+ });
426
+ // ChildProcess does not forward stdin pipe errors to its own `error`
427
+ // event. A timed-out/backpressured one-way write followed by replacement
428
+ // can otherwise emit an unhandled EPIPE and crash the detached supervisor.
429
+ processChild.stdin.on("error", (error) => {
430
+ if (tab.child !== processChild || !tabRunning(tab)) return;
431
+ this.emit(tab.id, { type: "pi_stdin_error", error: publicError(error) });
432
+ this.rejectPending(tab, error);
433
+ });
434
+ this.readJsonl(processChild.stdout, (line) => {
435
+ if (tab.child === processChild) this.handlePiLine(tab, line);
436
+ }, tab.id);
437
+ this.readText(processChild.stderr, (text) => {
438
+ if (text && tab.child === processChild) this.emit(tab.id, { type: "pi_stderr", text });
439
+ });
440
+ // The executable/arguments are launch details, not WebUI event data; never
441
+ // publish them because command-line credentials must stay private.
442
+ this.emit(tab.id, { type: "pi_process_start", pid: processChild.pid, cwd });
443
+ }
444
+
445
+ readJsonl(stream, onLine, tabId) {
446
+ const decoder = new StringDecoder("utf8");
447
+ let buffer = "";
448
+ let bytes = 0;
449
+ let discarding = false;
450
+ const consume = (chunk) => {
451
+ let input = typeof chunk === "string" ? chunk : decoder.write(chunk);
452
+ while (input) {
453
+ if (discarding) {
454
+ const newline = input.indexOf("\n");
455
+ if (newline < 0) return;
456
+ input = input.slice(newline + 1); discarding = false; continue;
457
+ }
458
+ const newline = input.indexOf("\n");
459
+ const piece = newline < 0 ? input : input.slice(0, newline);
460
+ const size = Buffer.byteLength(piece);
461
+ if (bytes + size > PI_RPC_JSONL_LINE_MAX_BYTES) {
462
+ buffer = ""; bytes = 0;
463
+ this.emit(tabId, { type: "pi_stdout_line_too_large", maxBytes: PI_RPC_JSONL_LINE_MAX_BYTES });
464
+ if (newline < 0) { discarding = true; return; }
465
+ input = input.slice(newline + 1); continue;
466
+ }
467
+ buffer += piece; bytes += size;
468
+ if (newline < 0) return;
469
+ const line = buffer.endsWith("\r") ? buffer.slice(0, -1) : buffer;
470
+ buffer = ""; bytes = 0;
471
+ if (line) onLine(line);
472
+ input = input.slice(newline + 1);
473
+ }
474
+ };
475
+ stream.on("data", consume);
476
+ stream.on("end", () => { consume(decoder.end()); if (!discarding && buffer) onLine(buffer); });
477
+ }
478
+
479
+ readText(stream, onText) {
480
+ const decoder = new StringDecoder("utf8");
481
+ stream.on("data", (chunk) => onText(typeof chunk === "string" ? chunk : decoder.write(chunk)));
482
+ stream.on("end", () => { const tail = decoder.end(); if (tail) onText(tail); });
483
+ }
484
+
485
+ handlePiLine(tab, line) {
486
+ let payload;
487
+ try { payload = JSON.parse(line); }
488
+ catch (error) { this.emit(tab.id, { type: "pi_stdout_parse_error", line: line.slice(0, 4096), error: publicError(error) }); return; }
489
+ if (payload?.type === "response" && typeof payload.id === "string" && tab.pending.has(payload.id)) {
490
+ const pending = tab.pending.get(payload.id);
491
+ tab.pending.delete(payload.id);
492
+ clearTimeout(pending.timer);
493
+ pending.resolve(payload);
494
+ }
495
+ this.emit(tab.id, payload);
496
+ }
497
+
498
+ command({ tabId, requestId, command, timeoutMs = 60_000 }) {
499
+ const tab = this.requireTab(tabId);
500
+ if (!tabRunning(tab) || !tab.child?.stdin?.writable) throw new Error("Pi RPC process is not running");
501
+ const payload = { ...command, id: requestId };
502
+ return new Promise((resolve, reject) => {
503
+ const timer = setTimeout(() => {
504
+ tab.pending.delete(requestId);
505
+ reject(new Error(`Timed out waiting for RPC response to ${payload.type}`));
506
+ }, timeoutMs);
507
+ timer.unref?.();
508
+ tab.pending.set(requestId, { resolve, reject, timer });
509
+ try {
510
+ const writable = tab.child.stdin.write(`${JSON.stringify(payload)}\n`);
511
+ if (!writable) tab.child.stdin.once("drain", () => {});
512
+ } catch (error) {
513
+ clearTimeout(timer);
514
+ tab.pending.delete(requestId);
515
+ reject(error);
516
+ }
517
+ });
518
+ }
519
+
520
+ write({ tabId, command }) {
521
+ const tab = this.requireTab(tabId);
522
+ if (!tabRunning(tab) || !tab.child?.stdin?.writable) throw new Error("Pi RPC process is not running");
523
+ // Unlike `command`, this preserves the supplied Pi RPC object exactly and
524
+ // never waits for a Pi response. Keep FIFO ordering until Node flushes the
525
+ // record, but bound that wait: a backpressured/unresponsive child must not
526
+ // poison the tab mutation queue and block reload, CWD changes, or startup
527
+ // probes for a forked tab forever.
528
+ return new Promise((resolve, reject) => {
529
+ let settled = false;
530
+ let timer = null;
531
+ const finish = (error) => {
532
+ if (settled) return;
533
+ settled = true;
534
+ if (timer) clearTimeout(timer);
535
+ if (error) reject(error);
536
+ else resolve({ written: true });
537
+ };
538
+ timer = setTimeout(() => finish(Object.assign(
539
+ new Error(`Timed out flushing a one-way Pi RPC write after ${CHILD_STDIN_WRITE_TIMEOUT_MS}ms`),
540
+ { code: "RPC_SUPERVISOR_CHILD_WRITE_TIMEOUT" },
541
+ )), CHILD_STDIN_WRITE_TIMEOUT_MS);
542
+ timer.unref?.();
543
+ try {
544
+ tab.child.stdin.write(`${JSON.stringify(command)}\n`, finish);
545
+ } catch (error) {
546
+ finish(error);
547
+ }
548
+ });
549
+ }
550
+
551
+ rejectPending(tab, error) {
552
+ for (const [id, pending] of tab.pending) {
553
+ clearTimeout(pending.timer);
554
+ pending.reject(error);
555
+ tab.pending.delete(id);
556
+ }
557
+ }
558
+
559
+ async stopChild(tab, reason) {
560
+ if (!tab.child) return;
561
+ const child = tab.child;
562
+ this.emit(tab.id, { type: "pi_process_stopping", reason });
563
+ terminateProcessTree(child, "SIGTERM");
564
+ await exitPromise(child);
565
+ if (tabRunning(tab)) {
566
+ terminateProcessTree(child, "SIGKILL");
567
+ await exitPromise(child, 1_000);
568
+ }
569
+ if (tabRunning(tab)) {
570
+ throw Object.assign(new Error(`Pi RPC process ${child.pid || "unknown"} did not stop for ${reason}`), {
571
+ code: "RPC_SUPERVISOR_CHILD_STOP_TIMEOUT",
572
+ });
573
+ }
574
+ this.rejectPending(tab, new Error(`Pi RPC process stopped for ${reason}`));
575
+ }
576
+
577
+ cancelIdleExit() {
578
+ if (this.idleTimer) clearTimeout(this.idleTimer);
579
+ this.idleTimer = null;
580
+ }
581
+
582
+ scheduleIdleExit() {
583
+ if (this.closing || this.tabs.size || this.clients.size || this.idleTimer) return;
584
+ this.idleTimer = setTimeout(() => this.shutdown("idle"), EMPTY_IDLE_GRACE_MS);
585
+ this.idleTimer.unref?.();
586
+ }
587
+
588
+ async shutdown(reason) {
589
+ if (this.closing) return;
590
+ this.closing = true;
591
+ this.cancelIdleExit();
592
+ const stopResults = await Promise.allSettled([...this.tabs.values()].map((tab) => this.stopChild(tab, reason)));
593
+ const stopFailures = stopResults.filter((result) => result.status === "rejected");
594
+ if (stopFailures.length) {
595
+ this.closing = false;
596
+ await this.persist("shutdown blocked by live child").catch(() => {});
597
+ console.error(`RPC supervisor shutdown blocked: ${stopFailures.map((result) => publicError(result.reason)).join("; ")}`);
598
+ return false;
599
+ }
600
+ await this.persistQueue.catch(() => {});
601
+ this.tabs.clear();
602
+ for (const client of this.clients) client.socket.destroy();
603
+ await new Promise((resolve) => this.server?.close(() => resolve()) || resolve());
604
+ await removeSupervisorState(this.paths, { removeSocket: true, instanceId: this.instanceId }).catch(() => {});
605
+ process.exit(0);
606
+ }
607
+ }
608
+
609
+ const options = cliOptions(process.argv.slice(2));
610
+ const paths = await supervisorPaths(options);
611
+ const host = new SupervisorHost(paths);
612
+ await host.start();