@andares/pi-toolkits 1.2.1 → 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.
- package/CHANGELOG.md +8 -0
- package/README.md +2 -113
- package/README.zh-CN.md +2 -48
- package/package.json +2 -4
- package/src/index.ts +0 -3
- package/src/lib/approval-log.ts +3 -3
- package/src/features/quit-guard/constants.ts +0 -98
- package/src/features/quit-guard/guard.ts +0 -235
- package/src/features/quit-guard/index.ts +0 -368
- package/src/features/quit-guard/killer.test.ts +0 -77
- package/src/features/quit-guard/killer.ts +0 -215
- package/src/features/quit-guard/quit-guard.test.ts +0 -853
- package/src/features/quit-guard/report.ts +0 -212
- package/src/features/quit-guard/store.ts +0 -144
|
@@ -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
|
-
}
|
|
@@ -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
|
-
});
|