infinity-portpilot 0.0.0-stage → 0.1.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.
@@ -0,0 +1,196 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.linuxProvider = void 0;
4
+ exports.formatProcAddress = formatProcAddress;
5
+ exports.parseProcNetTcp = parseProcNetTcp;
6
+ exports.findWithProc = findWithProc;
7
+ const node_fs_1 = require("node:fs");
8
+ const lsof_1 = require("../lsof");
9
+ function reverseBytes(hex) {
10
+ const bytes = hex.match(/../g) ?? [];
11
+ return bytes.reverse().join("");
12
+ }
13
+ /** Convert the hex address format used by /proc/net/tcp{,6}. */
14
+ function formatProcAddress(hex, ipv6) {
15
+ if (!ipv6) {
16
+ if (hex.length !== 8) {
17
+ return null;
18
+ }
19
+ const reversed = reverseBytes(hex);
20
+ return [0, 2, 4, 6]
21
+ .map((offset) => Number.parseInt(reversed.slice(offset, offset + 2), 16))
22
+ .join(".");
23
+ }
24
+ if (hex.length !== 32) {
25
+ return null;
26
+ }
27
+ const groups = [];
28
+ for (let offset = 0; offset < 32; offset += 8) {
29
+ groups.push(reverseBytes(hex.slice(offset, offset + 8)));
30
+ }
31
+ const matched = groups.join("").match(/.{4}/g);
32
+ return matched ? matched.join(":") : null;
33
+ }
34
+ /** Parse /proc/net/tcp or /proc/net/tcp6, returning only LISTEN sockets. */
35
+ function parseProcNetTcp(content, ipv6) {
36
+ const sockets = [];
37
+ for (const line of content.split("\n").slice(1)) {
38
+ const fields = line.trim().split(/\s+/);
39
+ if (fields.length < 10) {
40
+ continue;
41
+ }
42
+ const [localHex, portHex] = fields[1].split(":");
43
+ const state = fields[3].toUpperCase();
44
+ const inode = fields[9];
45
+ if (state !== "0A") {
46
+ continue;
47
+ }
48
+ const address = formatProcAddress(localHex, ipv6);
49
+ const port = Number.parseInt(portHex, 16);
50
+ if (!address || !Number.isInteger(port) || port < 1 || port > 65535) {
51
+ continue;
52
+ }
53
+ sockets.push({ address, port, inode });
54
+ }
55
+ return sockets;
56
+ }
57
+ /**
58
+ * Resolve listening sockets to PIDs by scanning /proc/<pid>/fd.
59
+ *
60
+ * Processes owned by other users generally cannot be read without elevated
61
+ * privileges; those endpoints are still reported with an unknown PID rather
62
+ * than being hidden or causing a failure.
63
+ */
64
+ async function findWithProc(port) {
65
+ const errors = [];
66
+ const sockets = [];
67
+ for (const [file, ipv6] of [
68
+ ["/proc/net/tcp", false],
69
+ ["/proc/net/tcp6", true],
70
+ ]) {
71
+ try {
72
+ const content = await node_fs_1.promises.readFile(file, "utf8");
73
+ sockets.push(...parseProcNetTcp(content, ipv6));
74
+ }
75
+ catch (error) {
76
+ const code = error.code;
77
+ if (code !== "ENOENT") {
78
+ errors.push({
79
+ code: code === "EACCES" ? "permission" : "unavailable",
80
+ message: `Could not read ${file}: ${error.message}`,
81
+ });
82
+ }
83
+ }
84
+ }
85
+ const wanted = port === undefined
86
+ ? sockets
87
+ : sockets.filter((socket) => socket.port === port);
88
+ const byInode = new Map(wanted.map((socket) => [socket.inode, socket]));
89
+ if (byInode.size === 0) {
90
+ return { listeners: [], errors };
91
+ }
92
+ const resolved = new Map();
93
+ let denied = false;
94
+ let procEntries = [];
95
+ try {
96
+ procEntries = await node_fs_1.promises.readdir("/proc");
97
+ }
98
+ catch (error) {
99
+ errors.push({
100
+ code: "unavailable",
101
+ message: `Could not scan /proc: ${error.message}`,
102
+ });
103
+ return { listeners: [], errors };
104
+ }
105
+ const pids = procEntries.filter((entry) => /^\d+$/.test(entry));
106
+ for (const pidEntry of pids) {
107
+ const pid = Number.parseInt(pidEntry, 10);
108
+ let fds;
109
+ try {
110
+ fds = await node_fs_1.promises.readdir(`/proc/${pidEntry}/fd`);
111
+ }
112
+ catch (error) {
113
+ if (error.code === "EACCES") {
114
+ denied = true;
115
+ }
116
+ continue;
117
+ }
118
+ let name;
119
+ for (const fd of fds) {
120
+ let target;
121
+ try {
122
+ target = await node_fs_1.promises.readlink(`/proc/${pidEntry}/fd/${fd}`);
123
+ }
124
+ catch {
125
+ continue;
126
+ }
127
+ const match = /^socket:\[(\d+)\]$/.exec(target);
128
+ if (!match) {
129
+ continue;
130
+ }
131
+ const socket = byInode.get(match[1]);
132
+ if (!socket) {
133
+ continue;
134
+ }
135
+ if (name === undefined) {
136
+ try {
137
+ name = (await node_fs_1.promises.readFile(`/proc/${pidEntry}/comm`, "utf8")).trim();
138
+ }
139
+ catch {
140
+ denied = true;
141
+ name = "unknown";
142
+ }
143
+ }
144
+ const key = `${pid}|${socket.address}|${socket.port}`;
145
+ if (resolved.has(key)) {
146
+ continue;
147
+ }
148
+ resolved.set(key, {
149
+ pid,
150
+ name,
151
+ localAddress: `${socket.address}:${socket.port}`,
152
+ port: socket.port,
153
+ protocol: "TCP",
154
+ });
155
+ }
156
+ }
157
+ const listeners = [...resolved.values()];
158
+ for (const socket of wanted) {
159
+ const known = listeners.some((listener) => listener.port === socket.port &&
160
+ listener.localAddress === `${socket.address}:${socket.port}`);
161
+ if (!known) {
162
+ listeners.push({
163
+ pid: null,
164
+ name: "unknown",
165
+ localAddress: `${socket.address}:${socket.port}`,
166
+ port: socket.port,
167
+ protocol: "TCP",
168
+ });
169
+ }
170
+ }
171
+ if (denied) {
172
+ errors.push({
173
+ code: "permission",
174
+ message: "Some processes could not be inspected due to permissions; their PIDs are shown as unknown",
175
+ });
176
+ }
177
+ return { listeners: (0, lsof_1.dedupeListeners)(listeners), errors };
178
+ }
179
+ exports.linuxProvider = {
180
+ name: "Linux (lsof, /proc fallback)",
181
+ async findListeners(port) {
182
+ const lsof = await (0, lsof_1.findWithLsof)(port);
183
+ if (lsof.listeners.length > 0 || lsof.errors.length === 0) {
184
+ return lsof;
185
+ }
186
+ const fallback = await findWithProc(port);
187
+ if (fallback.listeners.length > 0) {
188
+ return fallback;
189
+ }
190
+ return {
191
+ listeners: fallback.listeners,
192
+ errors: [...lsof.errors, ...fallback.errors].filter((error, index, all) => all.findIndex((candidate) => candidate.message === error.message) ===
193
+ index),
194
+ };
195
+ },
196
+ };
@@ -0,0 +1,89 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.macosProvider = void 0;
4
+ exports.parseMacNetstatOutput = parseMacNetstatOutput;
5
+ exports.findWithMacNetstat = findWithMacNetstat;
6
+ const exec_1 = require("../../utils/exec");
7
+ const lsof_1 = require("../lsof");
8
+ /**
9
+ * Parse macOS `netstat -an -p tcp` output. This fallback can identify
10
+ * listening endpoints but not owning PIDs unless lsof is available.
11
+ */
12
+ function parseMacNetstatOutput(output, filterPort) {
13
+ const listeners = [];
14
+ for (const line of output.split("\n")) {
15
+ const parts = line.trim().split(/\s+/);
16
+ if (parts.length < 6) {
17
+ continue;
18
+ }
19
+ const [proto, , , local, , state] = parts;
20
+ if (!/^tcp/.test(proto) || state.toUpperCase() !== "LISTEN") {
21
+ continue;
22
+ }
23
+ const match = /^(.*)\.(\d{1,5})$/.exec(local);
24
+ if (!match) {
25
+ continue;
26
+ }
27
+ const address = match[1];
28
+ const port = Number.parseInt(match[2], 10);
29
+ if (port < 1 || port > 65535) {
30
+ continue;
31
+ }
32
+ if (filterPort !== undefined && port !== filterPort) {
33
+ continue;
34
+ }
35
+ const host = address.includes(":") ? `[${address}]` : address;
36
+ listeners.push({
37
+ pid: null,
38
+ name: "unknown",
39
+ localAddress: `${host}:${port}`,
40
+ port,
41
+ protocol: "TCP",
42
+ });
43
+ }
44
+ return (0, lsof_1.dedupeListeners)(listeners);
45
+ }
46
+ async function findWithMacNetstat(port) {
47
+ const result = await (0, exec_1.runCommand)("netstat", ["-an", "-p", "tcp"]);
48
+ if (!result.ok) {
49
+ if ((0, exec_1.isMissingCommand)(result)) {
50
+ return {
51
+ listeners: [],
52
+ errors: [
53
+ {
54
+ code: "unavailable",
55
+ message: "Neither lsof nor netstat is available on this system",
56
+ },
57
+ ],
58
+ };
59
+ }
60
+ return {
61
+ listeners: [],
62
+ errors: [
63
+ {
64
+ code: "unknown",
65
+ message: `netstat failed: ${result.stderr.trim() || result.message}`,
66
+ },
67
+ ],
68
+ };
69
+ }
70
+ return { listeners: parseMacNetstatOutput(result.stdout, port), errors: [] };
71
+ }
72
+ exports.macosProvider = {
73
+ name: "macOS (lsof)",
74
+ async findListeners(port) {
75
+ const lsof = await (0, lsof_1.findWithLsof)(port);
76
+ if (lsof.listeners.length > 0 || lsof.errors.length === 0) {
77
+ return lsof;
78
+ }
79
+ // lsof is missing, timed out, or restricted. netstat can still show
80
+ // listening endpoints, but not reliably which process owns them.
81
+ const fallback = await findWithMacNetstat(port);
82
+ const errors = [...lsof.errors, ...fallback.errors].filter((error, index, all) => all.findIndex((candidate) => candidate.message === error.message) ===
83
+ index);
84
+ return {
85
+ listeners: fallback.listeners,
86
+ errors: fallback.listeners.length > 0 ? fallback.errors : errors,
87
+ };
88
+ },
89
+ };
@@ -0,0 +1,170 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseNetstatOutput = parseNetstatOutput;
4
+ exports.parseTasklistCsv = parseTasklistCsv;
5
+ exports.parsePowerShellConnections = parsePowerShellConnections;
6
+ exports.findOnWindows = findOnWindows;
7
+ const exec_1 = require("../../utils/exec");
8
+ const lsof_1 = require("../lsof");
9
+ /** Parse `netstat -ano` output, keeping only TCP LISTENING sockets. */
10
+ function parseNetstatOutput(output, filterPort) {
11
+ const connections = [];
12
+ for (const line of output.split("\n")) {
13
+ const match = /^\s*TCP\s+(\S+)\s+(\S+)\s+LISTENING\s+(\d+)\s*$/i.exec(line);
14
+ if (!match) {
15
+ continue;
16
+ }
17
+ const local = match[1];
18
+ const endpoint = /^(.*):(\d+)$/.exec(local);
19
+ if (!endpoint) {
20
+ continue;
21
+ }
22
+ const port = Number.parseInt(endpoint[2], 10);
23
+ if (port < 1 || port > 65535) {
24
+ continue;
25
+ }
26
+ if (filterPort !== undefined && port !== filterPort) {
27
+ continue;
28
+ }
29
+ const pid = Number.parseInt(match[3], 10);
30
+ connections.push({
31
+ address: `${endpoint[1]}:${port}`,
32
+ port,
33
+ pid: Number.isInteger(pid) ? pid : null,
34
+ });
35
+ }
36
+ return connections;
37
+ }
38
+ /** Parse `tasklist /FO CSV /NH` output. */
39
+ function parseTasklistCsv(output) {
40
+ const entries = [];
41
+ for (const line of output.split(/\r?\n/)) {
42
+ if (!line.trim().startsWith('"')) {
43
+ continue;
44
+ }
45
+ const fields = line
46
+ .slice(1, line.lastIndexOf('"'))
47
+ .split('","')
48
+ .map((field) => field.replace(/""/g, '"'));
49
+ const pid = Number.parseInt(fields[1], 10);
50
+ if (!Number.isInteger(pid) || !fields[0]) {
51
+ continue;
52
+ }
53
+ entries.push({ pid, name: fields[0] });
54
+ }
55
+ return entries;
56
+ }
57
+ /** Parse ConvertTo-Json output from Get-NetTCPConnection. */
58
+ function parsePowerShellConnections(output, filterPort) {
59
+ const trimmed = output.trim();
60
+ if (!trimmed) {
61
+ return [];
62
+ }
63
+ let parsed;
64
+ try {
65
+ parsed = JSON.parse(trimmed);
66
+ }
67
+ catch {
68
+ return [];
69
+ }
70
+ const records = Array.isArray(parsed) ? parsed : [parsed];
71
+ const connections = [];
72
+ for (const record of records) {
73
+ const port = record.LocalPort;
74
+ const rawAddress = record.LocalAddress;
75
+ if (typeof port !== "number" ||
76
+ port < 1 ||
77
+ port > 65535 ||
78
+ typeof rawAddress !== "string") {
79
+ continue;
80
+ }
81
+ if (filterPort !== undefined && port !== filterPort) {
82
+ continue;
83
+ }
84
+ const address = rawAddress.includes(":")
85
+ ? `[${rawAddress}]:${port}`
86
+ : `${rawAddress}:${port}`;
87
+ connections.push({
88
+ address,
89
+ port,
90
+ pid: typeof record.OwningProcess === "number" ? record.OwningProcess : null,
91
+ });
92
+ }
93
+ return connections;
94
+ }
95
+ async function resolveProcessNames() {
96
+ const names = new Map();
97
+ const result = await (0, exec_1.runCommand)("tasklist", ["/FO", "CSV", "/NH"]);
98
+ if (!result.ok) {
99
+ return names;
100
+ }
101
+ for (const entry of parseTasklistCsv(result.stdout)) {
102
+ names.set(entry.pid, entry.name);
103
+ }
104
+ return names;
105
+ }
106
+ async function findWithNetstat(filterPort) {
107
+ // Do not pass "-p tcp": Windows then enumerates TCPv4 only and hides IPv6
108
+ // listeners. Without a protocol filter both address families are listed,
109
+ // and the parser keeps only TCP LISTENING rows.
110
+ const result = await (0, exec_1.runCommand)("netstat", ["-ano"]);
111
+ if (!result.ok) {
112
+ return null;
113
+ }
114
+ const names = await resolveProcessNames();
115
+ const listeners = parseNetstatOutput(result.stdout, filterPort).map((connection) => ({
116
+ pid: connection.pid,
117
+ name: connection.pid === null
118
+ ? "unknown"
119
+ : (names.get(connection.pid) ?? `PID ${connection.pid}`),
120
+ localAddress: connection.address,
121
+ port: connection.port,
122
+ protocol: "TCP",
123
+ }));
124
+ return { listeners: (0, lsof_1.dedupeListeners)(listeners), errors: [] };
125
+ }
126
+ async function findWithPowerShell(filterPort) {
127
+ const result = await (0, exec_1.runCommand)("powershell.exe", [
128
+ "-NoProfile",
129
+ "-NonInteractive",
130
+ "-Command",
131
+ "Get-NetTCPConnection -State Listen | Select-Object LocalAddress,LocalPort,OwningProcess | ConvertTo-Json -Compress",
132
+ ], { timeoutMs: 20000 });
133
+ if (!result.ok) {
134
+ return null;
135
+ }
136
+ const names = await resolveProcessNames();
137
+ const listeners = parsePowerShellConnections(result.stdout, filterPort).map((connection) => ({
138
+ pid: connection.pid,
139
+ name: connection.pid === null
140
+ ? "unknown"
141
+ : (names.get(connection.pid) ?? `PID ${connection.pid}`),
142
+ localAddress: connection.address,
143
+ port: connection.port,
144
+ protocol: "TCP",
145
+ }));
146
+ return { listeners: (0, lsof_1.dedupeListeners)(listeners), errors: [] };
147
+ }
148
+ async function findOnWindows(port) {
149
+ const netstat = await findWithNetstat(port);
150
+ if (netstat) {
151
+ return netstat;
152
+ }
153
+ const powershell = await findWithPowerShell(port);
154
+ if (powershell) {
155
+ return powershell;
156
+ }
157
+ const probe = await (0, exec_1.runCommand)("netstat", ["-ano"]);
158
+ const missing = (0, exec_1.isMissingCommand)(probe)
159
+ ? "netstat is not available"
160
+ : "netstat failed";
161
+ return {
162
+ listeners: [],
163
+ errors: [
164
+ {
165
+ code: "unavailable",
166
+ message: `Could not enumerate TCP listeners: ${missing} and PowerShell Get-NetTCPConnection is unavailable`,
167
+ },
168
+ ],
169
+ };
170
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,196 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ProcessNotFoundError = void 0;
4
+ exports.inspectProcess = inspectProcess;
5
+ exports.getProcessIdentity = getProcessIdentity;
6
+ const exec_1 = require("../utils/exec");
7
+ const platform_1 = require("../utils/platform");
8
+ class ProcessNotFoundError extends Error {
9
+ constructor(pid) {
10
+ super(`Process ${pid} is no longer running`);
11
+ this.name = "ProcessNotFoundError";
12
+ }
13
+ }
14
+ exports.ProcessNotFoundError = ProcessNotFoundError;
15
+ const LSTART = /(\w{3}\s+\w{3}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2}\s+\d{4})/;
16
+ function basename(value) {
17
+ return value.split(/[\\/]/).pop() || value;
18
+ }
19
+ function unixBasicRegex() {
20
+ return new RegExp(`^\\s*(\\d+)\\s+(\\d+)\\s+(\\S+)\\s+(\\S+)\\s+${LSTART.source}\\s+(.+)$`);
21
+ }
22
+ async function inspectUnix(process, pid) {
23
+ const basic = await (0, exec_1.runCommand)("ps", [
24
+ "-p",
25
+ String(pid),
26
+ "-o",
27
+ "pid=,ppid=,user=,stat=,lstart=,comm=",
28
+ ]);
29
+ if (!basic.ok) {
30
+ if ((0, exec_1.isMissingCommand)(basic)) {
31
+ throw new Error("The ps command is required for process inspection but was not found");
32
+ }
33
+ throw new ProcessNotFoundError(pid);
34
+ }
35
+ const line = basic.stdout.trim().split("\n")[0]?.trim() ?? "";
36
+ const match = unixBasicRegex().exec(line);
37
+ if (!match) {
38
+ throw new ProcessNotFoundError(pid);
39
+ }
40
+ const [, , parentPid, user, status, startTime, command] = match;
41
+ const argsResult = await (0, exec_1.runCommand)("ps", ["-p", String(pid), "-o", "args="]);
42
+ const commandLine = argsResult.ok ? argsResult.stdout.trim() : undefined;
43
+ return {
44
+ ...process,
45
+ pid,
46
+ name: basename(command) || process.name,
47
+ parentPid: Number.parseInt(parentPid, 10),
48
+ user: user === "-" ? undefined : user,
49
+ status,
50
+ startTime,
51
+ executablePath: command.includes("/") || command.includes("\\") ? command : undefined,
52
+ commandLine: commandLine || undefined,
53
+ };
54
+ }
55
+ async function inspectWindows(process, pid) {
56
+ const tasklist = await (0, exec_1.runCommand)("tasklist", [
57
+ "/FI",
58
+ `PID eq ${pid}`,
59
+ "/FO",
60
+ "CSV",
61
+ "/NH",
62
+ ]);
63
+ if (tasklist.ok && /No tasks are running/i.test(tasklist.stdout)) {
64
+ throw new ProcessNotFoundError(pid);
65
+ }
66
+ let name = process.name;
67
+ if (tasklist.ok) {
68
+ const nameMatch = /^"([^"]+)"/.exec(tasklist.stdout.trim());
69
+ if (nameMatch) {
70
+ name = nameMatch[1];
71
+ }
72
+ }
73
+ const script = `$p = Get-CimInstance Win32_Process -Filter 'ProcessId=${pid}'; if ($p) { $p | Select-Object ProcessId,ParentProcessId,Name,CommandLine,ExecutablePath,CreationDate | ConvertTo-Json -Compress } else { 'null' }`;
74
+ const cim = await (0, exec_1.runCommand)("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script],
75
+ // Cold CIM startup can exceed the default command timeout on Windows CI.
76
+ { timeoutMs: 20000 });
77
+ let details = null;
78
+ if (cim.ok && cim.stdout.trim() !== "null") {
79
+ try {
80
+ details = JSON.parse(cim.stdout.trim());
81
+ }
82
+ catch {
83
+ details = null;
84
+ }
85
+ }
86
+ if (!details && (!tasklist.ok || tasklist.stdout.trim() === "")) {
87
+ const alive = await systemIsAlive(pid);
88
+ if (!alive) {
89
+ throw new ProcessNotFoundError(pid);
90
+ }
91
+ }
92
+ return {
93
+ ...process,
94
+ pid,
95
+ name: details?.Name ?? name,
96
+ parentPid: details?.ParentProcessId,
97
+ executablePath: details?.ExecutablePath ?? undefined,
98
+ commandLine: details?.CommandLine ?? undefined,
99
+ startTime: details?.CreationDate ? String(details.CreationDate) : undefined,
100
+ };
101
+ }
102
+ /** Enrich a discovered listener with details that require a second lookup. */
103
+ async function inspectProcess(process) {
104
+ if (process.pid === null) {
105
+ return process;
106
+ }
107
+ const pid = process.pid;
108
+ const platform = (0, platform_1.detectPlatform)();
109
+ if (platform === "windows") {
110
+ return inspectWindows(process, pid);
111
+ }
112
+ return inspectUnix(process, pid);
113
+ }
114
+ async function systemIsAlive(pid) {
115
+ try {
116
+ process.kill(pid, 0);
117
+ return true;
118
+ }
119
+ catch (error) {
120
+ return error.code === "EPERM";
121
+ }
122
+ }
123
+ async function unixIdentity(pid) {
124
+ const result = await (0, exec_1.runCommand)("ps", [
125
+ "-p",
126
+ String(pid),
127
+ "-o",
128
+ "pid=,lstart=,comm=",
129
+ ]);
130
+ if (!result.ok) {
131
+ const alive = await systemIsAlive(pid);
132
+ if (!alive) {
133
+ return null;
134
+ }
135
+ throw new Error(result.stderr.trim() || "Could not verify the process identity with ps");
136
+ }
137
+ const match = /^\s*(\d+)\s+(\w{3}\s+\w{3}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2}\s+\d{4})\s+(.+)$/.exec(result.stdout.trim());
138
+ if (!match) {
139
+ return { pid, name: "" };
140
+ }
141
+ return {
142
+ pid,
143
+ name: basename(match[3].trim()),
144
+ startTime: match[2],
145
+ };
146
+ }
147
+ async function windowsTasklistIdentity(pid) {
148
+ const result = await (0, exec_1.runCommand)("tasklist", [
149
+ "/FI",
150
+ `PID eq ${pid}`,
151
+ "/FO",
152
+ "CSV",
153
+ "/NH",
154
+ ]);
155
+ if (!result.ok || /No tasks are running/i.test(result.stdout)) {
156
+ return null;
157
+ }
158
+ const match = /^"([^"]+)"/.exec(result.stdout.trim());
159
+ return match ? { pid, name: match[1] } : null;
160
+ }
161
+ async function windowsIdentity(pid) {
162
+ const script = `$p = Get-CimInstance Win32_Process -Filter 'ProcessId=${pid}'; if ($p) { $p | Select-Object ProcessId,Name,CreationDate | ConvertTo-Json -Compress } else { 'null' }`;
163
+ const result = await (0, exec_1.runCommand)("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script], { timeoutMs: 20000 });
164
+ if (result.ok && result.stdout.trim() === "null") {
165
+ // CIM positively reports that the PID no longer exists.
166
+ return null;
167
+ }
168
+ if (result.ok) {
169
+ try {
170
+ const parsed = JSON.parse(result.stdout.trim());
171
+ return {
172
+ pid,
173
+ name: parsed.Name ?? "",
174
+ startTime: parsed.CreationDate
175
+ ? String(parsed.CreationDate)
176
+ : undefined,
177
+ };
178
+ }
179
+ catch {
180
+ // Fall through to tasklist below.
181
+ }
182
+ }
183
+ // tasklist can still confirm the name after a CIM timeout, but it has no
184
+ // start-time marker. Termination treats that as unverifiable identity.
185
+ return windowsTasklistIdentity(pid);
186
+ }
187
+ /**
188
+ * Snapshot identity used to detect PID reuse. Returns null when the process
189
+ * no longer exists.
190
+ */
191
+ async function getProcessIdentity(pid) {
192
+ if ((0, platform_1.detectPlatform)() === "windows") {
193
+ return windowsIdentity(pid);
194
+ }
195
+ return unixIdentity(pid);
196
+ }