openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
273 lines (272 loc) • 9.79 kB
JavaScript
import { n as resolveDiagnosticProcessEnv, r as resolveEnvironmentValue } from "./process-env-Bx8i77R6.mjs";
import { createRequire } from "node:module";
import childProcess, { spawnSync } from "node:child_process";
import fsSync from "node:fs";
import { ProcSafeError } from "@openclaw/proc-safe/errors";
import { readProcessIdentity } from "@openclaw/proc-safe/identity";
import path from "node:path";
//#region src/infra/windows-process-start.ts
const DEFAULT_TIMEOUT_MS = 5e3;
const DEFAULT_PROCESS_START_TIMEOUT_MS = 1e4;
const DEFAULT_WINDOWS_SYSTEM_ROOT = "C:\\Windows";
function readNativeProcessStartTime(e) {
if (process.platform !== "win32" || typeof SEALED_RUNTIME_BUILD === "boolean" && SEALED_RUNTIME_BUILD) return;
try {
const t = readProcessIdentity(e);
return t && !t.exited ? Math.floor(t.startTimeMicros / 1e3) : null;
} catch {
return;
}
}
function windowsSystemRoot(e) {
const t = resolveEnvironmentValue(e, "SystemRoot", "win32") ?? resolveEnvironmentValue(e, "WINDIR", "win32");
if (!t) return DEFAULT_WINDOWS_SYSTEM_ROOT;
const n = path.win32.normalize(t);
return /^[A-Za-z]:\\/.test(n) && !n.startsWith("\\\\") ? n : DEFAULT_WINDOWS_SYSTEM_ROOT;
}
function windowsPowerShellPath(e) {
return path.win32.join(windowsSystemRoot(e), "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
}
function windowsWmicPath(e) {
return path.win32.join(windowsSystemRoot(e), "System32", "wbem", "wmic.exe");
}
function decodeWindowsProcessOutput(e) {
if (!Buffer.isBuffer(e)) return e;
return e.length >= 2 && e[0] === 255 && e[1] === 254 ? e.toString("utf16le") : e.toString("utf8");
}
function parseWindowsProcessStartTime(e) {
const t = decodeWindowsProcessOutput(e).split(/\r?\n/).map((e) => e.trim()).filter(Boolean);
const n = t.find((e) => e.toLowerCase().startsWith("creationdate="))?.slice(13).trim() ?? t.find((e) => e.toLowerCase() !== "creationdate") ?? "";
const r = Date.parse(n);
if (Number.isFinite(r)) return r;
const i = n.match(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\.(\d{6})([+-])(\d{3})$/);
if (!i) return null;
const [, a, o, s, c, l, u, d, f, p] = i;
return Date.UTC(Number(a), Number(o) - 1, Number(s), Number(c), Number(l), Number(u), Math.floor(Number(d) / 1e3)) - Number(p) * 6e4 * (f === "+" ? 1 : -1);
}
/** Read a stable Windows process creation time for lock-owner identity checks. */
function readWindowsProcessStartTimeSync(e, t = DEFAULT_PROCESS_START_TIMEOUT_MS, n = process.env) {
if (!Number.isInteger(e) || e <= 0 || e > 4294967295) return null;
const r = Date.now() + t;
const i = readNativeProcessStartTime(e);
if (i !== void 0) return i;
const a = r - Date.now();
if (a <= 0) return null;
const o = spawnSync(windowsPowerShellPath(n), [
"-NoProfile",
"-NonInteractive",
"-Command",
`$process = [System.Diagnostics.Process]::GetProcessById(${e}); try { [Console]::Out.Write($process.StartTime.ToUniversalTime().ToString("o")) } finally { $process.Dispose() }`
], {
encoding: "utf8",
env: resolveDiagnosticProcessEnv(n, "win32"),
timeout: Math.min(a, DEFAULT_TIMEOUT_MS),
windowsHide: true
});
if (!o.error && o.status === 0) {
const e = parseWindowsProcessStartTime(o.stdout);
if (e !== null) return e;
}
const s = r - Date.now();
if (s <= 0) return null;
const c = spawnSync(windowsWmicPath(n), [
"process",
"where",
`ProcessId=${e}`,
"get",
"CreationDate",
"/value"
], {
env: resolveDiagnosticProcessEnv(n, "win32"),
timeout: s,
windowsHide: true,
stdio: [
"ignore",
"pipe",
"ignore"
]
});
return !c.error && c.status === 0 ? parseWindowsProcessStartTime(c.stdout) : null;
}
//#endregion
//#region src/shared/freebsd-process-identity-native.ts
let identity;
/** Normal installations use the dependency's public loader. */
function loadFreeBsdProcessIdentityNative() {
if (typeof SEALED_RUNTIME_BUILD === "boolean" && SEALED_RUNTIME_BUILD) throw new Error("FreeBSD process identity is unavailable in this sealed runtime");
if (!identity) identity = createRequire(import.meta.url)("@openclaw/proc-safe/identity");
return identity;
}
//#endregion
//#region src/shared/freebsd-process-identity.ts
/** Read the kernel's monotonic process start time in microseconds. */
function readFreeBsdProcessStartTime(e) {
if (process.platform !== "freebsd" || !Number.isInteger(e) || e <= 0 || e > 2147483647) return null;
try {
return loadFreeBsdProcessIdentityNative().readProcessIdentity(e)?.startTimeSinceBootMicros ?? null;
} catch {
return null;
}
}
//#endregion
//#region src/shared/pid-alive.ts
const PROCESS_START_TIMEOUT_MS = 1e3;
function readDarwinNativeIdentity(e) {
if (process.platform !== "darwin" || typeof SEALED_RUNTIME_BUILD === "boolean" && SEALED_RUNTIME_BUILD) return;
try {
const t = readProcessIdentity(e);
return t && !t.exited ? {
startedAt: Math.floor(t.startTimeMicros / 1e6),
startTimeMicros: t.startTimeMicros
} : null;
} catch {
return;
}
}
/** Unknown observations never prove death; Linux keeps its thread-aware procfs policy. */
function readNativeLiveness(e) {
if (![
"darwin",
"win32",
"freebsd"
].includes(process.platform) || typeof SEALED_RUNTIME_BUILD === "boolean" && SEALED_RUNTIME_BUILD) return;
try {
const t = readProcessIdentity(e);
return t !== null && !t.exited;
} catch (e) {
if (e instanceof ProcSafeError && (e.code === "helper-unavailable" || e.code === "unsupported-platform")) return;
return true;
}
}
let selfStartTime = null;
function isValidPid(e) {
return Number.isInteger(e) && e > 0;
}
function hasLinuxProcfs() {
return process.platform === "linux" || process.platform === "android";
}
/**
* Reject recycled worker TIDs and terminal leaders without live sibling threads.
* Missing or reaped procfs snapshots require a fresh existence probe.
*/
function isExitedLinuxProcess(e) {
if (!hasLinuxProcfs()) return false;
try {
const t = fsSync.readFileSync(`/proc/${e}/status`, "utf8");
const n = t.match(/^State:\s+(\S)/m)?.[1];
const r = t.match(/^Threads:[ \t]+(\d+)[ \t]*$/m)?.[1];
if (r !== "0") {
const i = t.match(/^Tgid:[ \t]+(\d+)[ \t]*$/m)?.[1];
return i !== void 0 && Number(i) !== e || (n === "Z" || n === "X") && r === "1";
}
} catch {}
try {
process.kill(e, 0);
} catch (e) {
return e.code === "ESRCH";
}
return false;
}
/** Returns true only when a positive PID exists and is not a known terminal task. */
function isPidAlive(e) {
if (!isValidPid(e)) return false;
try {
process.kill(e, 0);
} catch (t) {
const n = t.code;
if (n !== "EPERM") return n === "ESRCH" ? readNativeLiveness(e) ?? false : false;
}
return readNativeLiveness(e) ?? !isExitedLinuxProcess(e);
}
/** Returns true only when the PID is invalid, missing, or a known terminal task. */
function isPidDefinitelyDead(e) {
if (!isValidPid(e)) return true;
let t = false;
try {
process.kill(e, 0);
} catch (e) {
const n = e.code;
if (n !== "ESRCH" && !(process.platform === "win32" && n === "EPERM")) return false;
t = n === "ESRCH";
}
const n = readNativeLiveness(e);
return n === void 0 ? t && process.platform !== "freebsd" || isExitedLinuxProcess(e) : !n;
}
function getDarwinProcessStartTime(e, t, n) {
const r = performance.now();
const i = readDarwinNativeIdentity(e);
if (i !== void 0) return i?.startedAt ?? null;
const a = n === void 0 ? PROCESS_START_TIMEOUT_MS : Math.ceil(n - (performance.now() - r));
if (a <= 0) return null;
try {
const n = childProcess.execFileSync("/bin/ps", [
"-o",
"lstart=",
"-p",
String(e)
], {
encoding: "utf8",
env: {
...resolveDiagnosticProcessEnv(t),
LC_ALL: "C",
TZ: "UTC"
},
stdio: [
"ignore",
"pipe",
"ignore"
],
timeout: a,
killSignal: "SIGKILL"
}).trim();
const r = Date.parse(`${n} UTC`);
return Number.isFinite(r) ? Math.floor(r / 1e3) : null;
} catch {
return null;
}
}
/** Kernel parent and birth ticks share one procfs snapshot, independent of native addons. */
function readLinuxProcessStat(e) {
if (!isValidPid(e) || !hasLinuxProcfs()) return null;
try {
const t = fsSync.readFileSync(`/proc/${e}/stat`, "utf8");
const n = t.lastIndexOf(")");
if (n < 0 || !t.startsWith(`${e} (`)) return null;
const r = t.slice(n + 1).trimStart().split(/\s+/);
const i = Number(r[19]);
const a = Number(r[1]);
return Number.isSafeInteger(i) && i >= 0 && Number.isSafeInteger(a) && a >= 0 ? {
parentPid: a,
startedAt: i
} : null;
} catch {
return null;
}
}
/** Read the Linux procfs start identity used by Linux-owned runtime state. */
function getProcessStartTime(e) {
return readLinuxProcessStat(e)?.startedAt ?? null;
}
/** Custody recovery needs native birth precision rather than the shipped lease timestamp format. */
function getProcessInstanceStartTime(e) {
if (!isValidPid(e)) return null;
if (hasLinuxProcfs()) {
const t = getProcessStartTime(e);
return Number.isSafeInteger(t) ? t : null;
}
const t = readDarwinNativeIdentity(e);
if (!t) return null;
const n = t.startTimeMicros;
return Number.isSafeInteger(n) ? n : null;
}
/** Read a cross-platform process identity for filesystem lock ownership. */
function getFileLockProcessStartTime(e, t = process.env, n) {
if (!isValidPid(e)) return null;
const r = e === process.pid;
if (r && selfStartTime !== null) return selfStartTime;
const i = process.platform === "darwin" ? getDarwinProcessStartTime(e, t, n) : process.platform === "win32" ? readWindowsProcessStartTimeSync(e, n, t) : process.platform === "freebsd" ? readFreeBsdProcessStartTime(e) : getProcessStartTime(e);
if (r && i !== null) selfStartTime = i;
return i;
}
//#endregion
export { readLinuxProcessStat as a, isPidDefinitelyDead as i, getProcessInstanceStartTime as n, isPidAlive as r, getFileLockProcessStartTime as t };