@andares/pi-toolkits 1.2.0 → 1.2.2

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.
@@ -0,0 +1,80 @@
1
+ /**
2
+ * The port pool is a shared one: `/ask-spec`, `/ask-uat` and `/ask-talk` all
3
+ * walk from 7600, and a walk that left the hundred block would silently give
4
+ * the next feature's pool away. These tests pin the range, not the feature.
5
+ */
6
+ import { createServer as createNetServer, type AddressInfo } from "node:net";
7
+ import { afterEach, describe, expect, it } from "vitest";
8
+ import { portWalk, startWebServer, type WebServerHandle } from "./web-review.js";
9
+
10
+ const cleanups: Array<() => Promise<void>> = [];
11
+
12
+ afterEach(async () => {
13
+ for (const cleanup of cleanups.splice(0)) await cleanup();
14
+ });
15
+
16
+ describe("portWalk", () => {
17
+ it("walks the whole hundred block by default", () => {
18
+ const ports = portWalk(7600);
19
+ expect(ports[0]).toBe(7600);
20
+ expect(ports.at(-1)).toBe(7699);
21
+ expect(ports).toHaveLength(100);
22
+ });
23
+
24
+ it("honours an explicit attempt count", () => {
25
+ expect(portWalk(7600, 20)).toEqual(
26
+ Array.from({ length: 20 }, (_, index) => 7600 + index),
27
+ );
28
+ });
29
+
30
+ it("stops at the end of the block instead of spilling into the next one", () => {
31
+ expect(portWalk(7695, 20)).toEqual([7695, 7696, 7697, 7698, 7699]);
32
+ });
33
+
34
+ it("keeps a start on a boundary inside its own block", () => {
35
+ expect(portWalk(7700, 3)).toEqual([7700, 7701, 7702]);
36
+ });
37
+ });
38
+
39
+ describe("startWebServer", () => {
40
+ it("reports an exhausted pool as a range, and does not start", async () => {
41
+ const blocker = createNetServer();
42
+ await new Promise<void>((resolve, reject) => {
43
+ blocker.once("error", reject);
44
+ blocker.listen(0, "127.0.0.1", resolve);
45
+ });
46
+ const port = (blocker.address() as AddressInfo).port;
47
+ cleanups.push(() => new Promise<void>((resolve) => blocker.close(() => resolve())));
48
+
49
+ await expect(
50
+ startWebServer({
51
+ assetsDir: "/nonexistent-assets",
52
+ routes: () => false,
53
+ portStart: port,
54
+ portAttempts: 1,
55
+ bindHost: "127.0.0.1",
56
+ }),
57
+ ).rejects.toThrow(`cannot bind a review server on ports ${port}–${port}`);
58
+ });
59
+
60
+ it("takes the next port in the same block for a second page", async () => {
61
+ const start = 63_100 + Math.floor(Math.random() * 60);
62
+ const first: WebServerHandle = await startWebServer({
63
+ assetsDir: "/nonexistent-assets",
64
+ routes: () => false,
65
+ portStart: start,
66
+ bindHost: "127.0.0.1",
67
+ });
68
+ cleanups.push(() => first.close());
69
+ const second: WebServerHandle = await startWebServer({
70
+ assetsDir: "/nonexistent-assets",
71
+ routes: () => false,
72
+ portStart: start,
73
+ bindHost: "127.0.0.1",
74
+ });
75
+ cleanups.push(() => second.close());
76
+
77
+ expect(second.port).toBe(first.port + 1);
78
+ expect(Math.floor(second.port / 100)).toBe(Math.floor(start / 100));
79
+ });
80
+ });
@@ -55,6 +55,7 @@ export interface WebServerOptions {
55
55
  /** Called for authenticated `/api/*` requests; return true when handled. */
56
56
  routes: (ctx: WebRequestContext) => boolean | Promise<boolean>;
57
57
  portStart?: number;
58
+ /** How many ports to try; the walk still stops at the end of `portStart`'s hundred. */
58
59
  portAttempts?: number;
59
60
  /** Header the page echoes the token in. Default `x-plan-token`. */
60
61
  tokenHeader?: string;
@@ -129,11 +130,33 @@ function parseHost(value: string | undefined): string {
129
130
  return (value ?? "").toLowerCase();
130
131
  }
131
132
 
133
+ /**
134
+ * Ports to try, in order.
135
+ *
136
+ * The walk never leaves the hundred block `portStart` lives in (7600 → 7600…7699):
137
+ * every review page shares one pool, so an exhausted pool must fail loudly
138
+ * instead of drifting into 7700+, where the URL stops telling the operator
139
+ * anything and the next feature's own pool begins.
140
+ *
141
+ * The block sits high on purpose: 34xx is a range WSL and Windows-side
142
+ * forwarders grab for themselves, and a review page that silently loses its
143
+ * port to a forwarder is indistinguishable from one that never started.
144
+ */
145
+ export function portWalk(portStart: number, attempts = 100): number[] {
146
+ const blockEnd = Math.floor(portStart / 100) * 100 + 99;
147
+ // At least the start port: a zero attempt count must not turn the failure
148
+ // message into "ports undefined–undefined".
149
+ const last = Math.max(portStart, Math.min(portStart + Math.max(0, attempts) - 1, blockEnd));
150
+ const ports: number[] = [];
151
+ for (let port = portStart; port <= last; port += 1) ports.push(port);
152
+ return ports;
153
+ }
154
+
132
155
  export async function startWebServer(options: WebServerOptions): Promise<WebServerHandle> {
133
156
  const token = randomBytes(12).toString("hex");
134
157
  const tokenHeader = options.tokenHeader ?? "x-plan-token";
135
- const portStart = options.portStart ?? 3401;
136
- const attempts = options.portAttempts ?? 20;
158
+ const portStart = options.portStart ?? 7600;
159
+ const ports = portWalk(portStart, options.portAttempts);
137
160
  const host = options.bindHost ?? "127.0.0.1";
138
161
  const displayHost = options.urlHost ?? "127.0.0.1";
139
162
  const assetsRoot = resolve(options.assetsDir);
@@ -285,8 +308,7 @@ export async function startWebServer(options: WebServerOptions): Promise<WebServ
285
308
  const state = { closing: false };
286
309
  let currentPort = 0;
287
310
  let server: ReturnType<typeof createServer> | undefined;
288
- for (let attempt = 0; attempt < attempts; attempt += 1) {
289
- const port = portStart + attempt;
311
+ for (const port of ports) {
290
312
  const candidate = createServer((req, res) => {
291
313
  void handler(req, res, port, state).catch((error: unknown) => {
292
314
  text(res, `internal error: ${error instanceof Error ? error.message : String(error)}`, 500);
@@ -304,7 +326,7 @@ export async function startWebServer(options: WebServerOptions): Promise<WebServ
304
326
  candidate.close();
305
327
  }
306
328
  if (!server) {
307
- throw new Error(`cannot bind a review server on ports ${portStart}–${portStart + attempts - 1}`);
329
+ throw new Error(`cannot bind a review server on ports ${ports[0]}–${ports.at(-1)}`);
308
330
  }
309
331
  server.unref();
310
332
  heartbeat = setInterval(() => {
@@ -1,98 +0,0 @@
1
- /**
2
- * quit-guard feature — constants and the rationale behind them.
3
- *
4
- * WHY a terminal-sequence trigger instead of `session_shutdown`: pi runs
5
- * extension shutdown handlers one after another without a timeout. If a
6
- * handler loaded BEFORE ours never settles, our own `session_shutdown` never
7
- * runs, so a watchdog armed from that event would miss exactly the hangs it
8
- * is meant to catch. The teardown sequence below is written by the TUI
9
- * before that phase starts, so it arms the guard regardless of extension
10
- * load order (and even when the host's own writes are what hangs).
11
- *
12
- * Teardown markers (arm):
13
- * - `\x1b[?2004l` — bracketed paste off, written by `ProcessTerminal.stop()`
14
- * (both `regular` and `fullscreen` modes);
15
- * - `\x1b[?1049l` — alternate-screen exit, written by the fullscreen
16
- * renderer's `afterTerminalStop()`.
17
- *
18
- * Restart markers (disarm): a TUI that re-enters must never be killed by a
19
- * timer meant for a process that is leaving:
20
- * - `\x1b[?2004h` — bracketed paste on, `ProcessTerminal.start()`;
21
- * - `\x1b[?1049h` — alternate-screen enter, fullscreen `beforeTerminalStart()`.
22
- *
23
- * These cover the two legitimate teardown-then-restart paths: an interactive
24
- * TUI mode switch (`switchTuiMode()` stops the old renderer with
25
- * `preserveScreen`, then starts the new one) and Ctrl+Z suspend/resume
26
- * (`handleCtrlZ()` calls `ui.stop()`, then `ui.start()` on SIGCONT). The
27
- * SIGCONT listener in index.ts disarms synchronously as well, so an expired
28
- * timer cannot win a race against a resume.
29
- *
30
- * Scope: interactive TUI only. Print/JSON/RPC sessions never write these
31
- * sequences, so the guard stays inert there (documented boundary).
32
- */
33
- export const QUIT_GUARD_FILE = "pi-toolkits-quit-guard.json";
34
-
35
- /** Directory holding the JSON reports written when the guard fires. */
36
- export const QUIT_GUARD_REPORT_DIR = "quit-guard";
37
-
38
- /**
39
- * Default watchdog deadline, measured from the terminal teardown write.
40
- *
41
- * Measured on a 20-extension setup (2026-11-05): a healthy `/quit` spends
42
- * ~0.1–3 s between the teardown write and `process.exit(0)` (the whole
43
- * `runtimeHost.dispose()` / extension-shutdown phase), 5 s worst case end to
44
- * end, and 0.12 s with `pi -ne`. 8 s keeps ~3 s of margin over the slowest
45
- * healthy quit observed (enough for a memory flush or an MCP server close)
46
- * while returning the prompt sooner than the original 10 s when something
47
- * never settles. Set by the operator (2026-11-10); it is a default, not a
48
- * floor — `/quit-guard <ms>` still overrides it.
49
- */
50
- export const DEFAULT_TIMEOUT_MS = 8_000;
51
-
52
- /** Floor for `/quit-guard <ms>`: below this, a healthy slow quit would be cut. */
53
- export const MIN_TIMEOUT_MS = 2_000;
54
-
55
- /** Ceiling for `/quit-guard <ms>`: beyond this the user is better off with `kill -9`. */
56
- export const MAX_TIMEOUT_MS = 60_000;
57
-
58
- /** Sequences after which the interactive TUI has begun tearing down. */
59
- export const TEARDOWN_MARKERS = ["\x1b[?2004l", "\x1b[?1049l"] as const;
60
-
61
- /**
62
- * Pseudo-marker for the second, event-driven trigger.
63
- *
64
- * `shutdown({ fromSignal: true })` runs every extension's `session_shutdown`
65
- * handler BEFORE `ui.stop()` writes the teardown sequence (pi 1.5.1,
66
- * interactive-mode.js). With a handler that never settles, the marker is never
67
- * written and a sequence-only watchdog stays asleep: the process keeps the
68
- * terminal, raw mode and the frozen frame forever. `session_shutdown` with
69
- * reason `"quit"` is the only in-process signal available at that point, so it
70
- * arms the guard too. Session replacements use `"new"`/`"resume"`/`"fork"`
71
- * and `/reload` uses `"reload"` — those must never arm it.
72
- */
73
- export const SHUTDOWN_EVENT_MARKER = "session_shutdown";
74
-
75
- /**
76
- * Terminal restore written before every forced exit (writeSync(1, …), which
77
- * bypasses our own stdout wrapper and cannot re-arm the guard).
78
- *
79
- * The shutdown-event path needs it because nothing restored the terminal:
80
- * without it the prompt comes back on the alternate screen, with bracketed
81
- * paste on and the cursor hidden. The marker path gets it too (since
82
- * 2026-11-13): `ui.stop()` can also hang between its two sequences —
83
- * `?2004l` written, `?1049l` never — and an already-restored terminal
84
- * simply ignores the extra sequences. Idempotent, unlike a frozen screen.
85
- */
86
- export const TERMINAL_RESTORE = "\x1b[?2004l\x1b[?1049l\x1b[?25h\x1b[0m\r\n";
87
-
88
- /**
89
- * Grace period for the kill fallbacks that run AFTER the report is on disk
90
- * and "forcing exit" has been printed: `process.exit(0)` first, then, in
91
- * layers, a same-loop `setTimeout` SIGKILL and the independent-thread
92
- * SIGKILL from killer.ts (see there for why the timer alone is not enough:
93
- * the main thread can deadlock inside `process.exit`, where no timer runs).
94
- */
95
- export const HARD_KILL_DELAY_MS = 500;
96
-
97
- /** Sequences that mean a TUI is starting (mode switch or suspend/resume). */
98
- export const RESTART_MARKERS = ["\x1b[?2004h", "\x1b[?1049h"] as const;
@@ -1,235 +0,0 @@
1
- /**
2
- * quit-guard feature — watchdog state machine.
3
- *
4
- * Deliberately dependency-free and side-effect free: it is fed stdout chunks
5
- * and clock/scheduler callbacks, so every branch is unit-testable without a
6
- * real TUI. The wiring to `process.stdout`, `SIGCONT`, the settings store and
7
- * the actual `process.exit()` lives in index.ts.
8
- *
9
- * State machine:
10
- *
11
- * idle ──teardown marker──▶ armed ──timer──▶ fired (onFire, then exit)
12
- * ▲ │
13
- * └──restart marker / resume┘
14
- *
15
- * Invariants:
16
- * - arming is idempotent while armed (a teardown writes two markers);
17
- * - a TUI restart (mode switch, Ctrl+Z resume) always wins over the timer:
18
- * the fire callback is deferred one turn so a SIGCONT handler can disarm
19
- * first, and the token check drops a fire whose arm was superseded;
20
- * - disabled means inert: it never arms and disarms immediately.
21
- */
22
- import {
23
- RESTART_MARKERS,
24
- SHUTDOWN_EVENT_MARKER,
25
- TEARDOWN_MARKERS,
26
- } from "./constants.js";
27
-
28
- /** A chunk as written to `process.stdout` (string, or Buffer/typed array). */
29
- export type GuardChunk = string | Uint8Array;
30
-
31
- export interface GuardFireInfo {
32
- /** Clock value captured when the guard armed. */
33
- startedAt: number;
34
- /** Milliseconds spent armed (i.e. inside the shutdown phase). */
35
- elapsedMs: number;
36
- /** The teardown sequence that armed the guard. */
37
- marker: string;
38
- }
39
-
40
- export interface QuitGuardDeps {
41
- now?: () => number;
42
- /** Start a timer; returns a handle handed back to `cancel`. */
43
- schedule?: (run: () => void, ms: number) => unknown;
44
- cancel?: (handle: unknown) => void;
45
- /**
46
- * Defer one turn (setImmediate in production). Used so an expired timer
47
- * cannot beat a SIGCONT-driven disarm on the resume path.
48
- */
49
- defer?: (run: () => void) => void;
50
- /** Called exactly once per arm that reaches the deadline. */
51
- onFire: (info: GuardFireInfo) => void;
52
- /** Optional debug tap (PI_QUIT_GUARD_DEBUG); never affects behavior. */
53
- onEvent?: (event: "arm" | "disarm" | "fire", detail: string) => void;
54
- /**
55
- * Second, independent "is a TUI still running" signal, checked right before
56
- * firing. The teardown marker can also arrive inside rendered content (a
57
- * file or tool output that happens to contain the escape sequence); raw
58
- * mode cannot: the TUI leaves raw mode while tearing down. An active
59
- * session must never be killed by a stray marker.
60
- */
61
- isTuiActive?: () => boolean;
62
- }
63
-
64
- /** First marker in `markers` that appears in the chunk, if any. */
65
- export function findMarker(
66
- chunk: GuardChunk,
67
- markers: readonly string[],
68
- ): string | undefined {
69
- if (typeof chunk === "string") {
70
- if (chunk.length === 0) return undefined;
71
- for (const marker of markers) {
72
- if (chunk.includes(marker)) return marker;
73
- }
74
- return undefined;
75
- }
76
- if (!(chunk instanceof Uint8Array) || chunk.byteLength === 0) {
77
- return undefined;
78
- }
79
- // Buffers are the normal case; other typed arrays are rare enough that a
80
- // one-off copy is cheaper than a hand-rolled byte scan.
81
- const buffer: Buffer = Buffer.isBuffer(chunk)
82
- ? chunk
83
- : Buffer.from(chunk);
84
- for (const marker of markers) {
85
- if (buffer.includes(marker)) return marker;
86
- }
87
- return undefined;
88
- }
89
-
90
- export class QuitGuard {
91
- private readonly now: () => number;
92
- private readonly schedule: (run: () => void, ms: number) => unknown;
93
- private readonly cancel: (handle: unknown) => void;
94
- private readonly defer: (run: () => void) => void;
95
- private readonly onFire: (info: GuardFireInfo) => void;
96
- private readonly onEvent?: (event: "arm" | "disarm" | "fire", detail: string) => void;
97
- private readonly isTuiActive?: () => boolean;
98
-
99
- private enabled = true;
100
- private timeoutMs: number;
101
- private armed = false;
102
- private handle: unknown;
103
- private startedAt = 0;
104
- private armedBy = "";
105
- /** Incremented on every arm; a stale fire callback compares against it. */
106
- private armToken = 0;
107
-
108
- constructor(timeoutMs: number, deps: QuitGuardDeps) {
109
- this.timeoutMs = timeoutMs;
110
- // performance.now() is monotonic: a wall-clock jump (NTP, WSL VM
111
- // resume, manual `date`) must not make an 8 s deadline look like 5 s,
112
- // and `elapsedMs` in the hang report must measure real time spent.
113
- this.now = deps.now ?? (() => performance.now());
114
- this.schedule =
115
- deps.schedule ??
116
- ((run, ms) => setTimeout(run, ms));
117
- this.cancel =
118
- deps.cancel ??
119
- ((handle) => clearTimeout(handle as ReturnType<typeof setTimeout>));
120
- this.defer = deps.defer ?? ((run) => setImmediate(run));
121
- this.onFire = deps.onFire;
122
- this.onEvent = deps.onEvent;
123
- this.isTuiActive = deps.isTuiActive;
124
- }
125
-
126
- /** Feed one stdout chunk. Converts markers into arm/disarm transitions. */
127
- observeOutput(chunk: GuardChunk): void {
128
- if (!this.enabled) return;
129
- if (this.armed) {
130
- // While armed the only meaningful signal is "the TUI came back".
131
- if (findMarker(chunk, RESTART_MARKERS)) {
132
- this.disarm();
133
- }
134
- return;
135
- }
136
- const marker = findMarker(chunk, TEARDOWN_MARKERS);
137
- if (marker) this.arm(marker);
138
- }
139
-
140
- /** Process resumed from Ctrl+Z: the TUI is about to re-enter, never kill it. */
141
- resume(): void {
142
- this.disarm();
143
- }
144
-
145
- /**
146
- * Arm from a `session_shutdown` (reason `"quit"`) event, for shutdowns that
147
- * hang before the TUI writes its teardown sequence — the signal-triggered
148
- * path runs extension handlers first, so a stuck handler there never
149
- * produces a marker. No-op when a teardown marker already armed the guard,
150
- * so the measured deadline still starts at the earliest evidence.
151
- */
152
- armFromShutdown(): void {
153
- if (!this.enabled || this.armed) return;
154
- this.arm(SHUTDOWN_EVENT_MARKER);
155
- }
156
-
157
- setEnabled(enabled: boolean): void {
158
- this.enabled = enabled;
159
- if (!enabled) this.disarm();
160
- }
161
-
162
- isEnabled(): boolean {
163
- return this.enabled;
164
- }
165
-
166
- setTimeoutMs(timeoutMs: number): void {
167
- this.timeoutMs = timeoutMs;
168
- }
169
-
170
- getTimeoutMs(): number {
171
- return this.timeoutMs;
172
- }
173
-
174
- isArmed(): boolean {
175
- return this.armed;
176
- }
177
-
178
- private arm(marker: string): void {
179
- const token = (this.armToken += 1);
180
- const startedAt = this.now();
181
- this.armed = true;
182
- this.startedAt = startedAt;
183
- this.armedBy = marker;
184
- this.onEvent?.("arm", `${marker} timeout=${this.timeoutMs}ms`);
185
- this.handle = this.schedule(
186
- () => this.onTimeout(token, startedAt),
187
- this.timeoutMs,
188
- );
189
- }
190
-
191
- private disarm(): void {
192
- if (!this.armed) return;
193
- this.armed = false;
194
- this.onEvent?.("disarm", this.armedBy);
195
- if (this.handle !== undefined) {
196
- this.cancel(this.handle);
197
- this.handle = undefined;
198
- }
199
- }
200
-
201
- private onTimeout(token: number, startedAt: number): void {
202
- this.handle = undefined;
203
- // One turn later: a pending SIGCONT handler runs before this and can
204
- // disarm, so resume always wins over an expired timer.
205
- this.defer(() => {
206
- if (!this.armed || this.armToken !== token || this.startedAt !== startedAt) {
207
- return;
208
- }
209
- // The liveness probe is best-effort: if it throws (stdin already
210
- // destroyed/replaced during teardown), treat the TUI as gone and
211
- // still fire. A probe that can throw must not disable the watchdog.
212
- // An event-armed guard skips the probe on purpose: the TUI is still
213
- // up in exactly the signal-triggered case we are covering, and the
214
- // shutdown event (not rendered content) is what armed it.
215
- let tuiActive = false;
216
- if (this.armedBy !== SHUTDOWN_EVENT_MARKER) {
217
- try {
218
- tuiActive = this.isTuiActive?.() === true;
219
- } catch {
220
- tuiActive = false;
221
- }
222
- }
223
- if (tuiActive) {
224
- // A live TUI means the marker was content, not a teardown.
225
- this.armed = false;
226
- this.onEvent?.("disarm", "tui-still-active");
227
- return;
228
- }
229
- this.armed = false;
230
- const elapsedMs = this.now() - startedAt;
231
- this.onEvent?.("fire", `elapsed=${Math.round(elapsedMs)}ms`);
232
- this.onFire({ startedAt, elapsedMs, marker: this.armedBy });
233
- });
234
- }
235
- }