@jini-ai/platform 0.7.2 → 0.7.3-next.1
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/CHANGELOG.md +2 -8
- package/README.md +16 -4
- package/dist/asset-cache.d.ts +13 -3
- package/dist/asset-cache.js +163 -154
- package/dist/blob-storage.d.ts +3 -32
- package/dist/blob-storage.js +1 -9
- package/dist/child-environment.d.ts +0 -16
- package/dist/child-environment.js +0 -25
- package/dist/command.d.ts +6 -11
- package/dist/command.js +8 -54
- package/dist/download-lock.d.ts +4 -0
- package/dist/download-lock.js +82 -0
- package/dist/download-maintenance.d.ts +5 -0
- package/dist/download-maintenance.js +82 -0
- package/dist/download-state.d.ts +8 -0
- package/dist/download-state.js +126 -0
- package/dist/download-store.d.ts +22 -0
- package/dist/download-store.js +174 -0
- package/dist/download-target.d.ts +10 -0
- package/dist/download-target.js +102 -0
- package/dist/download-transfer.d.ts +12 -0
- package/dist/download-transfer.js +174 -0
- package/dist/download-types.d.ts +162 -0
- package/dist/download-types.js +31 -0
- package/dist/download.d.ts +1 -89
- package/dist/download.js +8 -738
- package/dist/fetch-with-timeout.d.ts +7 -32
- package/dist/fetch-with-timeout.js +1 -77
- package/dist/fs/app-data-root.d.ts +28 -0
- package/dist/fs/app-data-root.js +35 -0
- package/dist/fs/atomic-write.js +1 -1
- package/dist/fs/boot-identity.d.ts +1 -4
- package/dist/fs/directory-delete-guard.d.ts +93 -0
- package/dist/fs/directory-delete-guard.js +148 -0
- package/dist/fs/directory-registry.js +45 -35
- package/dist/fs/directory-relocation.d.ts +82 -0
- package/dist/fs/directory-relocation.js +99 -0
- package/dist/fs/directory-running-lock.d.ts +1 -1
- package/dist/fs/directory-running-lock.js +24 -21
- package/dist/fs/directory-sync.js +1 -1
- package/dist/fs/directory-user-config.js +30 -3
- package/dist/fs/directory-workspace.d.ts +34 -30
- package/dist/fs/directory-workspace.js +70 -29
- package/dist/fs/durable-json.d.ts +6 -15
- package/dist/fs/durable-json.js +38 -35
- package/dist/fs/errno.d.ts +12 -3
- package/dist/fs/errno.js +5 -3
- package/dist/fs/file-lock.d.ts +3 -87
- package/dist/fs/file-lock.js +16 -30
- package/dist/fs/guarded-reader.js +335 -315
- package/dist/fs/index.d.ts +5 -0
- package/dist/fs/index.js +5 -0
- package/dist/fs/recent-directories.d.ts +46 -0
- package/dist/fs/recent-directories.js +68 -0
- package/dist/fs/remove-directory-tree.d.ts +20 -0
- package/dist/fs/remove-directory-tree.js +28 -0
- package/dist/fs/user-data-directories.js +2 -2
- package/dist/fs/workspace-directory.js +2 -1
- package/dist/fs.d.ts +16 -4
- package/dist/fs.js +4 -4
- package/dist/home-expansion.d.ts +7 -2
- package/dist/home-expansion.js +3 -3
- package/dist/http/guarded/client.d.ts +1 -2
- package/dist/http/guarded/client.js +2 -1
- package/dist/http/guarded/index.d.ts +0 -3
- package/dist/http/guarded/node-ports.d.ts +1 -1
- package/dist/http/guarded/transport.fetch.d.ts +2 -3
- package/dist/http/guarded/transport.fetch.js +64 -58
- package/dist/http.d.ts +3 -1
- package/dist/http.js +2 -2
- package/dist/index.d.ts +10 -11
- package/dist/index.js +7 -6
- package/dist/mail/activity/activity.d.ts +136 -0
- package/dist/mail/activity/activity.js +172 -0
- package/dist/mail/activity/ports.d.ts +113 -0
- package/dist/mail/activity/suppressions.d.ts +82 -0
- package/dist/mail/activity/suppressions.js +119 -0
- package/dist/mail/activity/vocabulary.d.ts +10 -0
- package/dist/mail/activity/vocabulary.js +8 -0
- package/dist/mail/builtin-providers.d.ts +12 -6
- package/dist/mail/builtin-providers.js +14 -11
- package/dist/mail/delivery-wrapper.js +2 -1
- package/dist/mail/email-sender-registry.d.ts +1 -1
- package/dist/mail/email-sender-registry.js +1 -1
- package/dist/mail/email-template-operations.d.ts +186 -0
- package/dist/mail/email-template-operations.js +226 -0
- package/dist/mail/email-template.d.ts +120 -0
- package/dist/mail/email-template.js +243 -0
- package/dist/mail/index.d.ts +4 -0
- package/dist/mail/index.js +3 -0
- package/dist/mail/prepare-sender-email.d.ts +1 -10
- package/dist/mail/prepare-sender-email.js +1 -11
- package/dist/mail/resolve-mailer.d.ts +2 -1
- package/dist/mail/resolve-mailer.js +5 -2
- package/dist/mail/senders.d.ts +0 -1
- package/dist/mail/senders.js +0 -1
- package/dist/mail/smtp.d.ts +1 -31
- package/dist/net/address.d.ts +1 -8
- package/dist/net/address.js +1 -18
- package/dist/net/index.d.ts +1 -1
- package/dist/net/index.js +1 -1
- package/dist/net/local-http-probe.js +1 -1
- package/dist/net/local-http-request.js +1 -1
- package/dist/process-probes.d.ts +36 -0
- package/dist/process-probes.js +151 -0
- package/dist/process-top-footprint.d.ts +7 -0
- package/dist/process-top-footprint.js +30 -0
- package/dist/process.d.ts +29 -31
- package/dist/process.js +18 -196
- package/dist/proxy-env.d.ts +12 -3
- package/dist/proxy-env.js +9 -8
- package/dist/resource-paths.d.ts +15 -3
- package/dist/resource-paths.js +7 -5
- package/dist/sandbox-env.d.ts +26 -5
- package/dist/sandbox-env.js +7 -7
- package/dist/secrets/credential-sets/contracts.d.ts +0 -1
- package/dist/secrets/credential-sets/contracts.js +0 -1
- package/dist/secrets/credential-sets/index.d.ts +2 -3
- package/dist/secrets/credential-sets/index.js +1 -1
- package/dist/secrets/credential-sets/provider-matches.d.ts +1 -1
- package/dist/secrets/credential-sets/provider-matches.js +1 -1
- package/dist/secrets/credential-sets/vault-archive.d.ts +1 -1
- package/dist/secrets/credential-sets/vault-archive.js +14 -8
- package/dist/secrets/credential-sets/vault.aad.d.ts +1 -1
- package/dist/secrets/credential-sets/vault.meta.d.ts +1 -1
- package/dist/secrets/credential-sets/vault.meta.js +1 -1
- package/dist/secrets/credential-sets/vault.repo.memory.d.ts +1 -1
- package/dist/secrets/credential-sets/vault.repo.memory.js +1 -1
- package/dist/secrets/credential-sets/vault.reseal-refused.d.ts +23 -0
- package/dist/secrets/credential-sets/vault.reseal-refused.js +36 -0
- package/dist/secrets/credential-sets/vault.service.d.ts +25 -5
- package/dist/secrets/credential-sets/vault.service.js +42 -8
- package/dist/secrets/index.d.ts +0 -3
- package/dist/secrets/index.js +5 -0
- package/dist/secrets/keyring.env.d.ts +1 -1
- package/dist/secrets/legacy-owner.d.ts +61 -0
- package/dist/secrets/legacy-owner.js +196 -0
- package/dist/secrets/root-key/decide.d.ts +89 -0
- package/dist/secrets/root-key/decide.js +60 -0
- package/dist/secrets/sealer-contract.d.ts +19 -0
- package/dist/secrets/sealer-contract.js +37 -0
- package/dist/secrets/secret-sealer.aesgcm.d.ts +1 -1
- package/dist/secrets/testing.d.ts +1 -0
- package/dist/secrets/testing.js +1 -0
- package/dist/shell.d.ts +4 -1
- package/dist/shell.js +1 -1
- package/dist/system.d.ts +6 -0
- package/dist/system.js +9 -0
- package/dist/terminal.d.ts +11 -96
- package/dist/terminal.js +80 -56
- package/dist/web/agent-tools.d.ts +107 -0
- package/dist/web/agent-tools.js +49 -0
- package/dist/web/index.d.ts +1 -0
- package/dist/web/index.js +1 -0
- package/package.json +38 -12
- package/dist/http/guarded/ports.d.ts +0 -56
- package/dist/http/guarded/types.d.ts +0 -8
- package/dist/http/guarded/types.js +0 -2
- package/dist/mail/email-sender.d.ts +0 -109
- package/dist/mail/email-sender.js +0 -10
- package/dist/net/endpoint-policy.d.ts +0 -39
- package/dist/net/endpoint-policy.js +0 -218
- package/dist/secrets/credential-sets/aad.d.ts +0 -7
- package/dist/secrets/credential-sets/aad.js +0 -7
- package/dist/secrets/credential-sets/repo.memory.d.ts +0 -44
- package/dist/secrets/credential-sets/repo.memory.js +0 -80
- package/dist/secrets/credential-sets/vault.types.d.ts +0 -27
- package/dist/secrets/credential-sets/vault.types.js +0 -49
- /package/dist/{http/guarded → mail/activity}/ports.js +0 -0
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { posix, win32 } from "node:path";
|
|
2
|
+
import { captureLineTail } from "@jini-ai/core/text";
|
|
3
|
+
import { windowsPowerShell } from "./windows-system-tools.js";
|
|
4
|
+
import { execFileBuffered } from "./shell.js";
|
|
5
|
+
/** @internal Parse `ps -axo pid=,ppid=,command=` output into process snapshots. */
|
|
6
|
+
function parsePsOutput(stdout) {
|
|
7
|
+
return stdout
|
|
8
|
+
.split(/\r?\n/)
|
|
9
|
+
.map((line) => {
|
|
10
|
+
// Same as /^\s*(\d+)\s+(\d+)\s+(.+)$/, split so the command tail cannot backtrack.
|
|
11
|
+
const match = /^\s*(\d+)\s+(\d+)/.exec(line);
|
|
12
|
+
const command = match ? captureLineTail({ rest: line.slice(match[0].length) }, { minWhitespace: 1 }) : null;
|
|
13
|
+
if (!match || command === null)
|
|
14
|
+
return null;
|
|
15
|
+
return { pid: Number(match[1]), ppid: Number(match[2]), command };
|
|
16
|
+
})
|
|
17
|
+
.filter((snapshot) => snapshot != null);
|
|
18
|
+
}
|
|
19
|
+
/** @internal Enumerate process snapshots on POSIX via `ps`. */
|
|
20
|
+
export async function listPosixProcessSnapshots(input, options) {
|
|
21
|
+
// Fixed process-enumeration utility intentionally uses the trusted host PATH; command and argv are code-owned.
|
|
22
|
+
const stdout = await processProbeOutput({ command: "ps", run: input.run ?? execFileBuffered,
|
|
23
|
+
args: ["-axo", options.commandLines === false ? "pid=,ppid=,comm=" : "pid=,ppid=,command="],
|
|
24
|
+
}, options);
|
|
25
|
+
return parsePsOutput(stdout ?? "");
|
|
26
|
+
}
|
|
27
|
+
/** @internal Enumerate process snapshots on Windows via `Get-CimInstance Win32_Process` JSON. */
|
|
28
|
+
export async function listWindowsProcessSnapshots(input, options) {
|
|
29
|
+
const field = options.commandLines === false ? "Name" : "CommandLine";
|
|
30
|
+
const command = [
|
|
31
|
+
"$ErrorActionPreference = 'Stop'",
|
|
32
|
+
`Get-CimInstance Win32_Process | Select-Object ProcessId, ParentProcessId, ${field} | ConvertTo-Json -Compress`,
|
|
33
|
+
].join("; ");
|
|
34
|
+
const stdout = await processProbeOutput({ command: windowsPowerShell(), run: input.run ?? execFileBuffered,
|
|
35
|
+
args: ["-NoProfile", "-NonInteractive", "-Command", command],
|
|
36
|
+
}, options);
|
|
37
|
+
const payload = stdout?.trim();
|
|
38
|
+
if (!payload)
|
|
39
|
+
return [];
|
|
40
|
+
const records = JSON.parse(payload);
|
|
41
|
+
return (Array.isArray(records) ? records : [records])
|
|
42
|
+
.map((record) => {
|
|
43
|
+
const pid = Number(record.ProcessId);
|
|
44
|
+
const ppid = Number(record.ParentProcessId);
|
|
45
|
+
const commandLine = options.commandLines === false ? record.Name?.trim() ?? "" : record.CommandLine?.trim();
|
|
46
|
+
if (commandLine == null || Number.isNaN(pid) || Number.isNaN(ppid))
|
|
47
|
+
return null;
|
|
48
|
+
if (options.commandLines !== false && !commandLine)
|
|
49
|
+
return null;
|
|
50
|
+
return { command: commandLine, pid, ppid };
|
|
51
|
+
})
|
|
52
|
+
.filter((snapshot) => snapshot != null);
|
|
53
|
+
}
|
|
54
|
+
/** @internal Decode ps cumulative CPU time, including macOS fractional seconds and days. */
|
|
55
|
+
function parseCpuTime(value) {
|
|
56
|
+
const match = value.match(/^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+(?:\.\d+)?)$/);
|
|
57
|
+
if (!match)
|
|
58
|
+
return NaN;
|
|
59
|
+
return Number(match[1] ?? 0) * 86400 + Number(match[2] ?? 0) * 3600
|
|
60
|
+
+ Number(match[3]) * 60 + Number(match[4]);
|
|
61
|
+
}
|
|
62
|
+
/** @internal Reject incomplete metrics instead of presenting missing usage as zero. */
|
|
63
|
+
function validProcessUsage(usage) {
|
|
64
|
+
const { pid, ppid, rssBytes, cpuSeconds } = usage;
|
|
65
|
+
return [pid, ppid].every(Number.isSafeInteger) && [rssBytes, cpuSeconds].every(Number.isFinite)
|
|
66
|
+
&& [pid, ppid, rssBytes, cpuSeconds].every((value) => value >= 0);
|
|
67
|
+
}
|
|
68
|
+
/** @internal Read only comm, never args/command, so credentials cannot enter the result. */
|
|
69
|
+
export function parsePsUsage(stdout) {
|
|
70
|
+
return stdout.split(/\r?\n/).flatMap((line) => {
|
|
71
|
+
const match = line.match(/^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(\S.*)$/);
|
|
72
|
+
if (!match)
|
|
73
|
+
return [];
|
|
74
|
+
const usage = {
|
|
75
|
+
pid: Number(match[1]), ppid: Number(match[2]), rssBytes: Number(match[3]) * 1024,
|
|
76
|
+
cpuSeconds: parseCpuTime(match[4]), name: posix.basename(match[5].trim()),
|
|
77
|
+
};
|
|
78
|
+
return validProcessUsage(usage) ? [usage] : [];
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
/** @internal CIM serializes numeric fields as numbers or strings; null is not zero usage. */
|
|
82
|
+
function cimNumber(value) {
|
|
83
|
+
if (typeof value === "number")
|
|
84
|
+
return value;
|
|
85
|
+
return typeof value === "string" && value.trim() ? Number(value) : NaN;
|
|
86
|
+
}
|
|
87
|
+
/** @internal Convert Windows 100ns CPU counters and retain nameless process rows. */
|
|
88
|
+
export function parseCimUsage(stdout) {
|
|
89
|
+
if (!stdout.trim())
|
|
90
|
+
return [];
|
|
91
|
+
const payload = JSON.parse(stdout);
|
|
92
|
+
return (Array.isArray(payload) ? payload : [payload]).flatMap((record) => {
|
|
93
|
+
if (!record || typeof record !== "object")
|
|
94
|
+
return [];
|
|
95
|
+
const row = record;
|
|
96
|
+
const usage = {
|
|
97
|
+
pid: cimNumber(row.ProcessId), ppid: cimNumber(row.ParentProcessId),
|
|
98
|
+
rssBytes: cimNumber(row.WorkingSetSize),
|
|
99
|
+
cpuSeconds: (cimNumber(row.UserModeTime) + cimNumber(row.KernelModeTime)) / 10_000_000,
|
|
100
|
+
name: typeof row.Name === "string" ? win32.basename(row.Name.trim()) : "",
|
|
101
|
+
};
|
|
102
|
+
return validProcessUsage(usage) ? [usage] : [];
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
/** @internal Fixed executable and argv, invoked directly without a command shell. */
|
|
106
|
+
export function processUsageCommand(windows) {
|
|
107
|
+
return windows
|
|
108
|
+
? { command: windowsPowerShell(), args: ["-NoProfile", "-NonInteractive", "-Command",
|
|
109
|
+
"$ErrorActionPreference = 'Stop'; Get-CimInstance Win32_Process | Select-Object ProcessId, ParentProcessId, WorkingSetSize, UserModeTime, KernelModeTime, Name | ConvertTo-Json -Compress"] }
|
|
110
|
+
: { command: "ps", args: ["-axo", "pid=,ppid=,rss=,time=,comm="] };
|
|
111
|
+
}
|
|
112
|
+
/** @internal One bounded read-only OS probe; partial output on failure is discarded. */
|
|
113
|
+
export async function processProbeOutput(input, options) {
|
|
114
|
+
try {
|
|
115
|
+
const result = await input.run(input.command, input.args, {
|
|
116
|
+
encoding: "utf8", timeout: options.timeoutMs ?? 5000, maxBuffer: 8 * 1024 * 1024, windowsHide: true,
|
|
117
|
+
});
|
|
118
|
+
return result.ok ? result.stdout : null;
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
/** @internal Performance instance names can reorder (node, node#1); only IDProcess is identity. */
|
|
125
|
+
export function parsePrivateWorkingSets({ stdout }) {
|
|
126
|
+
const readings = new Map();
|
|
127
|
+
try {
|
|
128
|
+
const payload = JSON.parse(stdout ?? "null");
|
|
129
|
+
for (const record of Array.isArray(payload) ? payload : [payload]) {
|
|
130
|
+
if (!record || typeof record !== "object")
|
|
131
|
+
continue;
|
|
132
|
+
const row = record;
|
|
133
|
+
const pid = cimNumber(row.IDProcess);
|
|
134
|
+
const bytes = cimNumber(row.WorkingSetPrivate);
|
|
135
|
+
if (!validSamplePid(pid))
|
|
136
|
+
continue;
|
|
137
|
+
readings.set(pid, Number.isSafeInteger(bytes) && bytes >= 0 ? bytes : null);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
catch { /* Malformed/absent counters are unavailable, never zero. */ }
|
|
141
|
+
return readings;
|
|
142
|
+
}
|
|
143
|
+
const validSamplePid = (pid) => Number.isSafeInteger(pid) && pid > 0;
|
|
144
|
+
/** @internal Reject invalid identities and oversized collections before making any OS calls. */
|
|
145
|
+
export function assertPrivateMemorySample({ pids, maxPids }) {
|
|
146
|
+
if (!pids.every(validSamplePid))
|
|
147
|
+
throw new RangeError("invalid process PID");
|
|
148
|
+
if (!Number.isSafeInteger(maxPids) || maxPids < 1 || pids.length > maxPids)
|
|
149
|
+
throw new RangeError("process sample exceeds PID limit");
|
|
150
|
+
}
|
|
151
|
+
//# sourceMappingURL=process-probes.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { ProcessPrivateMemory } from "./process.js";
|
|
2
|
+
/** Only the requested PID table is trusted; duplicate rows invalidate that PID. O(text length + p) space/time. */
|
|
3
|
+
export declare function topReadings({ text, pids }: {
|
|
4
|
+
text: string;
|
|
5
|
+
pids: readonly number[];
|
|
6
|
+
}, _options?: {}): ProcessPrivateMemory['readings'];
|
|
7
|
+
//# sourceMappingURL=process-top-footprint.d.ts.map
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/** top uses binary K/M/G and may append a change marker. Invalid/unsafe values stay unknown. O(1). */
|
|
2
|
+
function topBytes({ text }, _options = {}) {
|
|
3
|
+
const match = /^(\d+(?:\.\d+)?)([BKMG])[+-]?$/.exec(text);
|
|
4
|
+
if (!match || match[2] === undefined)
|
|
5
|
+
return null;
|
|
6
|
+
const scale = { B: 1, K: 1024, M: 1024 ** 2, G: 1024 ** 3 };
|
|
7
|
+
const multiplier = scale[match[2]];
|
|
8
|
+
if (multiplier === undefined)
|
|
9
|
+
return null;
|
|
10
|
+
const bytes = Math.round(Number(match[1]) * multiplier);
|
|
11
|
+
return Number.isSafeInteger(bytes) ? bytes : null;
|
|
12
|
+
}
|
|
13
|
+
/** Only the requested PID table is trusted; duplicate rows invalidate that PID. O(text length + p) space/time. */
|
|
14
|
+
export function topReadings({ text, pids }, _options = {}) {
|
|
15
|
+
const readings = new Map();
|
|
16
|
+
const lines = text.split(/\r?\n/);
|
|
17
|
+
const header = lines.findIndex(line => /^\s*PID\s+MEM\s*$/.test(line));
|
|
18
|
+
const table = header < 0 ? [] : lines.slice(header + 1);
|
|
19
|
+
const requested = new Set(pids);
|
|
20
|
+
for (const line of table) {
|
|
21
|
+
const row = /^\s*(\d+)\s+(\S+)\s*$/.exec(line);
|
|
22
|
+
if (!row || row[2] === undefined)
|
|
23
|
+
continue;
|
|
24
|
+
const pid = Number(row[1]);
|
|
25
|
+
if (requested.has(pid))
|
|
26
|
+
readings.set(pid, readings.has(pid) ? null : topBytes({ text: row[2] }));
|
|
27
|
+
}
|
|
28
|
+
return pids.map(pid => ({ pid, bytes: readings.get(pid) ?? null }));
|
|
29
|
+
}
|
|
30
|
+
//# sourceMappingURL=process-top-footprint.js.map
|
package/dist/process.d.ts
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
* executor for bounded usage samples; keeps a private `errorCode` copy.
|
|
12
12
|
*/
|
|
13
13
|
import { type ChildProcess } from "node:child_process";
|
|
14
|
-
import {
|
|
14
|
+
import type { CommandInvocationRequest, ProcessSnapshot, StopProcessesResult } from "@jini-ai/core/contracts/runtime";
|
|
15
15
|
import { execFileBuffered } from "./shell.js";
|
|
16
16
|
export type ProcessStampShape = object;
|
|
17
17
|
export type ProcessStampField<TStamp extends ProcessStampShape> = Extract<keyof TStamp, string>;
|
|
@@ -28,11 +28,6 @@ export type SpawnProcessRequest = CommandInvocationRequest & {
|
|
|
28
28
|
detached?: boolean;
|
|
29
29
|
logFd?: number | null;
|
|
30
30
|
};
|
|
31
|
-
export type ProcessSnapshot = {
|
|
32
|
-
command: string;
|
|
33
|
-
pid: number;
|
|
34
|
-
ppid: number;
|
|
35
|
-
};
|
|
36
31
|
/** Display-only usage: RSS is bytes; CPU is cumulative seconds across all cores. */
|
|
37
32
|
export type ProcessUsage = {
|
|
38
33
|
pid: number;
|
|
@@ -58,13 +53,6 @@ export type ProcessPrivateMemory = {
|
|
|
58
53
|
}>;
|
|
59
54
|
};
|
|
60
55
|
export type StampedProcessMatchCriteria<TStamp extends ProcessStampShape> = Partial<TStamp>;
|
|
61
|
-
export type StopProcessesResult = {
|
|
62
|
-
alreadyStopped: boolean;
|
|
63
|
-
forcedPids: number[];
|
|
64
|
-
matchedPids: number[];
|
|
65
|
-
remainingPids: number[];
|
|
66
|
-
stoppedPids: number[];
|
|
67
|
-
};
|
|
68
56
|
/**
|
|
69
57
|
* Serialize a process stamp into `--flag=value` CLI arguments per the contract.
|
|
70
58
|
* Every stamp field must normalize to a string or an error is thrown.
|
|
@@ -73,7 +61,10 @@ export type StopProcessesResult = {
|
|
|
73
61
|
* @param contract - The stamp contract providing field list, flags, and normalization.
|
|
74
62
|
* @returns The `--flag=value` argument strings, one per stamp field.
|
|
75
63
|
*/
|
|
76
|
-
export declare function createProcessStampArgs<TStamp extends ProcessStampShape>(stamp
|
|
64
|
+
export declare function createProcessStampArgs<TStamp extends ProcessStampShape>({ stamp, contract }: {
|
|
65
|
+
stamp: TStamp;
|
|
66
|
+
contract: ProcessStampContract<TStamp>;
|
|
67
|
+
}, _optional?: Record<string, never>): string[];
|
|
77
68
|
/**
|
|
78
69
|
* Read the value of a CLI flag from an argument list, supporting both the
|
|
79
70
|
* `--flag value` and inline `--flag=value` forms.
|
|
@@ -82,7 +73,10 @@ export declare function createProcessStampArgs<TStamp extends ProcessStampShape>
|
|
|
82
73
|
* @param flagName - The flag name (including any leading dashes).
|
|
83
74
|
* @returns The flag's value, or `null` when the flag is absent.
|
|
84
75
|
*/
|
|
85
|
-
export declare function readFlagValue(args
|
|
76
|
+
export declare function readFlagValue({ args, flagName }: {
|
|
77
|
+
args: readonly string[];
|
|
78
|
+
flagName: string;
|
|
79
|
+
}, _optional?: Record<string, never>): string | null;
|
|
86
80
|
/**
|
|
87
81
|
* Decode a process stamp from a raw argument list per the contract, returning
|
|
88
82
|
* `null` when normalization fails (e.g. a required field is missing).
|
|
@@ -91,7 +85,10 @@ export declare function readFlagValue(args: readonly string[], flagName: string)
|
|
|
91
85
|
* @param contract - The stamp contract providing field list, flags, and normalization.
|
|
92
86
|
* @returns The decoded stamp, or `null` when it cannot be normalized.
|
|
93
87
|
*/
|
|
94
|
-
export declare function readProcessStamp<TStamp extends ProcessStampShape>(args
|
|
88
|
+
export declare function readProcessStamp<TStamp extends ProcessStampShape>({ args, contract }: {
|
|
89
|
+
args: readonly string[];
|
|
90
|
+
contract: ProcessStampContract<TStamp>;
|
|
91
|
+
}, _optional?: Record<string, never>): TStamp | null;
|
|
95
92
|
/**
|
|
96
93
|
* Decode a process stamp from a full command-line string by tokenizing it first.
|
|
97
94
|
*
|
|
@@ -99,7 +96,10 @@ export declare function readProcessStamp<TStamp extends ProcessStampShape>(args:
|
|
|
99
96
|
* @param contract - The stamp contract providing field list, flags, and normalization.
|
|
100
97
|
* @returns The decoded stamp, or `null` when it cannot be normalized.
|
|
101
98
|
*/
|
|
102
|
-
export declare function readProcessStampFromCommand<TStamp extends ProcessStampShape>(command
|
|
99
|
+
export declare function readProcessStampFromCommand<TStamp extends ProcessStampShape>({ command, contract }: {
|
|
100
|
+
command: string;
|
|
101
|
+
contract: ProcessStampContract<TStamp>;
|
|
102
|
+
}, _optional?: Record<string, never>): TStamp | null;
|
|
103
103
|
/**
|
|
104
104
|
* Test whether a stamp matches criteria: every criterion field that is set must
|
|
105
105
|
* equal the corresponding normalized stamp field; unset criteria fields match
|
|
@@ -110,7 +110,11 @@ export declare function readProcessStampFromCommand<TStamp extends ProcessStampS
|
|
|
110
110
|
* @param contract - The stamp contract providing field list and normalization.
|
|
111
111
|
* @returns `true` when every specified criterion matches the stamp.
|
|
112
112
|
*/
|
|
113
|
-
export declare function matchesProcessStamp<TStamp extends ProcessStampShape, TCriteria extends Partial<TStamp> = Partial<TStamp>>(stamp
|
|
113
|
+
export declare function matchesProcessStamp<TStamp extends ProcessStampShape, TCriteria extends Partial<TStamp> = Partial<TStamp>>({ stamp, criteria, contract }: {
|
|
114
|
+
stamp: TStamp;
|
|
115
|
+
criteria: TCriteria | undefined;
|
|
116
|
+
contract: ProcessStampContract<TStamp, TCriteria>;
|
|
117
|
+
}, _optional?: Record<string, never>): boolean;
|
|
114
118
|
/**
|
|
115
119
|
* Test whether a process snapshot's command line carries a stamp matching the
|
|
116
120
|
* criteria. Combines stamp decoding from the command with `matchesProcessStamp`.
|
|
@@ -120,7 +124,11 @@ export declare function matchesProcessStamp<TStamp extends ProcessStampShape, TC
|
|
|
120
124
|
* @param contract - The stamp contract providing field list and normalization.
|
|
121
125
|
* @returns `true` when the command carries a decodable stamp that matches.
|
|
122
126
|
*/
|
|
123
|
-
export declare function matchesStampedProcess<TStamp extends ProcessStampShape, TCriteria extends Partial<TStamp> = Partial<TStamp>>(processInfo
|
|
127
|
+
export declare function matchesStampedProcess<TStamp extends ProcessStampShape, TCriteria extends Partial<TStamp> = Partial<TStamp>>({ processInfo, criteria, contract }: {
|
|
128
|
+
processInfo: Pick<ProcessSnapshot, "command">;
|
|
129
|
+
criteria: TCriteria | undefined;
|
|
130
|
+
contract: ProcessStampContract<TStamp, TCriteria>;
|
|
131
|
+
}, _optional?: Record<string, never>): boolean;
|
|
124
132
|
/**
|
|
125
133
|
* Spawn a detached background process, wait for it to actually start, then
|
|
126
134
|
* `unref` it so the parent can exit independently.
|
|
@@ -186,13 +194,13 @@ export declare function parseProcessFootprint({ text }: {
|
|
|
186
194
|
text: string;
|
|
187
195
|
}, _options?: {}): number | null;
|
|
188
196
|
/**
|
|
189
|
-
* Read private memory
|
|
197
|
+
* Read private memory for unique PIDs, without attaching an inspector or changing target state.
|
|
190
198
|
* macOS uses physical footprint; Windows uses private working set joined by PID, never PrivateBytes
|
|
191
199
|
* or Win32_Process.WorkingSetSize. Failed probes return null; invalid PIDs/limits throw RangeError.
|
|
192
200
|
* @param input - Requested PIDs and optional host platform/bounded execution port.
|
|
193
201
|
* @param options - Per-probe timeout (5000ms) and unique-PID limit (512); excess is rejected.
|
|
194
202
|
* @returns Accurately labeled bytes, including a null row for every unavailable PID.
|
|
195
|
-
* @complexity O(n) output space for n unique PIDs; macOS makes
|
|
203
|
+
* @complexity O(n) output space for n unique PIDs; macOS makes one bounded `top` read,
|
|
196
204
|
* Windows makes one bounded bulk probe plus O(m) parsing space for m host processes.
|
|
197
205
|
* @example await sampleProcessPrivateMemory({ pids: [123] }, { timeoutMs: 10000 })
|
|
198
206
|
*/
|
|
@@ -201,16 +209,6 @@ export declare function sampleProcessPrivateMemory(input: ProcessUsagePorts & {
|
|
|
201
209
|
}, options?: ProcessUsageOptions & {
|
|
202
210
|
maxPids?: number;
|
|
203
211
|
}): Promise<ProcessPrivateMemory>;
|
|
204
|
-
/**
|
|
205
|
-
* Collect the transitive set of descendant PIDs (including the roots) from a
|
|
206
|
-
* process snapshot list, returned sorted by numeric PID descending for deterministic ordering.
|
|
207
|
-
* PID reuse and wraparound mean this does not guarantee children precede parents.
|
|
208
|
-
*
|
|
209
|
-
* @param processes - The full process snapshot list to walk.
|
|
210
|
-
* @param rootPids - The root PIDs whose subtrees to collect (non-numbers ignored).
|
|
211
|
-
* @returns The unique PIDs of the roots and all their descendants, descending.
|
|
212
|
-
*/
|
|
213
|
-
export declare function collectProcessTreePids(processes: ProcessSnapshot[], rootPids: Array<number | null | undefined>): number[];
|
|
214
212
|
/**
|
|
215
213
|
* Stop a set of PIDs with escalation: SIGTERM, wait, then SIGKILL any
|
|
216
214
|
* survivors. Excludes the current process and de-duplicates the input.
|
package/dist/process.js
CHANGED
|
@@ -11,12 +11,12 @@
|
|
|
11
11
|
* executor for bounded usage samples; keeps a private `errorCode` copy.
|
|
12
12
|
*/
|
|
13
13
|
import { spawn } from "node:child_process";
|
|
14
|
-
import { posix, win32 } from "node:path";
|
|
15
14
|
import { setTimeout as sleep } from "node:timers/promises";
|
|
16
|
-
import { captureLineTail } from "@jini-ai/core/text";
|
|
17
15
|
import { windowsPowerShell } from "./windows-system-tools.js";
|
|
18
16
|
import { createCommandInvocation } from "./command.js";
|
|
19
17
|
import { execFileBuffered } from "./shell.js";
|
|
18
|
+
import { topReadings } from "./process-top-footprint.js";
|
|
19
|
+
import { listPosixProcessSnapshots, listWindowsProcessSnapshots, parsePsUsage, parseCimUsage, processUsageCommand, processProbeOutput, parsePrivateWorkingSets, assertPrivateMemorySample } from "./process-probes.js";
|
|
20
20
|
/** @internal Extract a Node `error.code` as a string, or `null` when the value carries no code. */
|
|
21
21
|
function errorCode(error) {
|
|
22
22
|
if (typeof error !== "object" || error == null || !("code" in error))
|
|
@@ -32,7 +32,7 @@ function errorCode(error) {
|
|
|
32
32
|
* @param contract - The stamp contract providing field list, flags, and normalization.
|
|
33
33
|
* @returns The `--flag=value` argument strings, one per stamp field.
|
|
34
34
|
*/
|
|
35
|
-
export function createProcessStampArgs(stamp, contract) {
|
|
35
|
+
export function createProcessStampArgs({ stamp, contract }, _optional = {}) {
|
|
36
36
|
const normalized = contract.normalizeStamp(stamp);
|
|
37
37
|
return contract.stampFields.map((field) => {
|
|
38
38
|
const value = normalized[field];
|
|
@@ -54,7 +54,7 @@ function commandArgs(command) {
|
|
|
54
54
|
* @param flagName - The flag name (including any leading dashes).
|
|
55
55
|
* @returns The flag's value, or `null` when the flag is absent.
|
|
56
56
|
*/
|
|
57
|
-
export function readFlagValue(args, flagName) {
|
|
57
|
+
export function readFlagValue({ args, flagName }, _optional = {}) {
|
|
58
58
|
const inlinePrefix = `${flagName}=`;
|
|
59
59
|
for (let index = 0; index < args.length; index += 1) {
|
|
60
60
|
const argument = args[index];
|
|
@@ -74,9 +74,9 @@ export function readFlagValue(args, flagName) {
|
|
|
74
74
|
* @param contract - The stamp contract providing field list, flags, and normalization.
|
|
75
75
|
* @returns The decoded stamp, or `null` when it cannot be normalized.
|
|
76
76
|
*/
|
|
77
|
-
export function readProcessStamp(args, contract) {
|
|
77
|
+
export function readProcessStamp({ args, contract }, _optional = {}) {
|
|
78
78
|
try {
|
|
79
|
-
const input = Object.fromEntries(contract.stampFields.map((field) => [field, readFlagValue(args, contract.stampFlags[field])]));
|
|
79
|
+
const input = Object.fromEntries(contract.stampFields.map((field) => [field, readFlagValue({ args, flagName: contract.stampFlags[field] })]));
|
|
80
80
|
return contract.normalizeStamp(input);
|
|
81
81
|
}
|
|
82
82
|
catch {
|
|
@@ -90,8 +90,8 @@ export function readProcessStamp(args, contract) {
|
|
|
90
90
|
* @param contract - The stamp contract providing field list, flags, and normalization.
|
|
91
91
|
* @returns The decoded stamp, or `null` when it cannot be normalized.
|
|
92
92
|
*/
|
|
93
|
-
export function readProcessStampFromCommand(command, contract) {
|
|
94
|
-
return readProcessStamp(commandArgs(command), contract);
|
|
93
|
+
export function readProcessStampFromCommand({ command, contract }, _optional = {}) {
|
|
94
|
+
return readProcessStamp({ args: commandArgs(command), contract });
|
|
95
95
|
}
|
|
96
96
|
/**
|
|
97
97
|
* Test whether a stamp matches criteria: every criterion field that is set must
|
|
@@ -103,7 +103,7 @@ export function readProcessStampFromCommand(command, contract) {
|
|
|
103
103
|
* @param contract - The stamp contract providing field list and normalization.
|
|
104
104
|
* @returns `true` when every specified criterion matches the stamp.
|
|
105
105
|
*/
|
|
106
|
-
export function matchesProcessStamp(stamp, criteria, contract) {
|
|
106
|
+
export function matchesProcessStamp({ stamp, criteria, contract }, _optional = {}) {
|
|
107
107
|
const normalizedStamp = contract.normalizeStamp(stamp);
|
|
108
108
|
const normalizedCriteria = contract.normalizeStampCriteria(criteria ?? {});
|
|
109
109
|
return contract.stampFields.every((field) => {
|
|
@@ -120,9 +120,9 @@ export function matchesProcessStamp(stamp, criteria, contract) {
|
|
|
120
120
|
* @param contract - The stamp contract providing field list and normalization.
|
|
121
121
|
* @returns `true` when the command carries a decodable stamp that matches.
|
|
122
122
|
*/
|
|
123
|
-
export function matchesStampedProcess(processInfo, criteria, contract) {
|
|
124
|
-
const stamp = readProcessStampFromCommand(processInfo.command, contract);
|
|
125
|
-
return stamp != null && matchesProcessStamp(stamp, criteria, contract);
|
|
123
|
+
export function matchesStampedProcess({ processInfo, criteria, contract }, _optional = {}) {
|
|
124
|
+
const stamp = readProcessStampFromCommand({ command: processInfo.command, contract });
|
|
125
|
+
return stamp != null && matchesProcessStamp({ stamp, criteria, contract });
|
|
126
126
|
}
|
|
127
127
|
/** @internal Build the stdio triple for a spawned process, routing stdout/stderr to a log fd when provided. */
|
|
128
128
|
function createLoggedStdio(logFd) {
|
|
@@ -216,55 +216,6 @@ export async function waitForProcessExit(pid, timeoutMs = 5000) {
|
|
|
216
216
|
}
|
|
217
217
|
return !isProcessAlive(pid);
|
|
218
218
|
}
|
|
219
|
-
/** @internal Parse `ps -axo pid=,ppid=,command=` output into process snapshots. */
|
|
220
|
-
function parsePsOutput(stdout) {
|
|
221
|
-
return stdout
|
|
222
|
-
.split(/\r?\n/)
|
|
223
|
-
.map((line) => {
|
|
224
|
-
// Same as /^\s*(\d+)\s+(\d+)\s+(.+)$/, split so the command tail cannot backtrack.
|
|
225
|
-
const match = /^\s*(\d+)\s+(\d+)/.exec(line);
|
|
226
|
-
const command = match ? captureLineTail({ rest: line.slice(match[0].length) }, { minWhitespace: 1 }) : null;
|
|
227
|
-
if (!match || command === null)
|
|
228
|
-
return null;
|
|
229
|
-
return { pid: Number(match[1]), ppid: Number(match[2]), command };
|
|
230
|
-
})
|
|
231
|
-
.filter((snapshot) => snapshot != null);
|
|
232
|
-
}
|
|
233
|
-
/** @internal Enumerate process snapshots on POSIX via `ps`. */
|
|
234
|
-
async function listPosixProcessSnapshots(input, options) {
|
|
235
|
-
// Fixed process-enumeration utility intentionally uses the trusted host PATH; command and argv are code-owned.
|
|
236
|
-
const stdout = await processProbeOutput({ command: "ps", run: input.run ?? execFileBuffered,
|
|
237
|
-
args: ["-axo", options.commandLines === false ? "pid=,ppid=,comm=" : "pid=,ppid=,command="],
|
|
238
|
-
}, options);
|
|
239
|
-
return parsePsOutput(stdout ?? "");
|
|
240
|
-
}
|
|
241
|
-
/** @internal Enumerate process snapshots on Windows via `Get-CimInstance Win32_Process` JSON. */
|
|
242
|
-
async function listWindowsProcessSnapshots(input, options) {
|
|
243
|
-
const field = options.commandLines === false ? "Name" : "CommandLine";
|
|
244
|
-
const command = [
|
|
245
|
-
"$ErrorActionPreference = 'Stop'",
|
|
246
|
-
`Get-CimInstance Win32_Process | Select-Object ProcessId, ParentProcessId, ${field} | ConvertTo-Json -Compress`,
|
|
247
|
-
].join("; ");
|
|
248
|
-
const stdout = await processProbeOutput({ command: windowsPowerShell(), run: input.run ?? execFileBuffered,
|
|
249
|
-
args: ["-NoProfile", "-NonInteractive", "-Command", command],
|
|
250
|
-
}, options);
|
|
251
|
-
const payload = stdout?.trim();
|
|
252
|
-
if (!payload)
|
|
253
|
-
return [];
|
|
254
|
-
const records = JSON.parse(payload);
|
|
255
|
-
return (Array.isArray(records) ? records : [records])
|
|
256
|
-
.map((record) => {
|
|
257
|
-
const pid = Number(record.ProcessId);
|
|
258
|
-
const ppid = Number(record.ParentProcessId);
|
|
259
|
-
const commandLine = options.commandLines === false ? record.Name?.trim() ?? "" : record.CommandLine?.trim();
|
|
260
|
-
if (commandLine == null || Number.isNaN(pid) || Number.isNaN(ppid))
|
|
261
|
-
return null;
|
|
262
|
-
if (options.commandLines !== false && !commandLine)
|
|
263
|
-
return null;
|
|
264
|
-
return { command: commandLine, pid, ppid };
|
|
265
|
-
})
|
|
266
|
-
.filter((snapshot) => snapshot != null);
|
|
267
|
-
}
|
|
268
219
|
/**
|
|
269
220
|
* Enumerate all running processes as `{ pid, ppid, command }` snapshots, using
|
|
270
221
|
* the platform-appropriate backend. Returns an empty list on any failure.
|
|
@@ -285,64 +236,6 @@ export async function listProcessSnapshots(input = {}, options = {}) {
|
|
|
285
236
|
return [];
|
|
286
237
|
}
|
|
287
238
|
}
|
|
288
|
-
/** @internal Decode ps cumulative CPU time, including macOS fractional seconds and days. */
|
|
289
|
-
function parseCpuTime(value) {
|
|
290
|
-
const match = value.match(/^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+(?:\.\d+)?)$/);
|
|
291
|
-
if (!match)
|
|
292
|
-
return NaN;
|
|
293
|
-
return Number(match[1] ?? 0) * 86400 + Number(match[2] ?? 0) * 3600
|
|
294
|
-
+ Number(match[3]) * 60 + Number(match[4]);
|
|
295
|
-
}
|
|
296
|
-
/** @internal Reject incomplete metrics instead of presenting missing usage as zero. */
|
|
297
|
-
function validProcessUsage(usage) {
|
|
298
|
-
const { pid, ppid, rssBytes, cpuSeconds } = usage;
|
|
299
|
-
return [pid, ppid].every(Number.isSafeInteger) && [rssBytes, cpuSeconds].every(Number.isFinite)
|
|
300
|
-
&& [pid, ppid, rssBytes, cpuSeconds].every((value) => value >= 0);
|
|
301
|
-
}
|
|
302
|
-
/** @internal Read only comm, never args/command, so credentials cannot enter the result. */
|
|
303
|
-
function parsePsUsage(stdout) {
|
|
304
|
-
return stdout.split(/\r?\n/).flatMap((line) => {
|
|
305
|
-
const match = line.match(/^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(\S.*)$/);
|
|
306
|
-
if (!match)
|
|
307
|
-
return [];
|
|
308
|
-
const usage = {
|
|
309
|
-
pid: Number(match[1]), ppid: Number(match[2]), rssBytes: Number(match[3]) * 1024,
|
|
310
|
-
cpuSeconds: parseCpuTime(match[4]), name: posix.basename(match[5].trim()),
|
|
311
|
-
};
|
|
312
|
-
return validProcessUsage(usage) ? [usage] : [];
|
|
313
|
-
});
|
|
314
|
-
}
|
|
315
|
-
/** @internal CIM serializes numeric fields as numbers or strings; null is not zero usage. */
|
|
316
|
-
function cimNumber(value) {
|
|
317
|
-
if (typeof value === "number")
|
|
318
|
-
return value;
|
|
319
|
-
return typeof value === "string" && value.trim() ? Number(value) : NaN;
|
|
320
|
-
}
|
|
321
|
-
/** @internal Convert Windows 100ns CPU counters and retain nameless process rows. */
|
|
322
|
-
function parseCimUsage(stdout) {
|
|
323
|
-
if (!stdout.trim())
|
|
324
|
-
return [];
|
|
325
|
-
const payload = JSON.parse(stdout);
|
|
326
|
-
return (Array.isArray(payload) ? payload : [payload]).flatMap((record) => {
|
|
327
|
-
if (!record || typeof record !== "object")
|
|
328
|
-
return [];
|
|
329
|
-
const row = record;
|
|
330
|
-
const usage = {
|
|
331
|
-
pid: cimNumber(row.ProcessId), ppid: cimNumber(row.ParentProcessId),
|
|
332
|
-
rssBytes: cimNumber(row.WorkingSetSize),
|
|
333
|
-
cpuSeconds: (cimNumber(row.UserModeTime) + cimNumber(row.KernelModeTime)) / 10_000_000,
|
|
334
|
-
name: typeof row.Name === "string" ? win32.basename(row.Name.trim()) : "",
|
|
335
|
-
};
|
|
336
|
-
return validProcessUsage(usage) ? [usage] : [];
|
|
337
|
-
});
|
|
338
|
-
}
|
|
339
|
-
/** @internal Fixed executable and argv, invoked directly without a command shell. */
|
|
340
|
-
function processUsageCommand(windows) {
|
|
341
|
-
return windows
|
|
342
|
-
? { command: windowsPowerShell(), args: ["-NoProfile", "-NonInteractive", "-Command",
|
|
343
|
-
"$ErrorActionPreference = 'Stop'; Get-CimInstance Win32_Process | Select-Object ProcessId, ParentProcessId, WorkingSetSize, UserModeTime, KernelModeTime, Name | ConvertTo-Json -Compress"] }
|
|
344
|
-
: { command: "ps", args: ["-axo", "pid=,ppid=,rss=,time=,comm="] };
|
|
345
|
-
}
|
|
346
239
|
/**
|
|
347
240
|
* Sample process RSS and cumulative CPU without reading command lines. Returns
|
|
348
241
|
* [] on command, timeout, buffer or JSON failure. RSS totals may count shared
|
|
@@ -378,53 +271,14 @@ export function parseProcessFootprint({ text }, _options = {}) {
|
|
|
378
271
|
const bytes = Number(match[1]) * units[match[2]];
|
|
379
272
|
return Number.isFinite(bytes) ? bytes : null;
|
|
380
273
|
}
|
|
381
|
-
/** @internal One bounded read-only OS probe; partial output on failure is discarded. */
|
|
382
|
-
async function processProbeOutput(input, options) {
|
|
383
|
-
try {
|
|
384
|
-
const result = await input.run(input.command, input.args, {
|
|
385
|
-
encoding: "utf8", timeout: options.timeoutMs ?? 5000, maxBuffer: 8 * 1024 * 1024, windowsHide: true,
|
|
386
|
-
});
|
|
387
|
-
return result.ok ? result.stdout : null;
|
|
388
|
-
}
|
|
389
|
-
catch {
|
|
390
|
-
return null;
|
|
391
|
-
}
|
|
392
|
-
}
|
|
393
|
-
/** @internal Performance instance names can reorder (node, node#1); only IDProcess is identity. */
|
|
394
|
-
function parsePrivateWorkingSets({ stdout }) {
|
|
395
|
-
const readings = new Map();
|
|
396
|
-
try {
|
|
397
|
-
const payload = JSON.parse(stdout ?? "null");
|
|
398
|
-
for (const record of Array.isArray(payload) ? payload : [payload]) {
|
|
399
|
-
if (!record || typeof record !== "object")
|
|
400
|
-
continue;
|
|
401
|
-
const row = record;
|
|
402
|
-
const pid = cimNumber(row.IDProcess);
|
|
403
|
-
const bytes = cimNumber(row.WorkingSetPrivate);
|
|
404
|
-
if (!validSamplePid(pid))
|
|
405
|
-
continue;
|
|
406
|
-
readings.set(pid, Number.isSafeInteger(bytes) && bytes >= 0 ? bytes : null);
|
|
407
|
-
}
|
|
408
|
-
}
|
|
409
|
-
catch { /* Malformed/absent counters are unavailable, never zero. */ }
|
|
410
|
-
return readings;
|
|
411
|
-
}
|
|
412
|
-
const validSamplePid = (pid) => Number.isSafeInteger(pid) && pid > 0;
|
|
413
|
-
/** @internal Reject invalid identities and oversized collections before making any OS calls. */
|
|
414
|
-
function assertPrivateMemorySample({ pids, maxPids }) {
|
|
415
|
-
if (!pids.every(validSamplePid))
|
|
416
|
-
throw new RangeError("invalid process PID");
|
|
417
|
-
if (!Number.isSafeInteger(maxPids) || maxPids < 1 || pids.length > maxPids)
|
|
418
|
-
throw new RangeError("process sample exceeds PID limit");
|
|
419
|
-
}
|
|
420
274
|
/**
|
|
421
|
-
* Read private memory
|
|
275
|
+
* Read private memory for unique PIDs, without attaching an inspector or changing target state.
|
|
422
276
|
* macOS uses physical footprint; Windows uses private working set joined by PID, never PrivateBytes
|
|
423
277
|
* or Win32_Process.WorkingSetSize. Failed probes return null; invalid PIDs/limits throw RangeError.
|
|
424
278
|
* @param input - Requested PIDs and optional host platform/bounded execution port.
|
|
425
279
|
* @param options - Per-probe timeout (5000ms) and unique-PID limit (512); excess is rejected.
|
|
426
280
|
* @returns Accurately labeled bytes, including a null row for every unavailable PID.
|
|
427
|
-
* @complexity O(n) output space for n unique PIDs; macOS makes
|
|
281
|
+
* @complexity O(n) output space for n unique PIDs; macOS makes one bounded `top` read,
|
|
428
282
|
* Windows makes one bounded bulk probe plus O(m) parsing space for m host processes.
|
|
429
283
|
* @example await sampleProcessPrivateMemory({ pids: [123] }, { timeoutMs: 10000 })
|
|
430
284
|
*/
|
|
@@ -433,13 +287,11 @@ export async function sampleProcessPrivateMemory(input, options = {}) {
|
|
|
433
287
|
assertPrivateMemorySample({ pids, maxPids: options.maxPids ?? 512 });
|
|
434
288
|
const platform = input.platform ?? process.platform;
|
|
435
289
|
const run = input.run ?? execFileBuffered;
|
|
436
|
-
const readings = [];
|
|
437
290
|
if (platform === "darwin") {
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
}
|
|
442
|
-
return { metric: "physical-footprint", readings };
|
|
291
|
+
if (!pids.length)
|
|
292
|
+
return { metric: "physical-footprint", readings: [] };
|
|
293
|
+
const stdout = await processProbeOutput({ command: "/usr/bin/top", args: ["-l", "1", "-R", "-F", "-stats", "pid,mem", ...pids.flatMap(pid => ["-pid", String(pid)])], run }, options);
|
|
294
|
+
return { metric: "physical-footprint", readings: topReadings({ text: stdout ?? "", pids }) };
|
|
443
295
|
}
|
|
444
296
|
if (platform !== "win32")
|
|
445
297
|
return { metric: "unavailable", readings: pids.map((pid) => ({ pid, bytes: null })) };
|
|
@@ -449,36 +301,6 @@ export async function sampleProcessPrivateMemory(input, options = {}) {
|
|
|
449
301
|
const byPid = parsePrivateWorkingSets({ stdout });
|
|
450
302
|
return { metric: "private-working-set", readings: pids.map((pid) => ({ pid, bytes: byPid.get(pid) ?? null })) };
|
|
451
303
|
}
|
|
452
|
-
/**
|
|
453
|
-
* Collect the transitive set of descendant PIDs (including the roots) from a
|
|
454
|
-
* process snapshot list, returned sorted by numeric PID descending for deterministic ordering.
|
|
455
|
-
* PID reuse and wraparound mean this does not guarantee children precede parents.
|
|
456
|
-
*
|
|
457
|
-
* @param processes - The full process snapshot list to walk.
|
|
458
|
-
* @param rootPids - The root PIDs whose subtrees to collect (non-numbers ignored).
|
|
459
|
-
* @returns The unique PIDs of the roots and all their descendants, descending.
|
|
460
|
-
*/
|
|
461
|
-
export function collectProcessTreePids(processes, rootPids) {
|
|
462
|
-
const queue = [...new Set(rootPids.filter((pid) => typeof pid === "number"))];
|
|
463
|
-
const visited = new Set();
|
|
464
|
-
const childrenByParent = new Map();
|
|
465
|
-
for (const processInfo of processes) {
|
|
466
|
-
const children = childrenByParent.get(processInfo.ppid) ?? [];
|
|
467
|
-
children.push(processInfo.pid);
|
|
468
|
-
childrenByParent.set(processInfo.ppid, children);
|
|
469
|
-
}
|
|
470
|
-
while (queue.length > 0) {
|
|
471
|
-
const pid = queue.shift();
|
|
472
|
-
if (pid == null || visited.has(pid))
|
|
473
|
-
continue;
|
|
474
|
-
visited.add(pid);
|
|
475
|
-
for (const childPid of childrenByParent.get(pid) ?? []) {
|
|
476
|
-
if (!visited.has(childPid))
|
|
477
|
-
queue.push(childPid);
|
|
478
|
-
}
|
|
479
|
-
}
|
|
480
|
-
return [...visited].sort((left, right) => right - left);
|
|
481
|
-
}
|
|
482
304
|
/** @internal Send a signal to each PID, ignoring `ESRCH` (already-dead) but rethrowing other errors. */
|
|
483
305
|
function signalProcesses(pids, signal) {
|
|
484
306
|
for (const pid of pids) {
|