@firstpick/pi-package-webui 0.7.5 → 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.
Files changed (40) hide show
  1. package/README.md +37 -4
  2. package/bin/pi-webui-rpc-supervisor.mjs +518 -0
  3. package/bin/pi-webui.mjs +1003 -82
  4. package/lib/WEBUI_TUI_NATIVE_PARITY.json +13 -0
  5. package/lib/rpc-supervisor-client.mjs +301 -0
  6. package/lib/rpc-supervisor-protocol.mjs +236 -0
  7. package/lib/rpc-supervisor-state.mjs +165 -0
  8. package/lib/trust-boundaries.mjs +1 -0
  9. package/package.json +2 -2
  10. package/public/app.js +1243 -87
  11. package/public/index.html +334 -24
  12. package/public/service-worker.js +6 -1
  13. package/public/styles.css +642 -41
  14. package/public/subagent-gate-visibility.mjs +36 -0
  15. package/public/workflow-status-stack.mjs +69 -0
  16. package/tests/app-runner-process-tree-harness.test.mjs +37 -3
  17. package/tests/boot-failure-diagnostics.test.mjs +180 -0
  18. package/tests/compact-sections-static.test.mjs +111 -0
  19. package/tests/durable-rpc-supervisor-harness.test.mjs +252 -0
  20. package/tests/fast-mode-client-static.test.mjs +2 -2
  21. package/tests/fixtures/compacting-pi.mjs +0 -0
  22. package/tests/fixtures/fake-pi.mjs +81 -2
  23. package/tests/git-panel-file-preview-static.test.mjs +221 -0
  24. package/tests/http-endpoints-harness.test.mjs +458 -33
  25. package/tests/mobile-static.test.mjs +77 -9
  26. package/tests/native-parity-harness.test.mjs +2 -1
  27. package/tests/native-parity.test.mjs +11 -0
  28. package/tests/numpad-decimal-input-static.test.mjs +128 -0
  29. package/tests/prompt-routing-input-clear-static.test.mjs +34 -0
  30. package/tests/prompt-routing-tab-status.test.mjs +103 -0
  31. package/tests/rpc-supervisor-host.test.mjs +275 -0
  32. package/tests/rpc-supervisor-protocol.test.mjs +67 -0
  33. package/tests/rpc-supervisor-state.test.mjs +62 -0
  34. package/tests/run-all.mjs +4 -1
  35. package/tests/streaming-ui-coupling.test.mjs +15 -0
  36. package/tests/subagent-gate-visibility.test.mjs +66 -0
  37. package/tests/subagent-launch-slots-static.test.mjs +1 -1
  38. package/tests/subagents-helper.test.mjs +145 -8
  39. package/tests/workflow-status-stack.test.mjs +87 -0
  40. package/webui-rpc-helper.mjs +164 -4
package/README.md CHANGED
@@ -69,7 +69,7 @@ Examples:
69
69
  /webui-start --name browser -- --model anthropic/claude-sonnet-4-5:high
