-
-
Notifications
You must be signed in to change notification settings - Fork 80.8k
Expand file tree
/
Copy pathrestart-health.ts
More file actions
684 lines (638 loc) · 21.7 KB
/
Copy pathrestart-health.ts
File metadata and controls
684 lines (638 loc) · 21.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
// Restart health probes for gateway service restarts and port listener recovery.
import {
normalizeLowercaseStringOrEmpty,
normalizeOptionalString,
} from "@openclaw/normalization-core/string-coerce";
import type { PluginHealthErrorSummary } from "../../commands/health.types.js";
import { createConfigIO } from "../../config/io.js";
import type { OpenClawConfig } from "../../config/types.openclaw.js";
import type { GatewayServiceRuntime } from "../../daemon/service-runtime.js";
import type { GatewayService } from "../../daemon/service.js";
import { resolveGatewayProbeAuthSafeWithSecretInputs } from "../../gateway/probe-auth.js";
import { probeGateway } from "../../gateway/probe.js";
import {
classifyPortListener,
formatPortDiagnostics,
inspectPortUsage,
type PortUsage,
} from "../../infra/ports.js";
import { killProcessTree } from "../../process/kill-tree.js";
import { sleep } from "../../utils.js";
export const DEFAULT_RESTART_HEALTH_TIMEOUT_MS = 60_000;
export const DEFAULT_RESTART_HEALTH_DELAY_MS = 500;
export const DEFAULT_RESTART_HEALTH_ATTEMPTS = Math.ceil(
DEFAULT_RESTART_HEALTH_TIMEOUT_MS / DEFAULT_RESTART_HEALTH_DELAY_MS,
);
const STOPPED_FREE_EARLY_EXIT_GRACE_MS = 10_000;
const WINDOWS_STOPPED_FREE_EARLY_EXIT_GRACE_MS = 90_000;
export type GatewayRestartWaitOutcome =
| "healthy"
| "plugin-errors"
| "channel-errors"
| "version-mismatch"
| "stale-pids"
| "stopped-free"
| "timeout";
export type GatewayRestartSnapshot = {
runtime: GatewayServiceRuntime;
portUsage: PortUsage;
healthy: boolean;
staleGatewayPids: number[];
gatewayVersion?: string | null;
activatedPluginErrors?: PluginHealthErrorSummary[];
channelProbeErrors?: Array<{ id: string; error: string }>;
expectedVersion?: string;
versionMismatch?: {
expected: string;
actual: string | null;
};
waitOutcome?: GatewayRestartWaitOutcome;
elapsedMs?: number;
};
export type GatewayPortHealthSnapshot = {
portUsage: PortUsage;
healthy: boolean;
};
type GatewayReachability = {
reachable: boolean;
gatewayVersion: string | null;
activatedPluginErrors: PluginHealthErrorSummary[];
channelProbeErrors: Array<{ id: string; error: string }>;
};
type GatewayRestartProbeAuth = {
token?: string;
password?: string;
};
function hasListenerAttributionGap(portUsage: PortUsage): boolean {
// lsof/netstat may report a busy port without a PID; keep that distinct from a free port.
if (portUsage.status !== "busy" || portUsage.listeners.length > 0) {
return false;
}
if (portUsage.errors?.length) {
return true;
}
return portUsage.hints.some((hint) => hint.includes("process details are unavailable"));
}
function listenerOwnedByRuntimePid(params: {
listener: PortUsage["listeners"][number];
runtimePid: number;
}): boolean {
return params.listener.pid === params.runtimePid || params.listener.ppid === params.runtimePid;
}
function looksLikeAuthClose(code: number | undefined, reason: string | undefined): boolean {
if (code !== 1008) {
return false;
}
const normalized = normalizeLowercaseStringOrEmpty(reason);
if (!normalized) {
return false;
}
// The restart probe runs against loopback only and only decides restart
// liveness, not authorization. Keep this allowlist exact so a local listener
// cannot satisfy the health check with broad device/auth-looking text.
return (
normalized === "auth required" ||
normalized === "owner auth required" ||
normalized === "connect failed" ||
normalized === "device required" ||
normalized === "pairing required" ||
normalized.startsWith("pairing required:") ||
normalized.startsWith("unauthorized: gateway token missing") ||
normalized.startsWith("unauthorized: gateway token mismatch") ||
normalized.startsWith("unauthorized: gateway token not configured") ||
normalized.startsWith("unauthorized: gateway password missing") ||
normalized.startsWith("unauthorized: gateway password mismatch") ||
normalized.startsWith("unauthorized: gateway password not configured") ||
normalized.startsWith("unauthorized: bootstrap token invalid or expired") ||
normalized.startsWith("unauthorized: tailscale identity missing") ||
normalized.startsWith("unauthorized: tailscale proxy headers missing") ||
normalized.startsWith("unauthorized: tailscale identity check failed") ||
normalized.startsWith("unauthorized: tailscale identity mismatch") ||
normalized.startsWith("unauthorized: too many failed authentication attempts") ||
normalized.startsWith("unauthorized: device token mismatch") ||
normalized.startsWith("unauthorized: device token rejected")
);
}
function applyExpectedVersion(
snapshot: GatewayRestartSnapshot,
expectedVersion: string | undefined,
): GatewayRestartSnapshot {
if (!expectedVersion) {
return snapshot;
}
if (snapshot.gatewayVersion === expectedVersion) {
return { ...snapshot, expectedVersion };
}
if (snapshot.gatewayVersion == null) {
return { ...snapshot, healthy: false, expectedVersion };
}
return {
...snapshot,
healthy: false,
expectedVersion,
versionMismatch: {
expected: expectedVersion,
actual: snapshot.gatewayVersion ?? null,
},
};
}
function readActivatedPluginErrors(health: unknown): PluginHealthErrorSummary[] {
if (!health || typeof health !== "object") {
return [];
}
const plugins = (health as { plugins?: unknown }).plugins;
if (!plugins || typeof plugins !== "object") {
return [];
}
const errors = (plugins as { errors?: unknown }).errors;
if (!Array.isArray(errors)) {
return [];
}
return errors
.filter((entry): entry is PluginHealthErrorSummary => {
if (!entry || typeof entry !== "object") {
return false;
}
const candidate = entry as Partial<PluginHealthErrorSummary>;
return (
candidate.activated === true &&
typeof candidate.id === "string" &&
typeof candidate.error === "string"
);
})
.map((entry) => {
const error: PluginHealthErrorSummary = {
id: entry.id,
origin: typeof entry.origin === "string" ? entry.origin : "unknown",
activated: true,
error: entry.error,
};
if (typeof entry.activationSource === "string") {
error.activationSource = entry.activationSource;
}
if (typeof entry.activationReason === "string") {
error.activationReason = entry.activationReason;
}
if (typeof entry.failurePhase === "string") {
error.failurePhase = entry.failurePhase;
}
return error;
});
}
function readChannelProbeErrors(health: unknown): Array<{ id: string; error: string }> {
if (!health || typeof health !== "object") {
return [];
}
const channels = (health as { channels?: unknown }).channels;
if (!channels || typeof channels !== "object" || Array.isArray(channels)) {
return [];
}
const errors: Array<{ id: string; error: string }> = [];
for (const [id, summary] of Object.entries(channels)) {
if (!summary || typeof summary !== "object") {
continue;
}
const probe = (summary as { probe?: unknown }).probe;
if (!probe || typeof probe !== "object") {
continue;
}
const ok = (probe as { ok?: unknown }).ok;
if (ok !== false) {
continue;
}
const error = (probe as { error?: unknown }).error;
errors.push({
id,
error: typeof error === "string" && error.trim() ? error : "probe failed",
});
}
return errors;
}
function applyActivatedPluginErrors(snapshot: GatewayRestartSnapshot): GatewayRestartSnapshot {
if (!snapshot.activatedPluginErrors?.length) {
return snapshot;
}
return { ...snapshot, healthy: false };
}
function applyChannelProbeErrors(snapshot: GatewayRestartSnapshot): GatewayRestartSnapshot {
if (!snapshot.channelProbeErrors?.length) {
return snapshot;
}
return { ...snapshot, healthy: false };
}
async function confirmGatewayReachable(params: {
port: number;
includeHealthDetails?: boolean;
auth?: GatewayRestartProbeAuth;
env?: NodeJS.ProcessEnv;
}): Promise<GatewayReachability> {
const token = normalizeOptionalString(params.auth?.token ?? process.env.OPENCLAW_GATEWAY_TOKEN);
const password = normalizeOptionalString(
params.auth?.password ?? process.env.OPENCLAW_GATEWAY_PASSWORD,
);
const probe = await probeGateway({
url: `ws://127.0.0.1:${params.port}`,
auth: token || password ? { token, password } : undefined,
timeoutMs: 3_000,
includeDetails: params.includeHealthDetails === true,
env: params.env,
});
const reachedGateway =
probe.ok ||
looksLikeAuthClose(probe.close?.code, probe.close?.reason) ||
(probe.connectLatencyMs != null &&
probe.server?.version != null &&
probe.auth.capability === "connected_no_operator_scope");
return {
reachable: reachedGateway,
gatewayVersion: probe.server?.version ?? null,
activatedPluginErrors: readActivatedPluginErrors(probe.health),
channelProbeErrors: readChannelProbeErrors(probe.health),
};
}
async function resolveGatewayRestartProbeAuth(
env: NodeJS.ProcessEnv | undefined,
): Promise<GatewayRestartProbeAuth | undefined> {
const mergedEnv = {
...(process.env as Record<string, string | undefined>),
...(env ?? undefined),
} as NodeJS.ProcessEnv;
const cfg = await createConfigIO({
env: mergedEnv,
pluginValidation: "skip",
suppressFutureVersionWarning: true,
})
.readBestEffortConfig()
.catch((): OpenClawConfig => ({}));
const resolved = await resolveGatewayProbeAuthSafeWithSecretInputs({
cfg,
mode: "local",
env: mergedEnv,
});
return resolved.auth;
}
async function inspectGatewayPortHealth(params: {
port: number;
auth?: GatewayRestartProbeAuth;
}): Promise<GatewayPortHealthSnapshot> {
let portUsage: PortUsage;
try {
portUsage = await inspectPortUsage(params.port);
} catch (err) {
portUsage = {
port: params.port,
status: "unknown",
listeners: [],
hints: [],
errors: [String(err)],
};
}
let healthy = false;
if (portUsage.status === "busy") {
try {
healthy = (
await confirmGatewayReachable({
port: params.port,
auth: params.auth,
env: process.env,
})
).reachable;
} catch {
// best-effort probe
}
}
return { portUsage, healthy };
}
export async function inspectGatewayRestart(params: {
service: GatewayService;
port: number;
env?: NodeJS.ProcessEnv;
expectedVersion?: string | null;
includeUnknownListenersAsStale?: boolean;
probeAuth?: GatewayRestartProbeAuth;
}): Promise<GatewayRestartSnapshot> {
const env = params.env ?? process.env;
const expectedVersion = normalizeOptionalString(params.expectedVersion);
let reachability: GatewayReachability | null = null;
let activatedPluginErrors: PluginHealthErrorSummary[] = [];
let channelProbeErrors: Array<{ id: string; error: string }> = [];
const loadReachability = async () => {
if (!reachability) {
reachability = await confirmGatewayReachable({
port: params.port,
includeHealthDetails: Boolean(expectedVersion),
auth: params.probeAuth,
env,
});
activatedPluginErrors = reachability.activatedPluginErrors;
channelProbeErrors = reachability.channelProbeErrors;
}
return reachability;
};
let runtime: GatewayServiceRuntime = { status: "unknown" };
try {
runtime = await params.service.readRuntime(env);
} catch (err) {
runtime = { status: "unknown", detail: String(err) };
}
let portUsage: PortUsage;
try {
portUsage = await inspectPortUsage(params.port);
} catch (err) {
portUsage = {
port: params.port,
status: "unknown",
listeners: [],
hints: [],
errors: [String(err)],
};
}
if (portUsage.status === "busy" && runtime.status !== "running") {
try {
const reachable = await loadReachability();
if (reachable.reachable) {
return applyChannelProbeErrors(
applyActivatedPluginErrors(
applyExpectedVersion(
{
runtime,
portUsage,
healthy: true,
staleGatewayPids: [],
gatewayVersion: reachable.gatewayVersion,
...(reachable.activatedPluginErrors.length > 0
? { activatedPluginErrors: reachable.activatedPluginErrors }
: {}),
...(reachable.channelProbeErrors.length > 0
? { channelProbeErrors: reachable.channelProbeErrors }
: {}),
},
expectedVersion,
),
),
);
}
} catch {
// Probe is best-effort; keep the ownership-based diagnostics.
}
}
const gatewayListeners =
portUsage.status === "busy"
? portUsage.listeners.filter(
(listener) => classifyPortListener(listener, params.port) === "gateway",
)
: [];
const fallbackListenerPids =
params.includeUnknownListenersAsStale &&
process.platform === "win32" &&
runtime.status !== "running" &&
portUsage.status === "busy"
? portUsage.listeners
.filter((listener) => classifyPortListener(listener, params.port) === "unknown")
.map((listener) => listener.pid)
.filter((pid): pid is number => Number.isFinite(pid))
: [];
const running = runtime.status === "running";
const runtimePid = runtime.pid;
const listenerAttributionGap = hasListenerAttributionGap(portUsage);
const ownsPort =
runtimePid != null
? portUsage.listeners.some((listener) =>
listenerOwnedByRuntimePid({ listener, runtimePid }),
) || listenerAttributionGap
: gatewayListeners.length > 0 || listenerAttributionGap;
let healthy = running && ownsPort;
let gatewayVersion: string | null | undefined;
if (expectedVersion && healthy && portUsage.status === "busy") {
try {
const reachable = await loadReachability();
healthy = reachable.reachable;
gatewayVersion = reachable.gatewayVersion;
if (reachable.activatedPluginErrors.length > 0) {
healthy = false;
}
if (reachable.channelProbeErrors.length > 0) {
healthy = false;
}
} catch {
healthy = false;
}
}
if (!healthy && running && portUsage.status === "busy" && !expectedVersion) {
try {
const reachable = await loadReachability();
healthy = reachable.reachable;
gatewayVersion = reachable.gatewayVersion;
} catch {
// best-effort probe
}
}
const staleGatewayPids = Array.from(
new Set([
...gatewayListeners
.filter((listener) => Number.isFinite(listener.pid))
.filter((listener) => {
if (!running) {
return true;
}
if (runtimePid == null) {
return false;
}
return !listenerOwnedByRuntimePid({ listener, runtimePid });
})
.map((listener) => listener.pid as number),
...fallbackListenerPids.filter(
(pid) => runtime.pid == null || pid !== runtime.pid || !running,
),
]),
);
return applyChannelProbeErrors(
applyActivatedPluginErrors(
applyExpectedVersion(
{
runtime,
portUsage,
healthy,
staleGatewayPids,
...(gatewayVersion !== undefined ? { gatewayVersion } : {}),
...(activatedPluginErrors.length ? { activatedPluginErrors } : {}),
...(channelProbeErrors.length ? { channelProbeErrors } : {}),
},
expectedVersion,
),
),
);
}
function shouldEarlyExitStoppedFree(
snapshot: GatewayRestartSnapshot,
attempt: number,
minAttempt: number,
): boolean {
return (
attempt >= minAttempt &&
snapshot.runtime.status === "stopped" &&
snapshot.portUsage.status === "free"
);
}
function stoppedFreeEarlyExitGraceMs(): number {
return process.platform === "win32"
? WINDOWS_STOPPED_FREE_EARLY_EXIT_GRACE_MS
: STOPPED_FREE_EARLY_EXIT_GRACE_MS;
}
function withWaitContext(
snapshot: GatewayRestartSnapshot,
waitOutcome: GatewayRestartWaitOutcome,
elapsedMs: number,
): GatewayRestartSnapshot {
return { ...snapshot, waitOutcome, elapsedMs };
}
export async function waitForGatewayHealthyRestart(params: {
service: GatewayService;
port: number;
attempts?: number;
delayMs?: number;
env?: NodeJS.ProcessEnv;
expectedVersion?: string | null;
includeUnknownListenersAsStale?: boolean;
requireRunningService?: boolean;
}): Promise<GatewayRestartSnapshot> {
const attempts = params.attempts ?? DEFAULT_RESTART_HEALTH_ATTEMPTS;
const delayMs = params.delayMs ?? DEFAULT_RESTART_HEALTH_DELAY_MS;
const probeAuth = await resolveGatewayRestartProbeAuth(params.env).catch(() => undefined);
let snapshot = await inspectGatewayRestart({
service: params.service,
port: params.port,
env: params.env,
expectedVersion: params.expectedVersion,
includeUnknownListenersAsStale: params.includeUnknownListenersAsStale,
probeAuth,
});
let consecutiveStoppedFreeCount = 0;
const STOPPED_FREE_THRESHOLD = 6;
const minAttemptForEarlyExit = Math.min(
Math.ceil(stoppedFreeEarlyExitGraceMs() / delayMs),
Math.floor(attempts / 2),
);
for (let attempt = 0; attempt < attempts; attempt += 1) {
const healthy =
snapshot.healthy && (!params.requireRunningService || snapshot.runtime.status === "running");
if (healthy) {
return withWaitContext(snapshot, "healthy", attempt * delayMs);
}
if (snapshot.activatedPluginErrors?.length) {
return withWaitContext(snapshot, "plugin-errors", attempt * delayMs);
}
if (snapshot.channelProbeErrors?.length) {
return withWaitContext(snapshot, "channel-errors", attempt * delayMs);
}
if (snapshot.versionMismatch) {
return withWaitContext(snapshot, "version-mismatch", attempt * delayMs);
}
if (snapshot.staleGatewayPids.length > 0 && snapshot.runtime.status !== "running") {
return withWaitContext(snapshot, "stale-pids", attempt * delayMs);
}
if (shouldEarlyExitStoppedFree(snapshot, attempt, minAttemptForEarlyExit)) {
consecutiveStoppedFreeCount += 1;
if (consecutiveStoppedFreeCount >= STOPPED_FREE_THRESHOLD) {
return withWaitContext(snapshot, "stopped-free", attempt * delayMs);
}
} else if (snapshot.runtime.status !== "stopped" || snapshot.portUsage.status !== "free") {
consecutiveStoppedFreeCount = 0;
}
await sleep(delayMs);
snapshot = await inspectGatewayRestart({
service: params.service,
port: params.port,
env: params.env,
expectedVersion: params.expectedVersion,
includeUnknownListenersAsStale: params.includeUnknownListenersAsStale,
probeAuth,
});
}
return withWaitContext(snapshot, "timeout", attempts * delayMs);
}
export async function waitForGatewayHealthyListener(params: {
port: number;
attempts?: number;
delayMs?: number;
}): Promise<GatewayPortHealthSnapshot> {
const attempts = params.attempts ?? DEFAULT_RESTART_HEALTH_ATTEMPTS;
const delayMs = params.delayMs ?? DEFAULT_RESTART_HEALTH_DELAY_MS;
const probeAuth = await resolveGatewayRestartProbeAuth(undefined).catch(() => undefined);
let snapshot = await inspectGatewayPortHealth({
port: params.port,
auth: probeAuth,
});
for (let attempt = 0; attempt < attempts; attempt += 1) {
if (snapshot.healthy) {
return snapshot;
}
await sleep(delayMs);
snapshot = await inspectGatewayPortHealth({
port: params.port,
auth: probeAuth,
});
}
return snapshot;
}
function renderPortUsageDiagnostics(snapshot: GatewayPortHealthSnapshot): string[] {
const lines: string[] = [];
if (snapshot.portUsage.status === "busy") {
lines.push(...formatPortDiagnostics(snapshot.portUsage));
} else {
lines.push(`Gateway port ${snapshot.portUsage.port} status: ${snapshot.portUsage.status}.`);
}
if (snapshot.portUsage.errors?.length) {
lines.push(`Port diagnostics errors: ${snapshot.portUsage.errors.join("; ")}`);
}
return lines;
}
export function renderRestartDiagnostics(snapshot: GatewayRestartSnapshot): string[] {
const lines: string[] = [];
if (snapshot.versionMismatch) {
const actual = snapshot.versionMismatch.actual ?? "unavailable";
lines.push(
`Gateway version mismatch: expected ${snapshot.versionMismatch.expected}, running gateway reported ${actual}.`,
);
}
if (snapshot.activatedPluginErrors?.length) {
lines.push("Activated plugin load errors:");
for (const plugin of snapshot.activatedPluginErrors) {
lines.push(`- ${plugin.id}: ${plugin.error}`);
}
}
if (snapshot.channelProbeErrors?.length) {
lines.push("Channel health probe errors:");
for (const channel of snapshot.channelProbeErrors) {
lines.push(`- ${channel.id}: ${channel.error}`);
}
}
const runtimeSummary = [
snapshot.runtime.status ? `status=${snapshot.runtime.status}` : null,
snapshot.runtime.state ? `state=${snapshot.runtime.state}` : null,
snapshot.runtime.pid != null ? `pid=${snapshot.runtime.pid}` : null,
snapshot.runtime.lastExitStatus != null ? `lastExit=${snapshot.runtime.lastExitStatus}` : null,
]
.filter(Boolean)
.join(", ");
if (runtimeSummary) {
lines.push(`Service runtime: ${runtimeSummary}`);
}
lines.push(...renderPortUsageDiagnostics(snapshot));
return lines;
}
export function renderGatewayPortHealthDiagnostics(snapshot: GatewayPortHealthSnapshot): string[] {
return renderPortUsageDiagnostics(snapshot);
}
export async function terminateStaleGatewayPids(pids: number[]): Promise<number[]> {
const targets = Array.from(
new Set(pids.filter((pid): pid is number => Number.isFinite(pid) && pid > 0)),
);
for (const pid of targets) {
killProcessTree(pid, { graceMs: 300 });
}
if (targets.length > 0) {
await sleep(500);
}
return targets;
}