@blackbelt-technology/pi-dashboard-extension 0.3.0
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/.pi/skills/pi-dashboard/SKILL.md +134 -0
- package/.pi/skills/pi-dashboard/references/api-reference.md +470 -0
- package/.pi/skills/pi-dashboard/references/recipes.md +252 -0
- package/.pi/skills/pi-dashboard/scripts/dashboard-api.sh +75 -0
- package/package.json +38 -0
- package/src/__tests__/ask-user-tool.test.ts +432 -0
- package/src/__tests__/command-handler.test.ts +712 -0
- package/src/__tests__/connection.test.ts +344 -0
- package/src/__tests__/credentials-updated.test.ts +26 -0
- package/src/__tests__/dashboard-default-adapter.test.ts +77 -0
- package/src/__tests__/dev-build.test.ts +79 -0
- package/src/__tests__/enrich-model-metadata.test.ts +201 -0
- package/src/__tests__/event-forwarder.test.ts +89 -0
- package/src/__tests__/fork-entryid-timing.test.ts +100 -0
- package/src/__tests__/git-info.test.ts +124 -0
- package/src/__tests__/git-link-builder.test.ts +102 -0
- package/src/__tests__/openspec-activity-detector.test.ts +232 -0
- package/src/__tests__/openspec-poller.test.ts +124 -0
- package/src/__tests__/process-metrics.test.ts +47 -0
- package/src/__tests__/process-scanner-kill.test.ts +61 -0
- package/src/__tests__/process-scanner.test.ts +202 -0
- package/src/__tests__/prompt-bus-wiring.test.ts +791 -0
- package/src/__tests__/prompt-bus.test.ts +469 -0
- package/src/__tests__/prompt-expander.test.ts +54 -0
- package/src/__tests__/provider-register-reload.test.ts +394 -0
- package/src/__tests__/server-auto-start.test.ts +258 -0
- package/src/__tests__/server-launcher.test.ts +61 -0
- package/src/__tests__/server-probe.test.ts +25 -0
- package/src/__tests__/session-switch.test.ts +139 -0
- package/src/__tests__/session-sync.test.ts +55 -0
- package/src/__tests__/source-detector.test.ts +73 -0
- package/src/__tests__/stats-extractor.test.ts +92 -0
- package/src/__tests__/tui-prompt-adapter.test.ts +207 -0
- package/src/__tests__/watchdog.test.ts +161 -0
- package/src/ask-user-tool.ts +352 -0
- package/src/bridge-context.ts +64 -0
- package/src/bridge.ts +1182 -0
- package/src/command-handler.ts +533 -0
- package/src/connection.ts +204 -0
- package/src/dashboard-default-adapter.ts +37 -0
- package/src/dev-build.ts +39 -0
- package/src/event-forwarder.ts +40 -0
- package/src/flow-event-wiring.ts +85 -0
- package/src/git-info.ts +55 -0
- package/src/git-link-builder.ts +112 -0
- package/src/model-tracker.ts +56 -0
- package/src/pi-env.d.ts +37 -0
- package/src/process-metrics.ts +70 -0
- package/src/process-scanner.ts +430 -0
- package/src/prompt-bus.ts +240 -0
- package/src/prompt-expander.ts +108 -0
- package/src/provider-register.ts +564 -0
- package/src/server-auto-start.ts +113 -0
- package/src/server-launcher.ts +126 -0
- package/src/server-probe.ts +33 -0
- package/src/session-sync.ts +155 -0
- package/src/source-detector.ts +26 -0
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lightweight process metrics collector for bridge heartbeats.
|
|
3
|
+
* Uses Node.js built-in APIs — no external dependencies.
|
|
4
|
+
*/
|
|
5
|
+
import os from "node:os";
|
|
6
|
+
import { monitorEventLoopDelay, type IntervalHistogram } from "node:perf_hooks";
|
|
7
|
+
import type { ProcessMetrics } from "@blackbelt-technology/pi-dashboard-shared/protocol.js";
|
|
8
|
+
|
|
9
|
+
const ELD_RESOLUTION_MS = 20;
|
|
10
|
+
|
|
11
|
+
let lastCpuUsage: NodeJS.CpuUsage | undefined;
|
|
12
|
+
let lastCpuTime: number | undefined;
|
|
13
|
+
let eld: IntervalHistogram | undefined;
|
|
14
|
+
|
|
15
|
+
/** Start event loop delay monitoring. Call once at init. */
|
|
16
|
+
export function startMetricsMonitor(): void {
|
|
17
|
+
if (eld) return; // already started
|
|
18
|
+
try {
|
|
19
|
+
eld = monitorEventLoopDelay({ resolution: ELD_RESOLUTION_MS });
|
|
20
|
+
eld.enable();
|
|
21
|
+
} catch {
|
|
22
|
+
// monitorEventLoopDelay not available in older Node versions
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Stop event loop delay monitoring. */
|
|
27
|
+
export function stopMetricsMonitor(): void {
|
|
28
|
+
if (eld) {
|
|
29
|
+
eld.disable();
|
|
30
|
+
eld = undefined;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Collect current process metrics and reset deltas. */
|
|
35
|
+
export function collectMetrics(): ProcessMetrics {
|
|
36
|
+
const mem = process.memoryUsage();
|
|
37
|
+
|
|
38
|
+
// CPU percent since last call
|
|
39
|
+
const now = Date.now();
|
|
40
|
+
const cpuNow = process.cpuUsage();
|
|
41
|
+
let cpuPercent = 0;
|
|
42
|
+
if (lastCpuUsage && lastCpuTime) {
|
|
43
|
+
const elapsedMs = now - lastCpuTime;
|
|
44
|
+
if (elapsedMs > 0) {
|
|
45
|
+
const userDelta = cpuNow.user - lastCpuUsage.user; // microseconds
|
|
46
|
+
const systemDelta = cpuNow.system - lastCpuUsage.system;
|
|
47
|
+
// Total CPU microseconds / elapsed wall-clock microseconds * 100
|
|
48
|
+
cpuPercent = ((userDelta + systemDelta) / (elapsedMs * 1000)) * 100;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
lastCpuUsage = cpuNow;
|
|
52
|
+
lastCpuTime = now;
|
|
53
|
+
|
|
54
|
+
// Event loop max delay since last reset
|
|
55
|
+
let eventLoopMaxMs: number | undefined;
|
|
56
|
+
if (eld) {
|
|
57
|
+
// max is in nanoseconds
|
|
58
|
+
eventLoopMaxMs = Math.round(eld.max / 1_000_000);
|
|
59
|
+
eld.reset();
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
return {
|
|
63
|
+
rss: mem.rss,
|
|
64
|
+
heapUsed: mem.heapUsed,
|
|
65
|
+
heapTotal: mem.heapTotal,
|
|
66
|
+
cpuPercent: Math.round(cpuPercent * 10) / 10,
|
|
67
|
+
eventLoopMaxMs,
|
|
68
|
+
loadAvg1m: Math.round(os.loadavg()[0] * 100) / 100,
|
|
69
|
+
};
|
|
70
|
+
}
|
|
@@ -0,0 +1,430 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Process scanner for detecting child processes of a pi session.
|
|
3
|
+
* Supports Unix (macOS + Linux) via ps/PGID and Windows via wmic/tasklist.
|
|
4
|
+
*
|
|
5
|
+
* Two-phase approach (Unix):
|
|
6
|
+
* 1. CAPTURE: During active bash tool calls, `ps -eo pid=,ppid=` finds children
|
|
7
|
+
* of the pi process (pgrep is not used — it misses detached children on macOS).
|
|
8
|
+
* Grandchildren are found by recursing one level. PGIDs are stored in a tracked set.
|
|
9
|
+
* 2. CHECK: On every scan, verify which tracked PGIDs are still alive via ps.
|
|
10
|
+
* Dead ones are removed from the set.
|
|
11
|
+
*
|
|
12
|
+
* This handles the reparenting problem: children get reparented to PID 1
|
|
13
|
+
* when the bash wrapper exits, but we captured their PGIDs while alive.
|
|
14
|
+
*/
|
|
15
|
+
import { spawnSync as defaultSpawnSync } from "@blackbelt-technology/pi-dashboard-shared/platform/exec.js";
|
|
16
|
+
import type { SpawnSyncReturns } from "@blackbelt-technology/pi-dashboard-shared/platform/exec.js";
|
|
17
|
+
import { getDefaultRegistry } from "@blackbelt-technology/pi-dashboard-shared/tool-registry/index.js";
|
|
18
|
+
import { killPidWithGroup } from "@blackbelt-technology/pi-dashboard-shared/platform/process.js";
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Resolve a Windows system tool name (wmic / powershell / tasklist /
|
|
22
|
+
* taskkill) to its full `.exe` path via the global tool registry. If
|
|
23
|
+
* the registry lookup fails we fall back to the bare name and let
|
|
24
|
+
* `spawnSync` do PATHEXT resolution.
|
|
25
|
+
*
|
|
26
|
+
* Spawning the FULL path bypasses any cmd.exe / PATHEXT resolution
|
|
27
|
+
* layers, keeping `windowsHide: true` honored end-to-end. See change:
|
|
28
|
+
* consolidate-windows-spawn-and-platform-handlers.
|
|
29
|
+
*
|
|
30
|
+
* Uses `getDefaultRegistry` (not `peek*`) because the bridge extension
|
|
31
|
+
* runs inside pi's process and may be the FIRST caller to construct
|
|
32
|
+
* the registry in that process. Idempotent and cached per-process.
|
|
33
|
+
*/
|
|
34
|
+
const systemToolCache = new Map<string, string>();
|
|
35
|
+
function resolveSystemTool(name: string): string {
|
|
36
|
+
const cached = systemToolCache.get(name);
|
|
37
|
+
if (cached) return cached;
|
|
38
|
+
try {
|
|
39
|
+
const reg = getDefaultRegistry();
|
|
40
|
+
if (reg.has(name)) {
|
|
41
|
+
const res = reg.resolve(name);
|
|
42
|
+
if (res.ok && res.path) {
|
|
43
|
+
systemToolCache.set(name, res.path);
|
|
44
|
+
return res.path;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
} catch { /* registry unavailable in some test contexts */ }
|
|
48
|
+
// Cache the bare name so we only miss once per process.
|
|
49
|
+
systemToolCache.set(name, name);
|
|
50
|
+
return name;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface ChildProcessInfo {
|
|
54
|
+
pid: number;
|
|
55
|
+
pgid: number;
|
|
56
|
+
command: string;
|
|
57
|
+
elapsedMs: number;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Parse ps ETIME format into milliseconds.
|
|
62
|
+
* Re-exported from the shared platform primitive to keep the public API of
|
|
63
|
+
* this module stable while centralizing the pure helper.
|
|
64
|
+
* See change: consolidate-platform-handlers.
|
|
65
|
+
*/
|
|
66
|
+
export { parseEtime } from "@blackbelt-technology/pi-dashboard-shared/platform/process-scan.js";
|
|
67
|
+
import { parseEtime } from "@blackbelt-technology/pi-dashboard-shared/platform/process-scan.js";
|
|
68
|
+
|
|
69
|
+
const DEFAULT_MIN_ELAPSED_MS = 30_000;
|
|
70
|
+
|
|
71
|
+
export type SpawnSyncFn = (cmd: string, args: string[], opts: any) => SpawnSyncReturns<string>;
|
|
72
|
+
|
|
73
|
+
/** Get direct child PIDs of a parent using ps (pgrep misses detached children on macOS). */
|
|
74
|
+
function getChildPids(parentPid: number, spawnSync: SpawnSyncFn): number[] {
|
|
75
|
+
try {
|
|
76
|
+
const result = spawnSync("ps", ["-eo", "pid=,ppid="], {
|
|
77
|
+
encoding: "utf-8",
|
|
78
|
+
timeout: 5000,
|
|
79
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
80
|
+
});
|
|
81
|
+
if (result.status !== 0 || !result.stdout) return [];
|
|
82
|
+
const pids: number[] = [];
|
|
83
|
+
for (const line of result.stdout.split("\n")) {
|
|
84
|
+
const parts = line.trim().split(/\s+/);
|
|
85
|
+
if (parts.length === 2) {
|
|
86
|
+
const pid = parseInt(parts[0], 10);
|
|
87
|
+
const ppid = parseInt(parts[1], 10);
|
|
88
|
+
if (ppid === parentPid && !isNaN(pid)) pids.push(pid);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return pids;
|
|
92
|
+
} catch {
|
|
93
|
+
return [];
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Parse one line of ps output: " PID PGID ETIME ARGS..." */
|
|
98
|
+
function parsePsLine(line: string): ChildProcessInfo | null {
|
|
99
|
+
const trimmed = line.trim();
|
|
100
|
+
if (!trimmed) return null;
|
|
101
|
+
|
|
102
|
+
const match = trimmed.match(/^(\d+)\s+(\d+)\s+(\S+)\s+(.+)$/);
|
|
103
|
+
if (!match) return null;
|
|
104
|
+
|
|
105
|
+
return {
|
|
106
|
+
pid: parseInt(match[1], 10),
|
|
107
|
+
pgid: parseInt(match[2], 10),
|
|
108
|
+
elapsedMs: parseEtime(match[3]),
|
|
109
|
+
command: match[4],
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export interface ScanOptions {
|
|
114
|
+
_spawnSync?: SpawnSyncFn;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Captures new child PIDs of the pi process and adds their PGIDs to the tracked set.
|
|
119
|
+
* Call this during active bash tool calls when children are still in the process tree.
|
|
120
|
+
*/
|
|
121
|
+
export function captureChildPgids(
|
|
122
|
+
parentPid: number,
|
|
123
|
+
trackedPgids: Set<number>,
|
|
124
|
+
options?: ScanOptions,
|
|
125
|
+
): void {
|
|
126
|
+
const platform = (options as any)?._platform ?? process.platform;
|
|
127
|
+
if (platform === "win32") return;
|
|
128
|
+
|
|
129
|
+
const spawnSync: SpawnSyncFn = options?._spawnSync ?? defaultSpawnSync;
|
|
130
|
+
|
|
131
|
+
const directChildren = getChildPids(parentPid, spawnSync);
|
|
132
|
+
if (directChildren.length === 0) return;
|
|
133
|
+
|
|
134
|
+
// Collect all PIDs (children + grandchildren)
|
|
135
|
+
const allPids: number[] = [];
|
|
136
|
+
for (const childPid of directChildren) {
|
|
137
|
+
const grandchildren = getChildPids(childPid, spawnSync);
|
|
138
|
+
if (grandchildren.length > 0) {
|
|
139
|
+
allPids.push(...grandchildren);
|
|
140
|
+
} else {
|
|
141
|
+
allPids.push(childPid);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
if (allPids.length === 0) return;
|
|
146
|
+
|
|
147
|
+
// Get PGIDs for all discovered PIDs
|
|
148
|
+
try {
|
|
149
|
+
const result = spawnSync("ps", ["-p", allPids.join(","), "-o", "pgid="], {
|
|
150
|
+
encoding: "utf-8",
|
|
151
|
+
timeout: 5000,
|
|
152
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
153
|
+
});
|
|
154
|
+
if (result.status !== 0 || !result.stdout) return;
|
|
155
|
+
|
|
156
|
+
for (const line of result.stdout.split("\n")) {
|
|
157
|
+
const pgid = parseInt(line.trim(), 10);
|
|
158
|
+
if (!isNaN(pgid) && pgid > 0) {
|
|
159
|
+
trackedPgids.add(pgid);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
} catch {
|
|
163
|
+
// ignore
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Scans tracked PGIDs to find which are still alive.
|
|
169
|
+
* Returns live processes, removes dead PGIDs from the set.
|
|
170
|
+
*/
|
|
171
|
+
export function scanTrackedProcesses(
|
|
172
|
+
trackedPgids: Set<number>,
|
|
173
|
+
minElapsedMs: number = DEFAULT_MIN_ELAPSED_MS,
|
|
174
|
+
options?: ScanOptions,
|
|
175
|
+
): ChildProcessInfo[] {
|
|
176
|
+
const platform = (options as any)?._platform ?? process.platform;
|
|
177
|
+
if (platform === "win32" || trackedPgids.size === 0) return [];
|
|
178
|
+
|
|
179
|
+
const spawnSync: SpawnSyncFn = options?._spawnSync ?? defaultSpawnSync;
|
|
180
|
+
|
|
181
|
+
// Find all processes belonging to tracked PGIDs
|
|
182
|
+
// Use ps to find processes by PGID — we check all at once
|
|
183
|
+
const pgidList = Array.from(trackedPgids);
|
|
184
|
+
|
|
185
|
+
try {
|
|
186
|
+
// Get all processes, then filter by PGID
|
|
187
|
+
const result = spawnSync("ps", ["-eo", "pid=,pgid=,etime=,args="], {
|
|
188
|
+
encoding: "utf-8",
|
|
189
|
+
timeout: 5000,
|
|
190
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
191
|
+
});
|
|
192
|
+
if (result.status !== 0 || !result.stdout) return [];
|
|
193
|
+
|
|
194
|
+
const pgidSet = new Set(pgidList);
|
|
195
|
+
const alivePgids = new Set<number>();
|
|
196
|
+
const processes: ChildProcessInfo[] = [];
|
|
197
|
+
|
|
198
|
+
for (const line of result.stdout.split("\n")) {
|
|
199
|
+
const info = parsePsLine(line);
|
|
200
|
+
if (!info) continue;
|
|
201
|
+
if (!pgidSet.has(info.pgid)) continue;
|
|
202
|
+
|
|
203
|
+
alivePgids.add(info.pgid);
|
|
204
|
+
|
|
205
|
+
// Skip bash/sh wrappers (show the actual commands, not the shell)
|
|
206
|
+
const binary = info.command.split(/\s/)[0]?.split("/").pop() ?? "";
|
|
207
|
+
if (binary === "bash" || binary === "sh") continue;
|
|
208
|
+
|
|
209
|
+
if (info.elapsedMs >= minElapsedMs) {
|
|
210
|
+
processes.push(info);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// Remove dead PGIDs from tracked set
|
|
215
|
+
for (const pgid of pgidList) {
|
|
216
|
+
if (!alivePgids.has(pgid)) {
|
|
217
|
+
trackedPgids.delete(pgid);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
return processes;
|
|
222
|
+
} catch {
|
|
223
|
+
return [];
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Combined scan: capture new children + check tracked PGIDs.
|
|
229
|
+
* Convenience wrapper for the bridge timer.
|
|
230
|
+
*/
|
|
231
|
+
export function scanChildProcesses(
|
|
232
|
+
parentPid: number,
|
|
233
|
+
trackedPgids: Set<number>,
|
|
234
|
+
minElapsedMs: number = DEFAULT_MIN_ELAPSED_MS,
|
|
235
|
+
options?: ScanOptions,
|
|
236
|
+
): ChildProcessInfo[] {
|
|
237
|
+
const platform = (options as any)?._platform ?? process.platform;
|
|
238
|
+
if (platform === "win32") {
|
|
239
|
+
return scanWindowsProcesses(parentPid, minElapsedMs, options);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// Phase 1: Capture any new children (during active bash calls)
|
|
243
|
+
captureChildPgids(parentPid, trackedPgids, options);
|
|
244
|
+
|
|
245
|
+
// Phase 2: Check which tracked PGIDs are still alive
|
|
246
|
+
return scanTrackedProcesses(trackedPgids, minElapsedMs, options);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Kill a process group by PGID using SIGTERM (Unix) or taskkill (Windows).
|
|
251
|
+
* Returns true if signal was sent, false if process was already dead.
|
|
252
|
+
*/
|
|
253
|
+
export function killProcessByPgid(pgid: number, options?: ScanOptions): boolean {
|
|
254
|
+
const platform = (options as any)?._platform ?? process.platform;
|
|
255
|
+
if (platform === "win32") {
|
|
256
|
+
return killWindowsProcess(pgid, options);
|
|
257
|
+
}
|
|
258
|
+
try {
|
|
259
|
+
// Route through the platform helper so the pid → -pgid mapping stays
|
|
260
|
+
// in one place. See change: route-kill-paths-through-platform.
|
|
261
|
+
killPidWithGroup(pgid, "SIGTERM", { platform });
|
|
262
|
+
return true;
|
|
263
|
+
} catch {
|
|
264
|
+
return false;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// ---- Windows support ----
|
|
269
|
+
|
|
270
|
+
/** Parse wmic output lines into child process info. */
|
|
271
|
+
function parseWmicLine(line: string): { pid: number; ppid: number; command: string; creationDate: string } | null {
|
|
272
|
+
// wmic outputs: CommandLine CreationDate ParentProcessId ProcessId
|
|
273
|
+
// with fixed-width columns separated by whitespace
|
|
274
|
+
const parts = line.trim().split(/\s{2,}/);
|
|
275
|
+
if (parts.length < 4) return null;
|
|
276
|
+
const pid = parseInt(parts[3], 10);
|
|
277
|
+
const ppid = parseInt(parts[2], 10);
|
|
278
|
+
if (isNaN(pid) || isNaN(ppid)) return null;
|
|
279
|
+
return { pid, ppid, command: parts[0] || "", creationDate: parts[1] || "" };
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** Convert wmic CreationDate (yyyyMMddHHmmss.ffffff+ZZZ) to elapsed ms. */
|
|
283
|
+
function wmicDateToElapsedMs(creationDate: string): number {
|
|
284
|
+
if (!creationDate) return 0;
|
|
285
|
+
// Format: 20260410225300.123456+060
|
|
286
|
+
const match = creationDate.match(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/);
|
|
287
|
+
if (!match) return 0;
|
|
288
|
+
const created = new Date(
|
|
289
|
+
parseInt(match[1]), parseInt(match[2]) - 1, parseInt(match[3]),
|
|
290
|
+
parseInt(match[4]), parseInt(match[5]), parseInt(match[6])
|
|
291
|
+
);
|
|
292
|
+
return Math.max(0, Date.now() - created.getTime());
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** Find all descendant PIDs of a parent on Windows. */
|
|
296
|
+
function getWindowsDescendants(parentPid: number, spawnSync: SpawnSyncFn): ChildProcessInfo[] {
|
|
297
|
+
try {
|
|
298
|
+
const result = spawnSync(
|
|
299
|
+
resolveSystemTool("wmic"),
|
|
300
|
+
["process", "where", `ParentProcessId=${parentPid}`, "get", "CommandLine,CreationDate,ParentProcessId,ProcessId", "/format:list"],
|
|
301
|
+
{
|
|
302
|
+
encoding: "utf-8",
|
|
303
|
+
timeout: 5000,
|
|
304
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
305
|
+
// Critical: without this, every 10-second process scan flashes a
|
|
306
|
+
// console window. wmic is deprecated on Win 11 but still the
|
|
307
|
+
// default here; PowerShell fallback also needs windowsHide.
|
|
308
|
+
// Also: `resolveSystemTool` above returns the FULL .exe path
|
|
309
|
+
// when the registry is available, so there's no PATHEXT /
|
|
310
|
+
// cmd.exe resolution layer that could leak a console.
|
|
311
|
+
windowsHide: true,
|
|
312
|
+
},
|
|
313
|
+
);
|
|
314
|
+
if (result.status !== 0 || !result.stdout) {
|
|
315
|
+
// wmic removed in newer Windows 11 — fallback to tasklist
|
|
316
|
+
return getWindowsDescendantsTasklist(parentPid, spawnSync);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
const processes: ChildProcessInfo[] = [];
|
|
320
|
+
let current: Partial<{ pid: number; command: string; elapsed: number }> = {};
|
|
321
|
+
|
|
322
|
+
for (const line of result.stdout.split("\n")) {
|
|
323
|
+
const trimmed = line.trim();
|
|
324
|
+
if (!trimmed) {
|
|
325
|
+
if (current.pid) {
|
|
326
|
+
processes.push({
|
|
327
|
+
pid: current.pid,
|
|
328
|
+
pgid: current.pid, // Windows has no PGID; use PID
|
|
329
|
+
command: current.command || "",
|
|
330
|
+
elapsedMs: current.elapsed || 0,
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
current = {};
|
|
334
|
+
continue;
|
|
335
|
+
}
|
|
336
|
+
const [key, ...valueParts] = trimmed.split("=");
|
|
337
|
+
const value = valueParts.join("=");
|
|
338
|
+
if (key === "ProcessId") current.pid = parseInt(value, 10);
|
|
339
|
+
if (key === "CommandLine") current.command = value;
|
|
340
|
+
if (key === "CreationDate") current.elapsed = wmicDateToElapsedMs(value);
|
|
341
|
+
}
|
|
342
|
+
// Flush last entry
|
|
343
|
+
if (current.pid) {
|
|
344
|
+
processes.push({
|
|
345
|
+
pid: current.pid,
|
|
346
|
+
pgid: current.pid,
|
|
347
|
+
command: current.command || "",
|
|
348
|
+
elapsedMs: current.elapsed || 0,
|
|
349
|
+
});
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
return processes;
|
|
353
|
+
} catch {
|
|
354
|
+
return [];
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/** Fallback: use tasklist when wmic is unavailable. */
|
|
359
|
+
function getWindowsDescendantsTasklist(parentPid: number, spawnSync: SpawnSyncFn): ChildProcessInfo[] {
|
|
360
|
+
try {
|
|
361
|
+
// tasklist /FI filters by parent — but tasklist doesn't support ParentProcessId filter
|
|
362
|
+
// Use PowerShell Get-CimInstance as fallback
|
|
363
|
+
const result = spawnSync(
|
|
364
|
+
resolveSystemTool("powershell"),
|
|
365
|
+
["-NoProfile", "-Command", `Get-CimInstance Win32_Process -Filter "ParentProcessId=${parentPid}" | Select-Object ProcessId,CommandLine,CreationDate | ConvertTo-Json`],
|
|
366
|
+
{
|
|
367
|
+
encoding: "utf-8",
|
|
368
|
+
timeout: 10000,
|
|
369
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
370
|
+
// Suppress console flash for the PowerShell fallback path.
|
|
371
|
+
// `resolveSystemTool` returns the full .exe path when registry
|
|
372
|
+
// is available.
|
|
373
|
+
windowsHide: true,
|
|
374
|
+
},
|
|
375
|
+
);
|
|
376
|
+
if (result.status !== 0 || !result.stdout) return [];
|
|
377
|
+
|
|
378
|
+
const data = JSON.parse(result.stdout);
|
|
379
|
+
const items = Array.isArray(data) ? data : [data];
|
|
380
|
+
return items
|
|
381
|
+
.filter((item: any) => item?.ProcessId)
|
|
382
|
+
.map((item: any) => ({
|
|
383
|
+
pid: item.ProcessId,
|
|
384
|
+
pgid: item.ProcessId,
|
|
385
|
+
command: item.CommandLine || "",
|
|
386
|
+
elapsedMs: item.CreationDate ? Math.max(0, Date.now() - new Date(item.CreationDate).getTime()) : 0,
|
|
387
|
+
}));
|
|
388
|
+
} catch {
|
|
389
|
+
return [];
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/** Scan child processes on Windows using wmic/PowerShell. */
|
|
394
|
+
export function scanWindowsProcesses(
|
|
395
|
+
parentPid: number,
|
|
396
|
+
minElapsedMs: number = DEFAULT_MIN_ELAPSED_MS,
|
|
397
|
+
options?: ScanOptions,
|
|
398
|
+
): ChildProcessInfo[] {
|
|
399
|
+
const spawnSync: SpawnSyncFn = options?._spawnSync ?? defaultSpawnSync;
|
|
400
|
+
const children = getWindowsDescendants(parentPid, spawnSync);
|
|
401
|
+
|
|
402
|
+
// Recurse one level for grandchildren
|
|
403
|
+
const all: ChildProcessInfo[] = [];
|
|
404
|
+
for (const child of children) {
|
|
405
|
+
const grandchildren = getWindowsDescendants(child.pid, spawnSync);
|
|
406
|
+
if (grandchildren.length > 0) {
|
|
407
|
+
all.push(...grandchildren);
|
|
408
|
+
} else {
|
|
409
|
+
all.push(child);
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
return all.filter(p => p.elapsedMs >= minElapsedMs);
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/** Kill a process tree on Windows using taskkill. */
|
|
417
|
+
export function killWindowsProcess(pid: number, options?: ScanOptions): boolean {
|
|
418
|
+
const spawnSync: SpawnSyncFn = options?._spawnSync ?? defaultSpawnSync;
|
|
419
|
+
try {
|
|
420
|
+
const result = spawnSync(resolveSystemTool("taskkill"), ["/PID", String(pid), "/T", "/F"], {
|
|
421
|
+
windowsHide: true,
|
|
422
|
+
encoding: "utf-8",
|
|
423
|
+
timeout: 5000,
|
|
424
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
425
|
+
});
|
|
426
|
+
return result.status === 0;
|
|
427
|
+
} catch {
|
|
428
|
+
return false;
|
|
429
|
+
}
|
|
430
|
+
}
|