70
70
  ```
71
71
 
72
- Running `/webui-start` again on the same URL restarts the server and restores currently open Web UI tabs from their session files when possible.
72
+ Running `/webui-start` again on the same URL restarts the HTTP server. By default, supervised Pi tabs—including an active model turn—continue in their original Pi processes and reconnect to the replacement server; session-file restoration remains the fallback when no managed tabs exist.
73
73
 
74
74
  ### `/webui-status` options
75
75
 
@@ -125,6 +125,7 @@ Environment variables:
125
125
  - `PI_WEBUI_PI_BIN=/path/to/pi` selects the Pi executable when `--pi` is not passed.
126
126
  - `PI_WEBUI_REMOTE_AUTH=1` starts with Remote PIN authentication enabled.
127
127
  - `PI_WEBUI_OUTPUT_MODE=normal|compact-v1` sets the server default for newly auto-negotiated browser connections.
128
+ - `PI_WEBUI_RPC_SUPERVISOR=0` opts out to the legacy server-owned Pi transport only when the current scope has no live managed tabs. Use explicit shutdown before disabling or downgrading; fallback startup refuses to create duplicate direct children for a live managed scope.
128
129
  - Pi Web UI automatically injects a loopback `PI_WEBUI_RECOVERY_URL` and a bearer `PI_WEBUI_RECOVERY_TOKEN` into spawned Pi RPC processes. The authenticated endpoint can only create a separate plan-only recovery tab; keep any manually supplied token private.
129
130
  - `PI_WEBUI_SETTINGS_FILE=/path/to/settings.json` overrides persisted Web UI settings such as Remote PIN auth, guided Git preferences, and global Tools/Skills defaults.
130
131
  - `PI_WEBUI_OPTIONAL_FEATURE_INSTALL_ROOT=/path/to/package-root` overrides the npm prefix used for optional companion installs.
@@ -133,6 +134,23 @@ Environment variables:
133
134
  - `PI_BANG_AUTOCOMPLETE_INCLUDE_HISTORY=1` lets optional bang-command autocomplete include local fish/bash/zsh history executables.
134
135
  - `PI_BANG_AUTOCOMPLETE_RUNTIME_STORE_PATH=/path/to/runtime.json` overrides the runtime store shared with `@firstpick/pi-extension-bang-command-autocomplete`.
135
136
 
137
+ ### Durable Pi session continuity
138
+
139
+ Pi Web UI normally runs Pi RPC tabs under a narrow detached supervisor. Restarting only the HTTP Web UI—through `/webui-start` on the same URL, **Restart**, a successful **Update & restart**, `POST /api/restart`, or a restart-safe service-manager `SIGTERM`—preserves each managed Pi PID, tab identity, cwd, session file, running state, and active model turn. Output produced while the HTTP server is absent is replayed in supervisor order. The browser rejects duplicate or older replay records; if the bounded live buffer has a gap, it refreshes tabs, state, and the durable transcript from Pi and warns that buffered live output may be incomplete.
140
+
141
+ Continuity is scoped to the resolved private Pi agent/config root and Web UI port. A replacement server must use the same root and port; changing ports creates a different scope and does not migrate active tabs. The supervisor communicates only over per-user local IPC (an owner-private Unix-domain socket on POSIX or a local named pipe on Windows) with a private random credential and incarnation fencing. Runtime state and metadata are private (`0700` directory and `0600` files on POSIX), bounded, and secret-key sanitized. Supervisor credentials, IPC paths, and raw private state are not exposed to browser APIs, server diagnostics, logs, or Pi child environments.
142
+
143
+ Updates preserve already-running supervised Pi processes, so an active tab continues with the Pi/runtime code it already loaded. Newly created or explicitly reloaded tabs use the newly installed versions. Additive supervisor protocol-minor changes are compatible; a protocol-major mismatch with live children fails closed instead of replacing the supervisor or spawning duplicates. Roll forward to a compatible Web UI rather than killing a healthy supervisor that owns active work.
144
+
145
+ Continuity deliberately excludes app runners: restart and update stop their process trees, and they must be started again after reconnection. It also does not preserve browser drafts, SSE connections, arbitrary extension memory, or an active request across supervisor failure, OS reboot, power loss, or machine restart. Session files can still restore durable transcript history after those failures, but they cannot resume the same in-flight model request.
146
+
147
+ Operations and recovery:
148
+
149
+ - Use `/webui-status detailed`, `GET /api/health`, or `GET /api/webui-status?detailed=1` for diagnostics. Public supervisor diagnostics are limited to enabled/attached state and managed-tab count; private credentials and paths are intentionally omitted. A browser warning about incomplete buffered output means authoritative tabs/state/messages were requested, not that missing live deltas were reconstructed.
150
+ - Use the side-panel **Stop** action or localhost-only `POST /api/shutdown` for an explicit full stop. Explicit tab close terminates only that managed Pi child; explicit shutdown and `SIGINT` terminate the scope's managed Pi children. Do not use restart/update when the intent is to terminate active work.
151
+ - Normal authenticated shutdown removes the private scope state. Do not manually delete runtime files, sockets, pipes, journals, or PID records while managed tabs may be live. For cleanup, explicitly shut down first, verify the Web UI/scope has no managed tabs, and let normal startup clean stale empty state; removing private state for a live supervisor destroys the safe attachment path and can risk duplicate processes.
152
+ - To opt out or roll back, first perform explicit shutdown and verify no managed tabs remain. Then set `PI_WEBUI_RPC_SUPERVISOR=0` and restart, or install the previous Web UI package before restarting. Never disable, downgrade, change the continuity port, or remove private runtime state while a supervisor still owns live tabs. Re-enable by removing the opt-out and starting normally; continuity begins for newly supervised Pi tabs.
153
+
136
154
  ### Compact live output mode
137
155
 
138
156
  Normal output is the default. In the sidebar, open **Controls → Output processing**, select **Fast**, and click **Apply**. The same persisted server default is also available under **Settings → Browser workflow → Output processing**. Alternatively, set `--output-mode compact-v1`, `PI_WEBUI_OUTPUT_MODE=compact-v1`, or `outputModeDefault` directly. Precedence is explicit CLI flag, then environment variable, then the persisted setting, then `normal`.
@@ -173,7 +191,7 @@ Optional Natural Conversation server-side voice fallback variables:
173
191
  - Persistent context-window meter with manual compact and auto-compaction controls near the composer; side-panel thinking changes made while a tab is busy are queued for the next prompt.
174
192
  - Side-panel theme picker backed by optional `@firstpick/pi-themes-bundle` themes when loaded.
175
193
  - Per-tab cwd changes, a clickable footer cwd picker, directory creation/search in the picker, saved path fast picks, server-persisted fast picks, and restart-safe restoration of open tabs. When the optional stats and git-footer companions are loaded, clicking the footer **PI** token metric dispatches `/calibrate` in the background and refreshes the metric after the isolated calibration sample is recorded.
176
- - Detected app runner dropdown for the active tab cwd, including Cargo, Bun, npm/npx/pnpm, Python/uv, Go/Golang, Zig, C/C++, Docker Compose, root/dev/scripts shell scripts, and other common project runners with live output pinned at the top of the terminal. Running app runners expose line-oriented stdin in the widget for interactive scripts. Projects can add browseable custom runners in `.pi-webui-runners.json` with a command (default `./`) plus a relative path to the file to run.
194
+ - Detected app runner dropdown for the active tab cwd, including Cargo, Bun, npm/npx/pnpm, Python/uv, Go/Golang, Zig, C/C++, Docker Compose, root/dev/scripts shell scripts, and other common project runners with live output pinned at the top of the terminal. Running app runners expose line-oriented stdin in the widget for interactive scripts. Projects can add browseable custom runners in `.pi-webui-runners.json` with a command (default `./`) plus a relative path to the file to run. The same dialog also configures project discovery paths: project-relative directories that are scanned one level deep (no subdirectories) for `.sh`, `.bash`, `.zsh`, `.fish`, and `.py` files plus extensionless files with a bash/sh, zsh, fish, or Python shebang. Python candidates use `uv run` and/or the available `python3`/`python` interpreter. Discovered scripts extend the built-in root, `dev/`, `scripts/`, and `dev/scripts/` detection and run from the resolved project root.
177
195
  - Guided Git workflow for existing repos and new repos with persistent model/reasoning preferences, review-first staging, an optional manual staged repository-review gate from `aur-review`, generated or typed commit messages, explicit push/PR confirmation, and optional PR worktrees. When the review extension is loaded/enabled, both `git add .` and accepting the current staged set send `/aur-review start --scope staged --origin guided-git` to the same tab. Only its matching approval advances to message generation. The browser and server recheck the approved domain-separated staged-content hash before message generation, commit, and PR-worktree transfer; drift, missing hashes, or hash-check errors return to Stage and require a new review. A decline returns to staging and rejects an unchanged declined staged hash until corrected content is restaged. Guided Git never stages, commits, or pushes remediation automatically. The extension remains the decision authority; direct API callers are not granted an approval by this browser workflow.
178
196
  - Browser support for Pi extension UI prompts, widgets, status updates, `/btw` side-question output widgets with optional context transfer/live steering, browser notifications when a tab needs an extension UI response, and an optional side-panel toggle for agent-done notifications.
179
197
  - Localhost-only Pi/Web UI update checks with a top-right update notification and confirmed restart actions: **Update Pi & restart** runs `pi update --self` for Pi-only updates, while **Update Pi + Packages & Restart** first checks the selected Pi executable's `pi update --help`. It uses `pi update --all` when advertised, otherwise falls back to `pi update --self` followed by `pi update --extensions`, then updates detected Web UI/Optional Feature package roots for configured, local agent, project, global npm, and global Bun installs.
@@ -244,8 +262,23 @@ These screenshots show the v0.4.8 Web UI surfaces. Current implementations inclu
244
262
 
245
263
  ![Pi Web UI app runner selector showing detected project runners and custom runner creation](https://raw.githubusercontent.com/Firstp1ck/pi-coding-agent-forge/main/pi-package-webui/images/Webui_AppRunner_v0.4.8.png)
246
264
 
247
- - **What it is:** A project runner detector for common stacks plus browseable custom runners from `.pi-webui-runners.json`.
265
+ - **What it is:** A project runner detector for common stacks plus browseable custom runners and project discovery paths from `.pi-webui-runners.json`.
248
266
  - **What you can do:** Launch dev servers, tests, builds, scripts, and custom commands from the active cwd, pass arguments, watch pinned live output, and send line-oriented stdin to interactive runners. Windows runners use ConPTY through the optional `node-pty` dependency so Bash/Node scripts receive a real TTY; set `PI_WEBUI_APP_RUNNER_PTY=off` to force the pipe fallback.
267
+ - **Project discovery paths:** The app-runner dialog stays reachable even when nothing is detected, so you can add extra directories to scan for shell and Python scripts. Paths are project-local and relative to the resolved project root (`.` means the project root itself), are browseable from the dialog, and are saved beside custom runners.
268
+
269
+ `.pi-webui-runners.json` uses a backward-compatible version 2 shape; a missing `searchPaths` array simply means no extra directories are scanned:
270
+
271
+ ```json
272
+ {
273
+ "version": 2,
274
+ "searchPaths": ["tools", "ops/scripts"],
275
+ "runners": [
276
+ { "id": "start-dev", "label": "Start dev", "command": "./", "path": "dev/scripts/start.sh", "args": [] }
277
+ ]
278
+ }
279
+ ```
280
+
281
+ Discovery-path rules: at most 24 paths and direct children only (no recursive walk). Shell discovery supports `.sh`, `.bash`, `.zsh`, `.fish`, and matching extensionless shebang files. Python discovery supports `.py` and extensionless Python-shebang files, exposing `uv run` and/or the available `python3`/`python` interpreter. Required interpreters must be installed locally; duplicates and built-in overlaps do not duplicate menu entries. Absolute, drive/UNC, `..`, null-byte, missing, non-directory, or symlinked-outside-the-project paths are rejected. Stale or invalid stored paths surface diagnostics in the dialog instead of being scanned. `POST /api/app-runner-config` accepts either `{ "runner": { ... } }` or `{ "searchPaths": [...] }` (not both in one request) and preserves the other field.
249
282
 
250
283
  ### Queue manager
251
284
 
@@ -349,7 +382,7 @@ Useful browser endpoints exposed by the local server include:
349
382
  - `GET /api/skill-file` and localhost-only `POST /api/skill-file` for guarded `SKILL.md` editing from tracked skill tags.
350
383
  - `GET /api/sessions`, `GET /api/session-tree`, `POST /api/switch-session`, `POST /api/session-rename`, and localhost-only `POST /api/session-delete` for resume/tree/session metadata flows.
351
384
  - `GET /api/auth-providers` and localhost-only `POST /api/auth-logout` for provider-auth status and stored-credential removal.
352
- - `GET /api/app-runners`, `POST /api/app-runner`, `POST /api/app-runner/input`, `POST /api/app-runner/stop`, `GET/POST/DELETE /api/app-runner-config`, and `GET /api/app-runner-files` for detected and custom project runners.
385
+ - `GET /api/app-runners`, `POST /api/app-runner`, `POST /api/app-runner/input`, `POST /api/app-runner/stop`, `GET/POST/DELETE /api/app-runner-config`, and `GET /api/app-runner-files` for detected and custom project runners. `POST /api/app-runner-config` replaces project discovery paths with `{ "searchPaths": [...] }` or saves a custom runner with `{ "runner": { ... } }`; invalid path submissions fail atomically and leave the stored configuration unchanged.
353
386
  - `GET /api/git-root`, `GET /api/git-panel`, and `GET /api/git-commit?hash=<full-hash>` for compact per-terminal-group repository discovery, local status/history snapshots, and bounded read-only commit diffs. `POST /api/git-changes/stage-all` and `POST /api/git-changes/unstage-all` complement the guarded path-level staging routes.
354
387
  - `GET /api/git-changes`, `POST /api/git-changes/pull`, `GET /api/git-branches`, `POST /api/git-branch`, and `/api/git-workflow/*` for browser Git status, diff, branch, init, commit, push, and PR helpers.
355
388
  - `POST /api/action-feedback?tab=<tabId>` for feedback on final assistant output and action cards.
@@ -0,0 +1,518 @@
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
+
39
+ function cliOptions(argv) {
40
+ const options = { agentDir: defaultAgentDir(), port: undefined, runtimeDir: undefined };
41
+ for (let index = 0; index < argv.length; index += 1) {
42
+ const value = argv[index];
43
+ if (value === "--agent-dir") options.agentDir = argv[++index];
44
+ else if (value === "--port") options.port = Number(argv[++index]);
45
+ else if (value === "--runtime-dir") options.runtimeDir = argv[++index];
46
+ else throw new Error(`Unknown option: ${value}`);
47
+ }
48
+ if (!options.agentDir || !Number.isInteger(options.port) || options.port < 1 || options.port > 65535) {
49
+ throw new Error("Usage: pi-webui-rpc-supervisor --agent-dir <private-agent-dir> --port <1-65535> [--runtime-dir <private-dir>]");
50
+ }
51
+ return options;
52
+ }
53
+
54
+ function tabSnapshot(tab) {
55
+ return {
56
+ id: tab.id,
57
+ metadata: tab.metadata,
58
+ pid: tab.child?.pid,
59
+ startedAt: tab.startedAt,
60
+ running: tabRunning(tab),
61
+ };
62
+ }
63
+
64
+ function tabRunning(tab) {
65
+ return !!tab?.child && tab.child.exitCode === null && tab.child.signalCode === null;
66
+ }
67
+
68
+ function publicError(error) {
69
+ if (error instanceof RpcSupervisorProtocolError) return error.message;
70
+ return String(error?.message || error || "Supervisor operation failed").replace(/(?:token|secret|password)=[^\s]+/gi, "$1=[redacted]");
71
+ }
72
+
73
+ function exitPromise(child, timeoutMs = CHILD_STOP_GRACE_MS) {
74
+ if (!child || child.exitCode !== null || child.signalCode !== null) return Promise.resolve();
75
+ return new Promise((resolve) => {
76
+ const timer = setTimeout(resolve, timeoutMs);
77
+ timer.unref?.();
78
+ child.once("exit", () => { clearTimeout(timer); resolve(); });
79
+ });
80
+ }
81
+
82
+ class SupervisorHost {
83
+ constructor(paths) {
84
+ this.paths = paths;
85
+ this.token = newSupervisorToken();
86
+ this.instanceId = randomUUID();
87
+ this.epoch = randomUUID();
88
+ this.sequence = 0n;
89
+ this.tabs = new Map();
90
+ this.events = [];
91
+ this.retainedEventBytes = 0;
92
+ this.requests = new Map();
93
+ this.clients = new Set();
94
+ this.controller = null;
95
+ this.server = null;
96
+ this.closing = false;
97
+ this.idleTimer = null;
98
+ this.persistQueue = Promise.resolve();
99
+ }
100
+
101
+ async start() {
102
+ await ensureSupervisorRuntime(this.paths);
103
+ const current = await readSupervisorState(this.paths);
104
+ if (current) {
105
+ if (supervisorPidIsAlive(current.pid)) {
106
+ throw Object.assign(new Error(`Refusing to replace live RPC supervisor ${current.pid}`), { code: "RPC_SUPERVISOR_LIVE_STATE" });
107
+ }
108
+ // A direct supervisor launch is still constrained to the same stale-state
109
+ // rule as the client launcher. The normal replacement path also holds
110
+ // the startup lock before reaching here.
111
+ const removed = await removeSupervisorState(this.paths, { removeSocket: true, instanceId: current.instanceId });
112
+ if (!removed) throw new Error("RPC supervisor state changed while removing a confirmed-dead owner");
113
+ } else if (process.platform !== "win32") {
114
+ // No descriptor exists to identify an incumbent. This can only clean an
115
+ // orphaned local socket; a recorded live supervisor is never removed.
116
+ await rm(this.paths.socketPath, { force: true }).catch(() => {});
117
+ }
118
+ this.server = createServer((socket) => this.accept(socket));
119
+ this.server.on("error", (error) => {
120
+ console.error(`RPC supervisor listener error: ${publicError(error)}`);
121
+ this.shutdown("listener error").catch(() => process.exitCode = 1);
122
+ });
123
+ await new Promise((resolve, reject) => {
124
+ const onError = (error) => { this.server.off("listening", onListening); reject(error); };
125
+ const onListening = () => { this.server.off("error", onError); resolve(); };
126
+ this.server.once("error", onError);
127
+ this.server.once("listening", onListening);
128
+ this.server.listen(this.paths.socketPath);
129
+ });
130
+ await this.persist("started");
131
+ this.scheduleIdleExit();
132
+ }
133
+
134
+ persist(reason) {
135
+ const operation = this.persistQueue.catch(() => {}).then(async () => {
136
+ if (this.closing) return;
137
+ const tabs = [...this.tabs.values()].map(tabSnapshot);
138
+ await writeSupervisorState(this.paths, {
139
+ token: this.token,
140
+ instanceId: this.instanceId,
141
+ pid: process.pid,
142
+ startedAt: new Date().toISOString(),
143
+ epoch: this.epoch,
144
+ tabs,
145
+ });
146
+ await appendSupervisorJournal(this.paths, { type: "snapshot", reason, epoch: this.epoch, tabs }).catch(() => {});
147
+ });
148
+ this.persistQueue = operation;
149
+ return operation;
150
+ }
151
+
152
+ accept(socket) {
153
+ socket.setNoDelay(true);
154
+ const client = { socket, attached: false, controllerId: null, attachTimer: null };
155
+ client.attachTimer = setTimeout(() => {
156
+ if (client.attached) return;
157
+ 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" }));
158
+ socket.destroy();
159
+ }, ATTACH_TIMEOUT_MS);
160
+ client.attachTimer.unref?.();
161
+ this.clients.add(client);
162
+ this.cancelIdleExit();
163
+ const consume = frameReader(
164
+ (frame) => this.handleFrame(client, frame).catch((error) => this.sendError(client, undefined, error)),
165
+ (error) => { this.sendError(client, undefined, error); socket.destroy(); },
166
+ );
167
+ socket.on("data", consume);
168
+ socket.on("error", () => {});
169
+ socket.on("close", () => {
170
+ if (client.attachTimer) clearTimeout(client.attachTimer);
171
+ client.attachTimer = null;
172
+ this.clients.delete(client);
173
+ if (this.controller?.client === client) this.controller = null;
174
+ this.scheduleIdleExit();
175
+ });
176
+ }
177
+
178
+ send(client, frame) {
179
+ if (!client?.socket || client.socket.destroyed) return;
180
+ // Frames from Pi are local transport data, not persisted metadata. Never
181
+ // strip or truncate them here; explicit frame-size validation rejects an
182
+ // oversized record instead of silently changing it.
183
+ try { client.socket.write(encodeFrame(frame)); } catch { client.socket.destroy(); }
184
+ }
185
+
186
+ sendError(client, requestId, error) {
187
+ this.send(client, { type: "result", ...(requestId ? { requestId } : {}), ok: false, code: error?.code || "RPC_SUPERVISOR_ERROR", error: publicError(error) });
188
+ }
189
+
190
+ async handleFrame(client, frame) {
191
+ const request = validateClientFrame(frame);
192
+ if (request.type === "attach") return this.attach(client, request);
193
+ if (!client.attached || this.controller?.client !== client || this.controller?.controllerId !== client.controllerId) {
194
+ throw Object.assign(new Error("This RPC supervisor connection is not the active controller"), { code: "RPC_SUPERVISOR_FENCED" });
195
+ }
196
+ await this.operation(client, request);
197
+ }
198
+
199
+ attach(client, request) {
200
+ assertProtocolCompatible(request.version);
201
+ if (request.scopeId !== this.paths.scopeId || !constantTimeTokenEqual(request.token, this.token)) {
202
+ throw Object.assign(new Error("RPC supervisor authentication failed"), { code: "RPC_SUPERVISOR_AUTH" });
203
+ }
204
+ if (this.controller && this.controller.client !== client) {
205
+ this.send(this.controller.client, { type: "fenced", reason: "A newer server controller attached" });
206
+ this.controller.client.attached = false;
207
+ }
208
+ if (client.attachTimer) clearTimeout(client.attachTimer);
209
+ client.attachTimer = null;
210
+ client.attached = true;
211
+ client.controllerId = request.controllerId;
212
+ this.controller = { client, controllerId: request.controllerId, attachedAt: Date.now() };
213
+ const replay = this.replayFor(request.cursor);
214
+ this.send(client, {
215
+ type: "attached",
216
+ version: RPC_SUPERVISOR_PROTOCOL,
217
+ scopeId: this.paths.scopeId,
218
+ epoch: this.epoch,
219
+ tabs: [...this.tabs.values()].map(tabSnapshot),
220
+ earliestSeq: this.events.length ? this.events[0].seq : this.sequence.toString(),
221
+ latestSeq: this.sequence.toString(),
222
+ gap: replay.gap,
223
+ replay: replay.events,
224
+ });
225
+ }
226
+
227
+ replayFor(cursor) {
228
+ // A controller without a persisted handoff cursor cannot know which prior
229
+ // output it observed. Replay the retained suffix and require authoritative
230
+ // refresh whenever a live tab or retained history exists.
231
+ if (!cursor) return { gap: this.tabs.size > 0 || this.events.length > 0, events: [...this.events] };
232
+ if (cursor.epoch !== this.epoch) return { gap: true, events: [...this.events] };
233
+ const sequence = BigInt(cursor.seq);
234
+ const earliest = this.events.length ? BigInt(this.events[0].seq) : this.sequence + 1n;
235
+ const gap = sequence + 1n < earliest;
236
+ return { gap, events: this.events.filter((event) => BigInt(event.seq) > sequence) };
237
+ }
238
+
239
+ retainEvent(event) {
240
+ const bytes = Buffer.byteLength(JSON.stringify(event));
241
+ // Keep a contiguous retained suffix. An oversized live event is forwarded
242
+ // but clears prior history so cursors before it report an honest gap.
243
+ if (bytes > RPC_SUPERVISOR_EVENT_RING_MAX_BYTES) {
244
+ this.events = [];
245
+ this.retainedEventBytes = 0;
246
+ return;
247
+ }
248
+ this.events.push(event);
249
+ this.retainedEventBytes += bytes;
250
+ while (this.events.length > RPC_SUPERVISOR_EVENT_RING_LIMIT || this.retainedEventBytes > RPC_SUPERVISOR_EVENT_RING_MAX_BYTES) {
251
+ const evicted = this.events.shift();
252
+ this.retainedEventBytes -= Buffer.byteLength(JSON.stringify(evicted));
253
+ }
254
+ }
255
+
256
+ emit(tabId, payload) {
257
+ this.sequence += 1n;
258
+ const event = { type: "event", epoch: this.epoch, seq: this.sequence.toString(), scopeId: this.paths.scopeId, tabId, at: new Date().toISOString(), payload };
259
+ this.retainEvent(event);
260
+ for (const client of this.clients) if (client.attached && this.controller?.client === client) this.send(client, event);
261
+ return event;
262
+ }
263
+
264
+ pruneSettledRequests() {
265
+ for (const [requestId, entry] of this.requests) {
266
+ if (entry.settled) this.requests.delete(requestId);
267
+ }
268
+ }
269
+
270
+ async operation(client, request) {
271
+ const prior = this.requests.get(request.requestId);
272
+ if (prior) {
273
+ try { this.send(client, { type: "result", requestId: request.requestId, ok: true, data: await prior.promise }); }
274
+ catch (error) { this.sendError(client, request.requestId, error); }
275
+ return;
276
+ }
277
+ this.pruneSettledRequests();
278
+ if (this.requests.size >= RPC_SUPERVISOR_REQUEST_DEDUPE_LIMIT) {
279
+ this.sendError(client, request.requestId, Object.assign(new Error("RPC supervisor request dedupe capacity is occupied by unresolved work"), { code: "RPC_SUPERVISOR_DEDUPE_CAPACITY" }));
280
+ return;
281
+ }
282
+ const entry = { settled: false, promise: null };
283
+ entry.promise = Promise.resolve().then(() => this.perform(request));
284
+ entry.promise.then(() => { entry.settled = true; }, () => { entry.settled = true; });
285
+ this.requests.set(request.requestId, entry);
286
+ try { this.send(client, { type: "result", requestId: request.requestId, ok: true, data: await entry.promise }); }
287
+ catch (error) { this.sendError(client, request.requestId, error); }
288
+ }
289
+
290
+ async perform(request) {
291
+ switch (request.type) {
292
+ case "create": return this.create(request);
293
+ case "update": return this.update(request);
294
+ case "replace": return this.replace(request);
295
+ case "close": return this.closeTab(request.tabId);
296
+ case "command": return this.command(request);
297
+ case "write": return this.write(request);
298
+ case "ack": return { cursor: request.cursor };
299
+ case "prepare_handoff": return { epoch: this.epoch, latestSeq: this.sequence.toString(), tabs: [...this.tabs.values()].map(tabSnapshot) };
300
+ case "detach": return { detached: true };
301
+ case "shutdown":
302
+ setImmediate(() => this.shutdown("explicit shutdown"));
303
+ return { shuttingDown: true };
304
+ default: throw new Error(`Unsupported supervisor operation ${request.type}`);
305
+ }
306
+ }
307
+
308
+ async create({ tabId, metadata, child }) {
309
+ if (this.tabs.has(tabId)) throw new Error(`Managed tab already exists: ${tabId}`);
310
+ if (this.tabs.size >= RPC_SUPERVISOR_TAB_LIMIT) throw new Error(`Managed tab limit is ${RPC_SUPERVISOR_TAB_LIMIT}`);
311
+ const tab = { id: tabId, metadata, child: null, pending: new Map(), startedAt: new Date().toISOString() };
312
+ this.tabs.set(tabId, tab);
313
+ try { await this.spawnChild(tab, child); }
314
+ catch (error) { this.tabs.delete(tabId); throw error; }
315
+ await this.persist("create");
316
+ return tabSnapshot(tab);
317
+ }
318
+
319
+ async update({ tabId, metadata }) {
320
+ const tab = this.requireTab(tabId);
321
+ tab.metadata = metadata;
322
+ await this.persist("update");
323
+ return tabSnapshot(tab);
324
+ }
325
+
326
+ async replace({ tabId, metadata, child }) {
327
+ const tab = this.requireTab(tabId);
328
+ await this.stopChild(tab, "replace");
329
+ if (metadata !== undefined) tab.metadata = metadata;
330
+ await this.spawnChild(tab, child);
331
+ await this.persist("replace");
332
+ return tabSnapshot(tab);
333
+ }
334
+
335
+ async closeTab(tabId) {
336
+ const tab = this.requireTab(tabId);
337
+ await this.stopChild(tab, "close");
338
+ this.tabs.delete(tabId);
339
+ await this.persist("close");
340
+ this.scheduleIdleExit();
341
+ return { id: tabId, closed: true };
342
+ }
343
+
344
+ requireTab(tabId) {
345
+ const tab = this.tabs.get(tabId);
346
+ if (!tab) throw new Error(`Managed tab not found: ${tabId}`);
347
+ return tab;
348
+ }
349
+
350
+ async spawnChild(tab, child) {
351
+ const cwd = await realpath(child.cwd).catch(() => child.cwd);
352
+ const processChild = spawn(child.command, child.args, {
353
+ cwd,
354
+ env: sanitizedSupervisorEnvironment(process.env),
355
+ stdio: ["pipe", "pipe", "pipe"],
356
+ detached: process.platform !== "win32",
357
+ windowsHide: true,
358
+ });
359
+ tab.child = processChild;
360
+ tab.startedAt = new Date().toISOString();
361
+ processChild.on("error", (error) => {
362
+ this.emit(tab.id, { type: "pi_process_error", error: publicError(error) });
363
+ this.rejectPending(tab, error);
364
+ });
365
+ processChild.on("exit", (code, signal) => {
366
+ this.emit(tab.id, { type: "pi_process_exit", code, signal });
367
+ this.rejectPending(tab, new Error(`Pi RPC process exited${code === null ? "" : ` with code ${code}`}${signal ? ` (${signal})` : ""}`));
368
+ if (!this.closing) this.persist("child exit").catch(() => {});
369
+ });
370
+ this.readJsonl(processChild.stdout, (line) => this.handlePiLine(tab, line), tab.id);
371
+ this.readText(processChild.stderr, (text) => { if (text) this.emit(tab.id, { type: "pi_stderr", text }); });
372
+ // The executable/arguments are launch details, not WebUI event data; never
373
+ // publish them because command-line credentials must stay private.
374
+ this.emit(tab.id, { type: "pi_process_start", pid: processChild.pid, cwd });
375
+ }
376
+
377
+ readJsonl(stream, onLine, tabId) {
378
+ const decoder = new StringDecoder("utf8");
379
+ let buffer = "";
380
+ let bytes = 0;
381
+ let discarding = false;
382
+ const consume = (chunk) => {
383
+ let input = typeof chunk === "string" ? chunk : decoder.write(chunk);
384
+ while (input) {
385
+ if (discarding) {
386
+ const newline = input.indexOf("\n");
387
+ if (newline < 0) return;
388
+ input = input.slice(newline + 1); discarding = false; continue;
389
+ }
390
+ const newline = input.indexOf("\n");
391
+ const piece = newline < 0 ? input : input.slice(0, newline);
392
+ const size = Buffer.byteLength(piece);
393
+ if (bytes + size > PI_RPC_JSONL_LINE_MAX_BYTES) {
394
+ buffer = ""; bytes = 0;
395
+ this.emit(tabId, { type: "pi_stdout_line_too_large", maxBytes: PI_RPC_JSONL_LINE_MAX_BYTES });
396
+ if (newline < 0) { discarding = true; return; }
397
+ input = input.slice(newline + 1); continue;
398
+ }
399
+ buffer += piece; bytes += size;
400
+ if (newline < 0) return;
401
+ const line = buffer.endsWith("\r") ? buffer.slice(0, -1) : buffer;
402
+ buffer = ""; bytes = 0;
403
+ if (line) onLine(line);
404
+ input = input.slice(newline + 1);
405
+ }
406
+ };
407
+ stream.on("data", consume);
408
+ stream.on("end", () => { consume(decoder.end()); if (!discarding && buffer) onLine(buffer); });
409
+ }
410
+
411
+ readText(stream, onText) {
412
+ const decoder = new StringDecoder("utf8");
413
+ stream.on("data", (chunk) => onText(typeof chunk === "string" ? chunk : decoder.write(chunk)));
414
+ stream.on("end", () => { const tail = decoder.end(); if (tail) onText(tail); });
415
+ }
416
+
417
+ handlePiLine(tab, line) {
418
+ let payload;
419
+ try { payload = JSON.parse(line); }
420
+ catch (error) { this.emit(tab.id, { type: "pi_stdout_parse_error", line: line.slice(0, 4096), error: publicError(error) }); return; }
421
+ if (payload?.type === "response" && typeof payload.id === "string" && tab.pending.has(payload.id)) {
422
+ const pending = tab.pending.get(payload.id);
423
+ tab.pending.delete(payload.id);
424
+ clearTimeout(pending.timer);
425
+ pending.resolve(payload);
426
+ }
427
+ this.emit(tab.id, payload);
428
+ }
429
+
430
+ command({ tabId, requestId, command, timeoutMs = 60_000 }) {
431
+ const tab = this.requireTab(tabId);
432
+ if (!tabRunning(tab) || !tab.child?.stdin?.writable) throw new Error("Pi RPC process is not running");
433
+ const payload = { ...command, id: requestId };
434
+ return new Promise((resolve, reject) => {
435
+ const timer = setTimeout(() => {
436
+ tab.pending.delete(requestId);
437
+ reject(new Error(`Timed out waiting for RPC response to ${payload.type}`));
438
+ }, timeoutMs);
439
+ timer.unref?.();
440
+ tab.pending.set(requestId, { resolve, reject, timer });
441
+ try {
442
+ const writable = tab.child.stdin.write(`${JSON.stringify(payload)}\n`);
443
+ if (!writable) tab.child.stdin.once("drain", () => {});
444
+ } catch (error) {
445
+ clearTimeout(timer);
446
+ tab.pending.delete(requestId);
447
+ reject(error);
448
+ }
449
+ });
450
+ }
451
+
452
+ write({ tabId, command }) {
453
+ const tab = this.requireTab(tabId);
454
+ if (!tabRunning(tab) || !tab.child?.stdin?.writable) throw new Error("Pi RPC process is not running");
455
+ // Unlike `command`, this preserves the supplied Pi RPC object exactly and
456
+ // resolves after stdin accepts it; no response ID is injected or awaited.
457
+ return new Promise((resolve, reject) => {
458
+ try {
459
+ tab.child.stdin.write(`${JSON.stringify(command)}\n`, (error) => {
460
+ if (error) reject(error);
461
+ else resolve({ written: true });
462
+ });
463
+ } catch (error) {
464
+ reject(error);
465
+ }
466
+ });
467
+ }
468
+
469
+ rejectPending(tab, error) {
470
+ for (const [id, pending] of tab.pending) {
471
+ clearTimeout(pending.timer);
472
+ pending.reject(error);
473
+ tab.pending.delete(id);
474
+ }
475
+ }
476
+
477
+ async stopChild(tab, reason) {
478
+ if (!tab.child) return;
479
+ const child = tab.child;
480
+ this.emit(tab.id, { type: "pi_process_stopping", reason });
481
+ terminateProcessTree(child, "SIGTERM");
482
+ await exitPromise(child);
483
+ if (tabRunning(tab)) {
484
+ terminateProcessTree(child, "SIGKILL");
485
+ await exitPromise(child, 1_000);
486
+ }
487
+ this.rejectPending(tab, new Error(`Pi RPC process stopped for ${reason}`));
488
+ }
489
+
490
+ cancelIdleExit() {
491
+ if (this.idleTimer) clearTimeout(this.idleTimer);
492
+ this.idleTimer = null;
493
+ }
494
+
495
+ scheduleIdleExit() {
496
+ if (this.closing || this.tabs.size || this.clients.size || this.idleTimer) return;
497
+ this.idleTimer = setTimeout(() => this.shutdown("idle"), EMPTY_IDLE_GRACE_MS);
498
+ this.idleTimer.unref?.();
499
+ }
500
+
501
+ async shutdown(reason) {
502
+ if (this.closing) return;
503
+ this.closing = true;
504
+ this.cancelIdleExit();
505
+ await Promise.all([...this.tabs.values()].map((tab) => this.stopChild(tab, reason).catch(() => {})));
506
+ await this.persistQueue.catch(() => {});
507
+ this.tabs.clear();
508
+ for (const client of this.clients) client.socket.destroy();
509
+ await new Promise((resolve) => this.server?.close(() => resolve()) || resolve());
510
+ await removeSupervisorState(this.paths, { removeSocket: true, instanceId: this.instanceId }).catch(() => {});
511
+ process.exit(0);
512
+ }
513
+ }
514
+
515
+ const options = cliOptions(process.argv.slice(2));
516
+ const paths = await supervisorPaths(options);
517
+ const host = new SupervisorHost(paths);
518
+ await host.start();