@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.
@@ -1,368 +0,0 @@
1
- /**
2
- * quit-guard feature — quit watchdog (`/quit-guard`).
3
- *
4
- * Problem this solves: pi's interactive `/quit` stops the TUI, then awaits
5
- * `runtimeHost.dispose()` — every extension's `session_shutdown` handler,
6
- * one after another, with no timeout (upstream issue #9997; still unbounded
7
- * in 1.6.0 and on main — 1.5.1 added `await session.abort()` before the
8
- * handler loop and `await settleCredentialWrites()` after it, 1.6.0 added
9
- * `await flushStdout()` further down, i.e. more awaits in the same untimed
10
- * chain, which makes the failure mode more likely, not
11
- * less). One handler that never settles leaves the process
12
- * alive at 0% CPU, the terminal already restored and the final frame
13
- * reprinted: the screen looks like a frozen "exit screen" and the shell
14
- * prompt never comes back. The `isShuttingDown` latch in the host then
15
- * swallows Ctrl+C / SIGTERM / SIGHUP, so only `kill -9` helps.
16
- *
17
- * The guard watches the terminal instead of the event stream, because the
18
- * event stream is exactly what can hang (a handler loaded before ours never
19
- * returns, so our own `session_shutdown` never runs). It arms when the TUI
20
- * writes its teardown sequence, and disarms if the TUI comes back (mode
21
- * switch, Ctrl+Z suspend/resume). If the deadline passes while pi is still
22
- * alive, it writes a JSON hang report and forces `process.exit(0)`.
23
- *
24
- * Wiring:
25
- * - one global `process.stdout.write` wrapper per process (survives
26
- * `/reload`; the shared state object is the source of truth, so a reload
27
- * only refreshes config/settings, never double-wraps);
28
- * - one `SIGCONT` listener: a resume must never be mistaken for a quit;
29
- * - `/quit-guard` — status / `on` / `off` / `<timeoutMs>`, persisted to
30
- * `<agent-dir>/pi-toolkits-quit-guard.json`.
31
- *
32
- * Settings file (all fields optional, defaults shown):
33
- * { "enabled": true, "timeoutMs": 8000, "report": true }
34
- */
35
- import { appendFileSync, existsSync, readdirSync, writeSync } from "node:fs";
36
- import { join } from "node:path";
37
- import { getAgentDir } from "@earendil-works/pi-coding-agent";
38
- import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
39
- import {
40
- HARD_KILL_DELAY_MS,
41
- MAX_TIMEOUT_MS,
42
- MIN_TIMEOUT_MS,
43
- QUIT_GUARD_FILE,
44
- QUIT_GUARD_REPORT_DIR,
45
- TERMINAL_RESTORE,
46
- } from "./constants.js";
47
- import { QuitGuard, type GuardFireInfo } from "./guard.js";
48
- import { armThreadHardKill, armThreadWatchdog, type ThreadWatchdog } from "./killer.js";
49
- import {
50
- collectHangReport,
51
- formatHangReportSummary,
52
- writeHangReport,
53
- } from "./report.js";
54
- import {
55
- QuitGuardStore,
56
- normalizeTimeoutMs,
57
- type QuitGuardConfig,
58
- } from "./store.js";
59
-
60
- /** Process-wide key; `/reload` re-imports the module but keeps this state. */
61
- const STATE_KEY = Symbol.for("@andares/pi-toolkits/quit-guard/state");
62
-
63
- interface QuitGuardState {
64
- store: QuitGuardStore;
65
- guard: QuitGuard;
66
- config: QuitGuardConfig;
67
- reportDir: string;
68
- installed: boolean;
69
- }
70
-
71
- function sharedState(): QuitGuardState | undefined {
72
- // SAFETY: `globalThis` is an untyped property bag; the symbol key is the
73
- // private contract and this module is the only writer.
74
- return (
75
- globalThis as unknown as Record<symbol, QuitGuardState | undefined>
76
- )[STATE_KEY];
77
- }
78
-
79
- function storeSharedState(state: QuitGuardState): void {
80
- // SAFETY: same contract as `sharedState`; the value shape is checked by this
81
- // module, not by the property bag.
82
- (
83
- globalThis as unknown as Record<symbol, QuitGuardState | undefined>
84
- )[STATE_KEY] = state;
85
- }
86
-
87
- function fire(state: QuitGuardState, info: GuardFireInfo): void {
88
- // Restore the terminal on every path, not just the shutdown-event one.
89
- // When the guard was armed by `session_shutdown` nothing restored the
90
- // terminal at all: without this write the prompt comes back on the
91
- // alternate screen, with bracketed paste on and the cursor hidden. When it
92
- // was armed by a teardown marker the TUI usually already restored — but
93
- // `ui.stop()` can also hang between its two sequences (`?2004l` written,
94
- // `?1049l` never), and a terminal that is already healthy ignores the
95
- // extra sequences. `writeSync(1, …)` bypasses our own stdout wrapper, so
96
- // these sequences cannot re-arm the guard.
97
- try {
98
- writeSync(1, TERMINAL_RESTORE);
99
- } catch {
100
- // Dead terminal: the report and the exit still happen.
101
- }
102
- const timeoutMs = state.guard.getTimeoutMs();
103
- const elapsedMs = Math.round(info.elapsedMs);
104
- let reportPath: string | undefined;
105
- let summary: string | undefined;
106
- if (state.config.report) {
107
- // Diagnostics only: a throwing report (deleted cwd, unreadable home, ...)
108
- // must never keep the user from getting the prompt back.
109
- try {
110
- const report = collectHangReport({
111
- timeoutMs,
112
- elapsedMs,
113
- marker: info.marker,
114
- });
115
- summary = formatHangReportSummary(report);
116
- reportPath = writeHangReport(state.reportDir, report);
117
- } catch {
118
- summary = undefined;
119
- reportPath = undefined;
120
- }
121
- }
122
- const line = summary
123
- ? `[pi-toolkits/quit-guard] ${summary}${reportPath ? ` — report: ${reportPath}` : ""}; forcing exit.`
124
- : `[pi-toolkits/quit-guard] no exit ${elapsedMs}ms after the TUI teardown started (limit ${timeoutMs}ms); forcing exit.`;
125
- // stderr write is synchronous on POSIX; on failure the exit still happens.
126
- try {
127
- writeSync(2, `\n${line}\n`);
128
- } catch {
129
- // The terminal is gone or blocked; the report (if any) still exists.
130
- }
131
- // `process.exit(0)` is normally immediate, but every step of it is host
132
- // code: an `exit` listener (pi-tui's own `exitRestoreHandler`, the
133
- // graceful-fs patches bundled with the host, stdio flushing) can deadlock
134
- // it. Observed for real on 2026-11-13: the process sat in `futex_wait` for
135
- // 18 minutes after this line, its pty already deleted, because the
136
- // `setTimeout` SIGKILL below cannot fire while the main thread is blocked
137
- // *inside* `process.exit`. Three layers now guarantee the prompt comes
138
- // back: (1) `process.exit(0)`; (2) a same-loop SIGKILL timer for hangs
139
- // where the loop still turns; (3) the independent-thread SIGKILL from
140
- // killer.ts, which works even when the main thread never unblocks. The
141
- // report is already on disk and session entries are appended as they
142
- // happen, so nothing recoverable is lost.
143
- const hardKill = setTimeout(
144
- () => process.kill(process.pid, "SIGKILL"),
145
- HARD_KILL_DELAY_MS,
146
- );
147
- const cancelThreadKill = armThreadHardKill(HARD_KILL_DELAY_MS);
148
- try {
149
- process.exit(0);
150
- } catch {
151
- // Fall through to the hard kill.
152
- }
153
- clearTimeout(hardKill);
154
- cancelThreadKill();
155
- process.kill(process.pid, "SIGKILL");
156
- }
157
-
158
- function installProcessHooks(state: QuitGuardState): void {
159
- if (state.installed) return;
160
- state.installed = true;
161
-
162
- const originalWrite = process.stdout.write;
163
- // Capture the overload parameters once, then forward the exact same tuple:
164
- // no casts, and every `write(chunk)` / `write(chunk, cb)` / `write(chunk,
165
- // encoding, cb)` call site keeps working.
166
- const wrapped = (...args: Parameters<typeof process.stdout.write>): boolean => {
167
- try {
168
- state.guard.observeOutput(args[0]);
169
- } catch {
170
- // Never let observation break terminal output.
171
- }
172
- return originalWrite.apply(process.stdout, args);
173
- };
174
- // SAFETY: the forwarded tuple is exactly what the original function receives
175
- // (Node normalizes the (chunk, cb) form itself); the cast only restores
176
- // Writable.write's two overloads, which `Parameters<...>` collapses into one.
177
- process.stdout.write = wrapped as unknown as typeof process.stdout.write;
178
-
179
- // Ctrl+Z resume: `handleCtrlZ()` calls ui.stop() (teardown marker), then
180
- // SIGCONT calls ui.start() (restart marker). Both cancel; this listener
181
- // additionally disarms synchronously so an already-expired timer cannot
182
- // win the race against the resume. Windows cannot deliver SIGCONT at all.
183
- if (process.platform !== "win32") {
184
- process.on("SIGCONT", () => state.guard.resume());
185
- }
186
- }
187
-
188
- function latestReportName(dir: string): string | undefined {
189
- try {
190
- if (!existsSync(dir)) return undefined;
191
- const names = readdirSync(dir)
192
- .filter(
193
- (name) => name.startsWith("quit-hang-") && name.endsWith(".json"),
194
- )
195
- .sort();
196
- return names.length > 0 ? names[names.length - 1] : undefined;
197
- } catch {
198
- return undefined;
199
- }
200
- }
201
-
202
- function statusText(state: QuitGuardState): string {
203
- const config = state.config;
204
- const last = latestReportName(state.reportDir);
205
- const parts = [
206
- `quit guard: ${config.enabled ? "on" : "off"}`,
207
- `timeout ${config.timeoutMs}ms`,
208
- `report ${config.report ? "on" : "off"}`,
209
- `last hang: ${last ?? "none"}`,
210
- ];
211
- return parts.join(" · ");
212
- }
213
-
214
- function buildState(agentDir: string): QuitGuardState {
215
- const store = new QuitGuardStore(join(agentDir, QUIT_GUARD_FILE));
216
- const config = store.get();
217
- let state: QuitGuardState | undefined;
218
- // PI_QUIT_GUARD_DEBUG points at a file that receives one line per
219
- // arm/disarm/fire. It exists because the failure being debugged happens
220
- // after the TUI is gone: there is no other channel left to observe.
221
- const debugPath = process.env.PI_QUIT_GUARD_DEBUG;
222
- // Arm-time layer of the independent-thread kill: a main thread that
223
- // deadlocks synchronously (observed inside `process.exit` right after a
224
- // fast dispose) never runs the fire timer, so the guard needs a watcher
225
- // that does not live on the main event loop. The worker waits out the
226
- // deadline, then samples this heartbeat: a beating loop means the fire
227
- // timer owns the outcome (with its raw-mode probe and full report); a
228
- // stopped loop can only be ended by the worker. Disarmed/fired guards
229
- // cancel the worker — including every restart (mode switch, Ctrl+Z
230
- // resume, /reload) so a returning TUI is never killed.
231
- let watchdog: ThreadWatchdog | undefined;
232
- let heartbeatTimer: ReturnType<typeof setInterval> | undefined;
233
- const stopWatchdog = (): void => {
234
- if (heartbeatTimer !== undefined) {
235
- clearInterval(heartbeatTimer);
236
- heartbeatTimer = undefined;
237
- }
238
- watchdog?.cancel();
239
- watchdog = undefined;
240
- };
241
- const guard = new QuitGuard(config.timeoutMs, {
242
- onFire: (info) => {
243
- if (state) fire(state, info);
244
- },
245
- // Raw mode is the independent "TUI still running" signal; see guard.ts.
246
- isTuiActive: () => process.stdin.isRaw === true,
247
- onEvent: (event, detail) => {
248
- if (event === "arm") {
249
- watchdog = armThreadWatchdog({
250
- deadlineMs: guard.getTimeoutMs(),
251
- restore: TERMINAL_RESTORE,
252
- reportDir: join(agentDir, QUIT_GUARD_REPORT_DIR),
253
- debugPath,
254
- });
255
- watchdog.heartbeat();
256
- heartbeatTimer = setInterval(() => watchdog?.heartbeat(), 1_000);
257
- heartbeatTimer?.unref?.();
258
- } else if (event === "disarm" || event === "fire") {
259
- stopWatchdog();
260
- }
261
- if (debugPath) {
262
- try {
263
- appendFileSync(
264
- debugPath,
265
- `${new Date().toISOString()} ${event} ${detail}\n`,
266
- );
267
- } catch {
268
- // Debug output must never affect the guard.
269
- }
270
- }
271
- },
272
- });
273
- state = {
274
- store,
275
- guard,
276
- config,
277
- reportDir: join(agentDir, QUIT_GUARD_REPORT_DIR),
278
- installed: false,
279
- };
280
- return state;
281
- }
282
-
283
- export interface QuitGuardOptions {
284
- /** pi config directory; defaults to `getAgentDir()` (tests inject a temp dir). */
285
- readonly agentDir?: string;
286
- }
287
-
288
- export function registerQuitGuard(
289
- pi: ExtensionAPI,
290
- options: QuitGuardOptions = {},
291
- ): void {
292
- const agentDir = options.agentDir ?? getAgentDir();
293
- const state = sharedState() ?? buildState(agentDir);
294
- storeSharedState(state);
295
-
296
- // A reload rebuilds the extension instance: refresh settings from disk and
297
- // start unarmed. Any watchdog armed by the previous instance belonged to a
298
- // teardown that has already been replaced.
299
- state.store = new QuitGuardStore(join(agentDir, QUIT_GUARD_FILE));
300
- state.config = state.store.get();
301
- state.reportDir = join(agentDir, QUIT_GUARD_REPORT_DIR);
302
- state.guard.resume();
303
- state.guard.setEnabled(state.config.enabled);
304
- state.guard.setTimeoutMs(state.config.timeoutMs);
305
-
306
- installProcessHooks(state);
307
- if (process.env.PI_QUIT_GUARD_DEBUG) {
308
- try {
309
- appendFileSync(
310
- process.env.PI_QUIT_GUARD_DEBUG,
311
- `${new Date().toISOString()} register agentDir=${agentDir} enabled=${state.config.enabled} timeout=${state.config.timeoutMs}\n`,
312
- );
313
- } catch {
314
- // ignore
315
- }
316
- }
317
-
318
- // Second trigger: the process is quitting even though the TUI has not
319
- // written its teardown sequence yet. `reason === "quit"` is only emitted by
320
- // the runtime's dispose() on process exit; session replacements use
321
- // new/resume/fork and /reload uses reload, and none of those may arm.
322
- // The same event also fires for RPC/JSON/print shutdowns. Restrict this
323
- // trigger to the interactive TUI: terminal restoration must never inject
324
- // escape sequences into a machine-readable stdout protocol.
325
- pi.on("session_shutdown", (event, ctx) => {
326
- if (event.reason !== "quit" || ctx.mode !== "tui") return;
327
- state.guard.armFromShutdown();
328
- });
329
-
330
- pi.registerCommand("quit-guard", {
331
- description:
332
- "Quit watchdog: force-exit when pi's shutdown hangs (/quit-guard [on|off|<timeoutMs>])",
333
- handler: async (args: string, ctx: ExtensionCommandContext) => {
334
- const raw = args.trim();
335
- if (raw.length === 0) {
336
- ctx.ui.notify(statusText(state), "info");
337
- return;
338
- }
339
- const token = raw.toLowerCase();
340
- if (token === "on" || token === "off") {
341
- const enabled = token === "on";
342
- state.config = state.store.update({ enabled });
343
- state.guard.setEnabled(enabled);
344
- ctx.ui.notify(
345
- enabled
346
- ? `quit guard ON — force exits ${state.config.timeoutMs}ms after a stuck shutdown.`
347
- : "quit guard OFF — a stuck shutdown will keep hanging until kill -9.",
348
- "info",
349
- );
350
- return;
351
- }
352
- if (/^[0-9]+$/.test(token)) {
353
- const timeoutMs = normalizeTimeoutMs(Number(token));
354
- state.config = state.store.update({ timeoutMs });
355
- state.guard.setTimeoutMs(timeoutMs);
356
- ctx.ui.notify(
357
- `quit guard timeout ${timeoutMs}ms (allowed range ${MIN_TIMEOUT_MS}–${MAX_TIMEOUT_MS}ms).`,
358
- "info",
359
- );
360
- return;
361
- }
362
- ctx.ui.notify(
363
- "Usage: /quit-guard (status) | /quit-guard on|off | /quit-guard <timeoutMs>",
364
- "error",
365
- );
366
- },
367
- });
368
- }
@@ -1,77 +0,0 @@
1
- /**
2
- * Unit tests for the independent-thread hard kill (killer.ts).
3
- *
4
- * What these tests deliberately do NOT cover: the worker actually SIGKILLing
5
- * the process. A test that kills its own process cannot report results; the
6
- * kill path is verified in real-pi smoke runs (an extension whose
7
- * `process.on("exit")` listener deadlocks, /quit, and the pane returning to
8
- * the shell — see .agents/implementations/2026-11-13). Here we pin the
9
- * safety property instead: an armed kill that gets cancelled, or whose
10
- * process simply keeps living, must never fire on its own or break the
11
- * caller.
12
- */
13
- import { describe, expect, it } from "vitest";
14
- import { armThreadHardKill, armThreadWatchdog } from "./killer.js";
15
-
16
- function sleep(ms: number): Promise<void> {
17
- return new Promise((resolve) => {
18
- setTimeout(resolve, ms);
19
- });
20
- }
21
-
22
- describe("armThreadWatchdog", () => {
23
- it("never kills while the main loop keeps beating (deadline passes, loop alive)", async () => {
24
- // A tiny deadline so the worker's sampling phases run within the test;
25
- // the heartbeat below proves a live loop, which the worker must step
26
- // aside for — the main-loop fire timer owns the outcome there.
27
- const watchdog = armThreadWatchdog({
28
- deadlineMs: 100,
29
- headStartMs: 50,
30
- sampleMs: 100,
31
- restore: "",
32
- reportDir: undefined,
33
- });
34
- const beat = setInterval(() => watchdog.heartbeat(), 50);
35
- // Long past deadline + head start + sampling: the runner surviving is
36
- // the assertion.
37
- await sleep(700);
38
- clearInterval(beat);
39
- watchdog.cancel();
40
- expect(process.pid).toBeGreaterThan(0);
41
- });
42
-
43
- it("is inert once cancelled, even with the deadline long past", async () => {
44
- const watchdog = armThreadWatchdog({
45
- deadlineMs: 50,
46
- headStartMs: 25,
47
- sampleMs: 50,
48
- restore: "",
49
- reportDir: undefined,
50
- });
51
- // No heartbeat at all: only the cancellation keeps this process alive,
52
- // which is exactly the disarm contract (TUI restarted, /reload, ...).
53
- watchdog.cancel();
54
- watchdog.cancel();
55
- await sleep(400);
56
- expect(process.pid).toBeGreaterThan(0);
57
- });
58
- });
59
-
60
- describe("armThreadHardKill", () => {
61
- it("does not kill the process before its deadline passes", async () => {
62
- const cancel = armThreadHardKill(60_000);
63
- // Long enough for the worker thread to spin up, wait, and be bored;
64
- // the test runner surviving this line IS the assertion.
65
- await sleep(300);
66
- expect(process.pid).toBeGreaterThan(0);
67
- cancel();
68
- });
69
-
70
- it("tolerates being cancelled twice", async () => {
71
- const cancel = armThreadHardKill(60_000);
72
- cancel();
73
- cancel();
74
- await sleep(100);
75
- expect(process.pid).toBeGreaterThan(0);
76
- });
77
- });
@@ -1,215 +0,0 @@
1
- /**
2
- * quit-guard feature — independent-thread hard kill.
3
- *
4
- * Why this exists (2026-11-13, real hang, pid 398960): the guard fired,
5
- * wrote its report, printed "forcing exit" and called `process.exit(0)` —
6
- * and the process stayed alive for 18+ minutes (`futex_wait`, PPID=1, its
7
- * pty already deleted by the user closing the terminal window). The exit
8
- * path runs host code (`process.on("exit")` listeners, graceful-fs patches,
9
- * stdio flush) and can deadlock synchronously. Any fallback scheduled on
10
- * the event loop (`setTimeout`) is dead the moment the main thread blocks:
11
- * a timer cannot fire inside a dead loop.
12
- *
13
- * Two watchdogs, both on `worker_threads` (an independent OS thread that
14
- * keeps running while the main thread is blocked):
15
- *
16
- * 1. `armThreadHardKill(delayMs)` — the last-resort layer of fire(): after
17
- * the report is on disk and "forcing exit" has been printed, kill the
18
- * process `delayMs` later no matter what `process.exit(0)` did.
19
- *
20
- * 2. `armThreadWatchdog({ deadlineMs, ... })` — armed when the guard arms
21
- * (teardown marker / shutdown event), covering the blind spot the
22
- * main-loop timer has: a main thread that deadlocks BEFORE the fire
23
- * deadline (e.g. synchronously inside `process.exit` right after a fast
24
- * dispose) never runs the fire timer at all. The main loop must prove
25
- * liveness with a heartbeat (a 1 Hz counter in shared memory). The
26
- * worker waits out `deadlineMs` (+ a head start for the main-loop fire
27
- * timer, which handles the common hangs with full context: raw-mode
28
- * probe, report, restore), then samples the heartbeat twice. Still
29
- * beating → the event loop is alive → step aside (the fire timer owns
30
- * the outcome, including its stray-marker protection). Stopped → the
31
- * main loop can never fire → the worker restores the terminal, writes a
32
- * minimal report and SIGKILLs. This kills exactly-and-only a main
33
- * thread that is alive as a process but dead as an event loop.
34
- *
35
- * Failure policy: if a Worker cannot even be constructed, degrade to a
36
- * no-op — the fire path still has its `setTimeout` fallback, and a killer
37
- * that breaks the arm/fire sequence is worse than no extra killer.
38
- */
39
- import { Worker } from "node:worker_threads";
40
-
41
- /**
42
- * Start a watchdog thread that SIGKILLs this process after `delayMs`.
43
- *
44
- * Returns a `cancel()` that terminates the worker. Cancelling only matters
45
- * on the "process.exit threw synchronously" path, where fire() recovers and
46
- * performs its own synchronous kill; on every healthy path the process dies
47
- * with the main thread and the worker is never heard from again.
48
- */
49
- export function armThreadHardKill(delayMs: number): () => void {
50
- let worker: Worker;
51
- try {
52
- worker = new Worker(
53
- `Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ${Math.max(
54
- 0,
55
- delayMs,
56
- )});
57
- process.kill(process.pid, "SIGKILL");`,
58
- { eval: true },
59
- );
60
- } catch {
61
- // Could not start the watchdog thread (resource exhaustion, ...):
62
- // degrade to the setTimeout fallback instead of breaking the fire path.
63
- return () => {};
64
- }
65
- // The worker must never keep the process alive on its own: its only job
66
- // is to end it.
67
- worker.unref();
68
- return () => {
69
- try {
70
- void worker.terminate();
71
- } catch {
72
- // terminate() returns a promise that can only reject if the worker
73
- // is already gone; either way this process is about to exit.
74
- }
75
- };
76
- }
77
-
78
- /** Handle returned by {@link armThreadWatchdog}. */
79
- export interface ThreadWatchdog {
80
- /** Record one main-loop heartbeat tick (idempotent per tick). */
81
- heartbeat(): void;
82
- /** Disarm: the main loop owns the outcome from here on. */
83
- cancel(): void;
84
- }
85
-
86
- export interface ThreadWatchdogOptions {
87
- /** Guard deadline (ms) the main-loop fire timer is armed with. */
88
- readonly deadlineMs: number;
89
- /**
90
- * Grace after the deadline before the first heartbeat sample (ms), so
91
- * the main-loop fire timer — which handles hangs with full context —
92
- * always gets the first shot.
93
- */
94
- readonly headStartMs?: number;
95
- /** Gap between the two heartbeat samples (ms). Default 1500. */
96
- readonly sampleMs?: number;
97
- /** Terminal restore written before the watchdog's kill. */
98
- readonly restore?: string;
99
- /** Directory for the minimal deadlock report; omit to skip the report. */
100
- readonly reportDir?: string;
101
- /** PI_QUIT_GUARD_DEBUG path, appended to from the worker on a kill. */
102
- readonly debugPath?: string;
103
- }
104
-
105
- /**
106
- * Cells of the shared heartbeat buffer: [0] = heartbeat ticks (written by
107
- * the main loop, never waited on), [1] = signal (0 = armed, 1 = cancelled;
108
- * the only cell the worker waits on — Atomics.wait's third argument is the
109
- * EXPECTED value, so waiting on the heartbeat cell, which changes on every
110
- * tick, would return "not-equal" immediately and fake a deadlock).
111
- */
112
- const CELL_HEARTBEAT = 0;
113
- const CELL_SIGNAL = 1;
114
-
115
- const WATCHDOG_SOURCE = `
116
- (function () {
117
- const { workerData } = require("node:worker_threads");
118
- const { writeSync, writeFileSync, mkdirSync, appendFileSync } = require("node:fs");
119
- const cells = workerData.cells;
120
- const cancelFlag = () => Atomics.load(cells, ${CELL_SIGNAL}) === 1;
121
- // Phase 1: wait out the deadline plus the main-loop timer's head start.
122
- Atomics.wait(cells, ${CELL_SIGNAL}, 0, workerData.deadlineMs + workerData.headStartMs);
123
- if (cancelFlag()) return;
124
- // Phase 2: sample the heartbeat twice. A loop that is merely slow still
125
- // ticks; a loop that is blocked cannot.
126
- const first = Atomics.load(cells, ${CELL_HEARTBEAT});
127
- Atomics.wait(cells, ${CELL_SIGNAL}, 0, workerData.sampleMs);
128
- if (cancelFlag()) return;
129
- if (Atomics.load(cells, ${CELL_HEARTBEAT}) !== first) return;
130
- // Phase 3: deadlocked. Restore the terminal, leave a minimal trace, kill.
131
- try { writeSync(1, workerData.restore); } catch {}
132
- try {
133
- mkdirSync(workerData.reportDir, { recursive: true });
134
- const ts = new Date().toISOString().replace(/[:.]/g, "-");
135
- writeFileSync(
136
- workerData.reportDir + "/quit-hang-" + ts + "-" + process.pid + "-thread.json",
137
- JSON.stringify(
138
- {
139
- version: 1,
140
- kind: "quit-guard",
141
- source: "thread-watchdog",
142
- timestamp: new Date().toISOString(),
143
- pid: process.pid,
144
- timeoutMs: workerData.deadlineMs,
145
- elapsedMs: workerData.deadlineMs + workerData.headStartMs + workerData.sampleMs,
146
- marker: "heartbeat-stopped",
147
- note: "main event loop stopped beating during shutdown; killed from the watchdog thread (main-loop fire timer could never run)",
148
- },
149
- null,
150
- "\\t",
151
- ) + "\\n",
152
- );
153
- } catch {}
154
- try {
155
- writeSync(2, "[pi-toolkits/quit-guard] main loop stopped during shutdown (no heartbeat for " + workerData.sampleMs + "ms after the " + (workerData.deadlineMs + workerData.headStartMs) + "ms deadline); killing from the watchdog thread.\\n");
156
- } catch {}
157
- try {
158
- if (workerData.debugPath) appendFileSync(workerData.debugPath, new Date().toISOString() + " thread-kill heartbeat-stopped deadline=" + workerData.deadlineMs + "\\n");
159
- } catch {}
160
- process.kill(process.pid, "SIGKILL");
161
- })();
162
- `;
163
-
164
- /**
165
- * Arm the arm-time watchdog. See the module comment for the protocol.
166
- *
167
- * The returned handle is deliberately passive: an owner that forgets to
168
- * cancel merely keeps one unref'd worker alive for the rest of the process
169
- * — which the deadline then ends (heartbeat still beating → the worker
170
- * steps aside; heartbeat stopped → the process was dead anyway).
171
- */
172
- export function armThreadWatchdog(
173
- options: ThreadWatchdogOptions,
174
- ): ThreadWatchdog {
175
- const cells = new Int32Array(new SharedArrayBuffer(8));
176
- let worker: Worker;
177
- try {
178
- worker = new Worker(WATCHDOG_SOURCE, {
179
- eval: true,
180
- workerData: {
181
- cells,
182
- deadlineMs: Math.max(0, options.deadlineMs),
183
- headStartMs: Math.max(0, options.headStartMs ?? 500),
184
- sampleMs: Math.max(0, options.sampleMs ?? 1_500),
185
- restore: options.restore ?? "",
186
- reportDir: options.reportDir ?? "",
187
- debugPath: options.debugPath ?? "",
188
- },
189
- });
190
- } catch {
191
- // No watchdog thread: the guard degrades to its main-loop timer,
192
- // exactly the behavior that existed before this layer.
193
- return { heartbeat: () => {}, cancel: () => {} };
194
- }
195
- worker.unref();
196
- let beats = 0;
197
- return {
198
- heartbeat: () => {
199
- Atomics.store(cells, CELL_HEARTBEAT, ++beats);
200
- },
201
- cancel: () => {
202
- // Flag first so a worker whose terminate() has not landed yet
203
- // stops at its next check; notify so it wakes now (the signal cell
204
- // is the only one the worker waits on); terminate so the thread
205
- // goes away even mid-phase-1.
206
- Atomics.store(cells, CELL_SIGNAL, 1);
207
- Atomics.notify(cells, CELL_SIGNAL);
208
- try {
209
- void worker.terminate();
210
- } catch {
211
- // Already gone.
212
- }
213
- },
214
- };
215
- }