Files
Agent-Workbench/src/core/owned-process-tree.mjs
T

38 lines
2.9 KiB
JavaScript

import { execFile } from 'node:child_process';
import { gitEnvironment } from './git-process.mjs';
// Read only: recovery never terminates a process based on a historical PID.
// Command lines and environments are deliberately excluded from the inventory.
export async function readOwnedProcessTree(info) {
if (process.platform !== 'win32') return { processes: [], supported: false };
if (!Number.isSafeInteger(info.pid) || info.pid <= 0 || !Number.isFinite(Date.parse(info.startedAt))) throw new Error('原检查进程身份无效。');
const script = "$ErrorActionPreference='Stop'; [Console]::OutputEncoding=New-Object System.Text.UTF8Encoding($false); @(Get-CimInstance Win32_Process | ForEach-Object { [pscustomobject]@{ pid=[int]$_.ProcessId; parentPid=[int]$_.ParentProcessId; createdAt=$_.CreationDate.ToUniversalTime().ToString('o'); executable=$_.ExecutablePath } }) | ConvertTo-Json -Compress";
const inventory = await new Promise((resolve, reject) => execFile('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script],
{ windowsHide: true, timeout: 8000, maxBuffer: 2 * 1024 * 1024, env: gitEnvironment() }, (error, stdout) => {
if (error) reject(new Error('原检查进程树无法只读核对:' + error.message.slice(0, 1200)));
else { try { resolve(JSON.parse(stdout)); } catch { reject(new Error('原检查进程树输出格式无效,不能声明进程已结束。')); } }
}));
const all = Array.isArray(inventory) ? inventory : [inventory], selected = new Map(), seeds = new Set(), since = Date.parse(info.startedAt) - 3000;
const same = (actual, original) => actual.pid === original.pid && actual.createdAt === original.createdAt;
const root = all.find(value => value.pid === info.pid);
const rootMatches = root && (info.rootCreatedAt ? root.createdAt === info.rootCreatedAt
: Date.parse(root.createdAt) >= since && Date.parse(root.createdAt) <= Date.parse(info.startedAt) + 3000);
if (rootMatches) { selected.set(root.pid, root); seeds.add(root.pid); }
else if (!root) seeds.add(info.pid);
for (const original of info.descendants ?? []) {
const actual = all.find(value => same(value, original));
if (actual) { selected.set(actual.pid, actual); seeds.add(actual.pid); }
else if (!all.some(value => value.pid === original.pid)) seeds.add(original.pid);
}
for (let depth = 0; depth < 32; depth++) {
let added = false;
for (const value of all) if (seeds.has(value.parentPid) && !selected.has(value.pid) && Date.parse(value.createdAt) >= since) {
selected.set(value.pid, value); seeds.add(value.pid); added = true;
if (selected.size > 256) throw new Error('原检查进程树超过256项,不能省略进程后声明结束。');
}
if (!added) break;
if (depth === 31) throw new Error('原检查进程树超过32层,结束状态仍需核对。');
}
return { supported: true, processes: [...selected.values()].sort((a, b) => a.pid - b.pid), root: rootMatches ? root : null };
}