@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.
@@ -1,212 +0,0 @@
1
- /**
2
- * quit-guard feature — hang artifact.
3
- *
4
- * When the watchdog fires, extension cleanup was cut short. The artifact is
5
- * the only evidence of what the process was waiting on, so it is written
6
- * synchronously *before* `process.exit(0)` and never throws: a failed report
7
- * must not keep the user from getting the prompt back.
8
- *
9
- * Contents: the arm/fire timing, the process state (`activeHandles` /
10
- * `activeRequests` class names from Node's undocumented introspection helpers),
11
- * and the host's own libuv handle table (`process.report.getReport().libuv`).
12
- * Together they are enough to tell "waiting on a socket" from "waiting on a
13
- * thin promise that nobody will ever resolve" — the latter shows up as an
14
- * empty handle table with pi's extension-shutdown frames missing.
15
- *
16
- * Privacy: `argv` and `cwd` are process facts, not conversation data, but they
17
- * are still credential-adjacent (`pi --api-key …`, a prompt passed as an
18
- * argument, a path under a private tree). The file is therefore owner-only
19
- * (0600 in an 0700 directory, matching the approval log) and every argument
20
- * goes through the same redaction rules the approval log uses.
21
- */
22
- import { mkdirSync, writeFileSync } from "node:fs";
23
- import { join } from "node:path";
24
- import { redactText } from "../../lib/approval-log.js";
25
-
26
- export interface HangReport {
27
- version: 1;
28
- kind: "quit-guard";
29
- /** ISO timestamp of the forced exit. */
30
- timestamp: string;
31
- pid: number;
32
- /** Watchdog deadline that was configured at arm time. */
33
- timeoutMs: number;
34
- /** Time actually spent inside the shutdown phase. */
35
- elapsedMs: number;
36
- /** The teardown sequence that armed the guard. */
37
- marker: string;
38
- uptimeSeconds: number;
39
- cwd: string;
40
- /** Process arguments, redacted (see the privacy note above). */
41
- argv: string[];
42
- /** Constructor names of handles keeping the event loop alive. */
43
- activeHandles: string[];
44
- /** Node's pending-request list (fs, dns, zlib, ... callbacks). */
45
- activeRequests: string[];
46
- /**
47
- * Host libuv handle table (trimmed). Empty but non-null means "nothing is
48
- * pending that the OS knows about": the process is parked on a promise.
49
- */
50
- libuv: unknown[];
51
- }
52
-
53
- interface ProcessIntrospection {
54
- _getActiveHandles?: () => unknown[];
55
- _getActiveRequests?: () => unknown[];
56
- report?: { getReport?: () => { libuv?: unknown[] } };
57
- }
58
-
59
- export interface HangReportInput {
60
- timeoutMs: number;
61
- elapsedMs: number;
62
- marker: string;
63
- }
64
-
65
- export interface HangReportOptions {
66
- now?: () => Date;
67
- pid?: number;
68
- cwd?: string;
69
- argv?: string[];
70
- }
71
-
72
- /** Stand-in for `process.cwd()` when the working directory no longer exists. */
73
- const UNKNOWN_CWD = "<unknown: working directory unavailable>";
74
-
75
- /**
76
- * Flags whose *next* argument is a credential. `--api-key` with a bare opaque
77
- * token is the common shape and matches none of the value-prefix rules, so the
78
- * pair has to be recognised positionally.
79
- */
80
- const SECRET_ARG =
81
- /^--?(?:api[-_]?key|key|token|access[-_]?token|refresh[-_]?token|auth[-_]?token|secret|client[-_]?secret|password|passwd)$/i;
82
-
83
- /** Redact one argument list: flag/value pairs first, then the value patterns. */
84
- export function redactArgv(argv: readonly string[]): string[] {
85
- let hideNext = false;
86
- return argv.map((arg) => {
87
- if (hideNext) {
88
- hideNext = false;
89
- return "[redacted]";
90
- }
91
- if (SECRET_ARG.test(arg)) {
92
- hideNext = true;
93
- return arg;
94
- }
95
- const pair = /^(--?[^=]+)=(.+)$/.exec(arg);
96
- if (pair && SECRET_ARG.test(pair[1] ?? "")) {
97
- return `${pair[1]}=[redacted]`;
98
- }
99
- return redactText(arg);
100
- });
101
- }
102
-
103
- /** Owner-only modes; the file is credential-adjacent, like the approval log. */
104
- const REPORT_DIR_MODE = 0o700;
105
- const REPORT_FILE_MODE = 0o600;
106
-
107
- /** Read a process fact without letting it abort the report. */
108
- function attempt<T>(read: () => T, fallback: T): T {
109
- try {
110
- return read();
111
- } catch {
112
- // Every field here is diagnostics; a missing one is better than no report.
113
- return fallback;
114
- }
115
- }
116
-
117
- function constructorNames(list: unknown[] | undefined): string[] {
118
- if (!Array.isArray(list)) return [];
119
- const names = new Set<string>();
120
- for (const item of list) {
121
- const name =
122
- item && typeof item === "object" && "constructor" in item
123
- ? (item.constructor as { name?: string })?.name
124
- : undefined;
125
- names.add(
126
- typeof name === "string" && name.length > 0
127
- ? name
128
- : typeof item === "undefined"
129
- ? "undefined"
130
- : String(typeof item),
131
- );
132
- }
133
- return [...names].sort((a, b) => a.localeCompare(b));
134
- }
135
-
136
- /** Show this to whoever has to debug the hang: one line, no prefixes. */
137
- export function formatHangReportSummary(report: HangReport): string {
138
- const handles =
139
- report.activeHandles.length > 0
140
- ? report.activeHandles.join(", ")
141
- : "none";
142
- const cwd = report.cwd === UNKNOWN_CWD ? " (cwd unavailable)" : "";
143
- return `shutdown exceeded ${report.timeoutMs}ms (spent ${report.elapsedMs}ms); handles: ${handles}${cwd}`;
144
- }
145
-
146
- export function collectHangReport(
147
- input: HangReportInput,
148
- options: HangReportOptions = {},
149
- ): HangReport {
150
- // SAFETY: `_getActiveHandles`, `_getActiveRequests`, and `report.getReport`
151
- // exist on Node's process object but are missing from (or narrower in)
152
- // @types/node. `ProcessIntrospection` declares them as optional, so every
153
- // use below is guarded and nothing is called unconditionally.
154
- const proc = process as unknown as ProcessIntrospection & NodeJS.Process;
155
- const now = options.now ?? (() => new Date());
156
- const libuv = attempt(() => {
157
- const raw = proc.report?.getReport?.();
158
- return raw && Array.isArray(raw.libuv) ? raw.libuv.slice(0, 200) : [];
159
- }, [] as unknown[]);
160
- return {
161
- version: 1,
162
- kind: "quit-guard",
163
- timestamp: now().toISOString(),
164
- pid: options.pid ?? proc.pid,
165
- timeoutMs: input.timeoutMs,
166
- elapsedMs: Math.round(input.elapsedMs),
167
- marker: input.marker,
168
- uptimeSeconds: attempt(() => Math.round(proc.uptime()), 0),
169
- // `process.cwd()` throws ENOENT when the directory was removed during
170
- // the session (a startup crash pi itself guards against in 1.5.1). The
171
- // report is written on the exit path, so it must survive that.
172
- cwd: options.cwd ?? attempt(() => proc.cwd(), UNKNOWN_CWD),
173
- argv: attempt(
174
- () => redactArgv(options.argv ?? [...proc.argv]),
175
- [],
176
- ),
177
- activeHandles: constructorNames(
178
- attempt(() => proc._getActiveHandles?.(), [] as unknown[]),
179
- ),
180
- activeRequests: constructorNames(
181
- attempt(() => proc._getActiveRequests?.(), [] as unknown[]),
182
- ),
183
- libuv,
184
- };
185
- }
186
-
187
- /**
188
- * Write the report under `dir`. Returns the path, or `undefined` when the
189
- * filesystem rejected it (read-only home, missing permissions, ...).
190
- */
191
- export function writeHangReport(
192
- dir: string,
193
- report: HangReport,
194
- ): string | undefined {
195
- try {
196
- mkdirSync(dir, { recursive: true, mode: REPORT_DIR_MODE });
197
- const stamp = report.timestamp.replace(/[:.]/g, "-");
198
- const file = join(dir, `quit-hang-${stamp}-${report.pid}.json`);
199
- writeFileSync(file, `${JSON.stringify(report, null, 2)}\n`, {
200
- encoding: "utf8",
201
- mode: REPORT_FILE_MODE,
202
- });
203
- return file;
204
- } catch (error) {
205
- // pi-lens-ignore: no-console-except-error,console-statement, — deliberate degradation log
206
- console.warn(
207
- "[pi-toolkits/quit-guard] Failed to write hang report:",
208
- error instanceof Error ? error.message : String(error),
209
- );
210
- return undefined;
211
- }
212
- }
@@ -1,144 +0,0 @@
1
- /**
2
- * quit-guard feature — persisted settings store.
3
- *
4
- * State lives in `<agent-dir>/pi-toolkits-quit-guard.json` (agent-dir from
5
- * getAgentDir(), same convention as the favorites/compact/review stores).
6
- *
7
- * File shape:
8
- * {
9
- * "enabled": true,
10
- * "timeoutMs": 8000,
11
- * "report": true
12
- * }
13
- *
14
- * `enabled` (default true) gates the whole watchdog; `timeoutMs` is clamped
15
- * to [MIN_TIMEOUT_MS, MAX_TIMEOUT_MS]; `report` (default true) writes a JSON
16
- * artifact under `<agent-dir>/quit-guard/` every time the guard fires.
17
- *
18
- * Robustness: a missing file means defaults (and is created on first save),
19
- * corrupted/unreadable files fall back to defaults with a console.warn, and
20
- * writes are atomic (tmp + rename) and never throw.
21
- */
22
- import {
23
- existsSync,
24
- mkdirSync,
25
- readFileSync,
26
- renameSync,
27
- writeFileSync,
28
- } from "node:fs";
29
- import { dirname, join } from "node:path";
30
- import { getAgentDir } from "@earendil-works/pi-coding-agent";
31
- import {
32
- DEFAULT_TIMEOUT_MS,
33
- MAX_TIMEOUT_MS,
34
- MIN_TIMEOUT_MS,
35
- QUIT_GUARD_FILE,
36
- } from "./constants.js";
37
-
38
- export interface QuitGuardConfig {
39
- /** Master switch. When false the guard never arms. */
40
- enabled: boolean;
41
- /** Milliseconds allowed between the terminal teardown write and exit. */
42
- timeoutMs: number;
43
- /** Write a JSON hang report before forcing exit. */
44
- report: boolean;
45
- }
46
-
47
- export const DEFAULT_CONFIG: QuitGuardConfig = {
48
- enabled: true,
49
- timeoutMs: DEFAULT_TIMEOUT_MS,
50
- report: true,
51
- };
52
-
53
- /** Clamp/round a timeout into the supported range; non-numbers fall back. */
54
- export function normalizeTimeoutMs(value: unknown): number {
55
- if (typeof value !== "number" || !Number.isFinite(value)) {
56
- return DEFAULT_TIMEOUT_MS;
57
- }
58
- const rounded = Math.round(value);
59
- if (rounded <= MIN_TIMEOUT_MS) return MIN_TIMEOUT_MS;
60
- if (rounded >= MAX_TIMEOUT_MS) return MAX_TIMEOUT_MS;
61
- return rounded;
62
- }
63
-
64
- /** Coerce an unknown JSON blob into a complete config (defaults for gaps). */
65
- export function normalizeConfig(input: unknown): QuitGuardConfig {
66
- const config: QuitGuardConfig = { ...DEFAULT_CONFIG };
67
- if (!input || typeof input !== "object") return config;
68
- const raw = input as Partial<QuitGuardConfig>;
69
- if (typeof raw.enabled === "boolean") config.enabled = raw.enabled;
70
- if (typeof raw.report === "boolean") config.report = raw.report;
71
- if (raw.timeoutMs !== undefined) {
72
- config.timeoutMs = normalizeTimeoutMs(raw.timeoutMs);
73
- }
74
- return config;
75
- }
76
-
77
- export class QuitGuardStore {
78
- private config: QuitGuardConfig = { ...DEFAULT_CONFIG };
79
- private readonly file: string;
80
- private loaded = false;
81
-
82
- constructor(file: string = join(getAgentDir(), QUIT_GUARD_FILE)) {
83
- this.file = file;
84
- }
85
-
86
- /** Path of the JSON file (also used to derive the report directory). */
87
- get path(): string {
88
- return this.file;
89
- }
90
-
91
- private ensureLoaded(): void {
92
- if (this.loaded) return;
93
- this.loaded = true;
94
- try {
95
- if (!existsSync(this.file)) return;
96
- const parsed: unknown = JSON.parse(readFileSync(this.file, "utf8"));
97
- this.config = normalizeConfig(parsed);
98
- } catch (error) {
99
- // pi-lens-ignore: no-console-except-error,console-statement, — deliberate degradation log
100
- console.warn(
101
- "[pi-toolkits/quit-guard] Failed to load settings, using defaults:",
102
- error instanceof Error ? error.message : String(error),
103
- );
104
- this.config = { ...DEFAULT_CONFIG };
105
- }
106
- }
107
-
108
- /** Current settings (a copy). */
109
- get(): QuitGuardConfig {
110
- this.ensureLoaded();
111
- return { ...this.config };
112
- }
113
-
114
- /** Merge a patch, normalize it, persist, and return the new settings. */
115
- update(patch: Partial<QuitGuardConfig>): QuitGuardConfig {
116
- this.ensureLoaded();
117
- this.config = normalizeConfig({ ...this.config, ...patch });
118
- this.save();
119
- return { ...this.config };
120
- }
121
-
122
- /** Atomically persist (tmp + rename). Never throws. */
123
- save(): void {
124
- try {
125
- const dir = dirname(this.file);
126
- if (!existsSync(dir)) {
127
- mkdirSync(dir, { recursive: true });
128
- }
129
- const tmp = `${this.file}.tmp`;
130
- writeFileSync(
131
- tmp,
132
- `${JSON.stringify(this.config, null, 2)}\n`,
133
- "utf8",
134
- );
135
- renameSync(tmp, this.file);
136
- } catch (error) {
137
- // pi-lens-ignore: no-console-except-error,console-statement, — deliberate degradation log
138
- console.warn(
139
- "[pi-toolkits/quit-guard] Failed to save settings:",
140
- error instanceof Error ? error.message : String(error),
141
- );
142
- }
143
- }
144
- }