UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

682 lines (681 loc) • 26.4 kB
import { b as canAccessSync } from "./runtime-doctor-migrations-JGL9tD-z.js"; import { _ as _usingCtx, a as referencesRetainedArtifact, c as isUpdateCommandArgv, g as resolveDiagnosticProcessEnv, i as readProcessWorkingDirectories, l as rewriteUpdateFlagArgv, m as readLinuxProcessStat, n as classifyOpenClawEntrypointPath, p as isPidDefinitelyDead, r as readProcessPackageIdentity, s as getRootOptionAwareCommandPath, t as classifyOpenClawArgv, u as readProcessGroupMembers } from "./gateway-process-argv-C93wqkFe.js"; import { E as escapeRegExp, t as createSubsystemLogger } from "./subsystem-DLheYoE0.js"; import { a as runtimeProcessEntrypoints, n as isNodeRuntime, r as resolveRuntimeScriptPosition, t as isBunRuntime } from "./runtime-binary-DrN_tBF0.js"; import { createRequire } from "node:module"; import path from "node:path"; import fs from "node:fs"; import os from "node:os"; import { fileURLToPath, pathToFileURL } from "node:url"; import { execFileSync, spawnSync } from "node:child_process"; import { readProcessAncestry, readProcessIdentity } from "@openclaw/proc-safe/identity"; import { ProcSafeError } from "@openclaw/proc-safe/errors"; import { listProcesses, readProcessCommand } from "@openclaw/proc-safe/inspect"; import { PinnedProcess } from "@openclaw/proc-safe/windows-job"; //#region src/process/supervisor/darwin-process-command.ts let reportedForeignArguments = false; const REDACTED_ARGUMENTS_ENTITLEMENT = /\[Key\] com\.apple\.private\.no-read-procargs\s*\[Value\]\s*\[Bool\] true|<key>com\.apple\.private\.no-read-procargs<\/key>\s*<true\/>/u; /** The running image: the first text mapping, confirmed by the kernel accounting * name (exec basename, truncated to 16 bytes), so a mapped binary cannot pose as it. */ function readDarwinImagePath(e) { const t = { encoding: "utf8", timeout: 2e3 }; const n = spawnSync("/usr/sbin/lsof", [ "-a", "-p", String(e), "-d", "txt", "-Fn" ], t); const r = n.status === 0 ? /^n(\/.+)$/mu.exec(n.stdout)?.[1] : void 0; const i = r && spawnSync("/bin/ps", [ "-o", "ucomm=", "-p", String(e) ], t); return i && i.status === 0 && i.stdout.trim() === path.basename(r).slice(0, 16) ? r : void 0; } /** A sealed Apple binary that opts out of argument inspection, such as mdworker. */ function isRedactedSystemImage(e) { if (!e.startsWith("/System/")) return false; const t = spawnSync("/usr/bin/codesign", [ "-d", "--entitlements", "-", e ], { encoding: "utf8", timeout: 2e3 }); return t.status === 0 && REDACTED_ARGUMENTS_ENTITLEMENT.test(t.stdout); } function readCommandWithServiceMarker(e) { try { return readProcessCommand(e, { environmentKeys: ["OPENCLAW_SERVICE_MARKER"] }); } catch (t) { if (!(t instanceof ProcSafeError) || t.code !== "incomplete") throw t; const n = readProcessCommand(e); return n && [n.executable, n.argv[0] ?? ""].some((e) => isNodeRuntime(e) || isBunRuntime(e) || path.basename(e) === "tsx") ? { ...n, serviceMarkerUnavailable: true } : n; } } /** Exact argv, or observed foreign ownership when Darwin denies argument inspection. * Callers that never consult the service marker skip the environment: some macOS * argument images end without the separator that bounds it. */ function readDarwinProcessCommand(e, t, n = {}) { try { const t = n.serviceMarker === false ? readProcessCommand(e) : readCommandWithServiceMarker(e); if (!t) return; const r = t.environment.OPENCLAW_SERVICE_MARKER; return { argv: [...t.argv], executable: t.executable, ...r === void 0 ? {} : { serviceMarker: r }, ..."serviceMarkerUnavailable" in t ? { serviceMarkerUnavailable: true } : {} }; } catch (n) { if (!(n instanceof ProcSafeError)) throw n; if (n.code === "layout-mismatch" || n.code === "incomplete") { const r = readDarwinImagePath(e); if (r && isRedactedSystemImage(r)) return { argvUnavailable: true, executable: r, ...t ? { owner: t } : {} }; throw n; } if (n.code === "unsupported-platform" && process.platform === "darwin") throw new Error("Cannot inspect Darwin process arguments under Rosetta; run OpenClaw with native arm64 Node.js.", { cause: n }); if (n.code !== "access-denied" && n.code !== "operation-failed") throw n; if (isPidDefinitelyDead(e)) return; if (t === "different") { if (!reportedForeignArguments) { reportedForeignArguments = true; createSubsystemLogger("process/census").debug("Unreadable Darwin arguments for another UID do not establish capture custody.", { pid: e, code: n.code }); } return { argvUnavailable: true, owner: t }; } throw new Error(`Could not classify PID ${e}: cannot inspect Darwin arguments (${n.code}).`, { cause: n }); } } //#endregion //#region src/process/windows-command-line.ts /** Parse an Arguments field; it does not contain the executable's special first token. */ function parseWindowsNativeArguments(e) { const t = []; let n = 0; while (n < e.length) { while (/[ \t]/.test(e.charAt(n))) n++; if (n === e.length) break; let r = ""; let i = false; while (n < e.length) { let t = 0; while (e[n] === "\\") { t++; n++; } if (e[n] === "\"") { r += "\\".repeat(Math.floor(t / 2)); if (t % 2 === 1) { r += "\""; n++; } else if (i && e[n + 1] === "\"") { r += "\""; n += 2; } else { i = !i; n++; } continue; } r += "\\".repeat(t); if (n === e.length || !i && /[ \t]/.test(e.charAt(n))) break; r += e.charAt(n++); } t.push(r); } return t; } /** Parse a native process command line; argv[0] preserves backslashes before quotes. */ function parseWindowsNativeCommandLine(e) { if (e.includes("\0")) return null; let t = 0; while (/[ \t]/.test(e.charAt(t))) t++; if (t === e.length) return []; let n = ""; let r = false; while (t < e.length && (r || !/[ \t]/.test(e.charAt(t)))) { const i = e.charAt(t++); if (i === "\"") r = !r; else n += i; } if (r || !n) return null; return [n, ...parseWindowsNativeArguments(e.slice(t))]; } //#endregion //#region src/shared/rosetta-translation.ts let translated; /** * Whether this x86_64 Darwin process is running under Rosetta. * * Darwin process-argument inspection remains unavailable under translation in * proc-safe. The census uses this fact to name the supported native runtime. */ function isRosettaTranslatedProcess() { if (process.platform !== "darwin" || process.arch !== "x64") return false; translated ??= os.cpus()[0]?.model.includes("Apple") === true; return translated; } //#endregion //#region src/infra/container-environment.ts let containerEnvironmentCache; function isContainerEnvironment() { return containerEnvironmentCache ??= detectContainerEnvironment(); } function detectContainerEnvironment() { if (process.env.FLY_MACHINE_ID?.trim() && process.env.FLY_APP_NAME?.trim()) return true; for (const e of [ "/.dockerenv", "/run/.containerenv", "/var/run/.containerenv" ]) try { fs.accessSync(e, fs.constants.F_OK); return true; } catch {} try { const e = fs.readFileSync("/proc/1/cgroup", "utf8"); if (/\/docker\/|cri-containerd-[0-9a-f]|containerd\/[0-9a-f]{64}|\/kubepods[/.]|\blxc\b/.test(e)) return true; } catch {} return false; } //#endregion //#region src/infra/windows-process-census.ts /** Missing fields never establish absence for same-user or unknown-owner work. */ function readWindowsProcessCensus(e) { return listProcesses({ timeoutMs: e, includeCommand: true }).flatMap(({ pid: e, owner: t, identity: n, command: r }) => { if (e === 0 || e === 4 || n?.exited) return []; let i = r?.executable; if (!r && n) try { try { var a = _usingCtx(); i = a.u(PinnedProcess.open(e, { access: "observe", expect: { startTimeMicros: n.startTimeMicros } }))?.imagePath; } catch (e) { a.e = e; } finally { a.d(); } } catch {} let o; if (t === "unknown" && !n && !r) try { readProcessIdentity(e); } catch (e) { if (e instanceof ProcSafeError && e.code === "access-denied") o = true; } return [{ pid: e, ...n ? { parentPid: n.parentPid, startIdentity: String(Math.floor(n.startTimeMicros / 1e3)) } : {}, ...r?.commandLine === void 0 ? {} : { commandLine: r.commandLine }, ...i ? { executable: i } : {}, ...r?.cwd === void 0 ? {} : { cwd: r.cwd }, ...t === "different" ? { foreignOwner: true } : {}, ...o ? { accessDenied: o } : {} }]; }); } //#endregion //#region src/infra/windows-appcontainer-spawn.ts var AppContainerSpawnUnsupportedError = class extends Error { constructor(e) { super(`AppContainer: libuv ${e} cannot create child pipes; 1.53.0+ required. Run OpenClaw outside the AppContainer or use a Node build with libuv >= 1.53.0.`); this.code = "APPCONTAINER_SPAWN_UNSUPPORTED"; this.name = "AppContainerSpawnUnsupportedError"; } }; let checked = false; let unsupported; /** libuv before 1.53 loops forever creating child pipes in an AppContainer. */ function assertAppContainerSpawnSupported(e) { if (process.platform !== "win32") return; if (e === "ignore" || e === "inherit" || Array.isArray(e) && e.length >= 3 && e.every((e) => e !== void 0 && e !== null && e !== "pipe" && e !== "overlapped" && e !== "ipc" && !(typeof e === "number" && e < 0))) return; if (!checked) { checked = true; try { const { readCurrentAppContainerSid: e } = createRequire(import.meta.url)("@openclaw/proc-safe/windows-token"); const t = e(); const n = process.versions.uv; const r = Number(n.split(".")[0]); const i = Number(n.split(".")[1]); if (t !== null && (r < 1 || r === 1 && i < 53)) unsupported = new AppContainerSpawnUnsupportedError(n); } catch (e) { import("./subsystem-DLheYoE0.js").then((e) => e.n).then(({ createSubsystemLogger: t }) => { t("process").debug("AppContainer token probe failed; allowing spawn", { error: String(e) }); }).catch(() => {}); } } if (unsupported) throw unsupported; } //#endregion //#region src/infra/windows-install-roots.ts const DEFAULT_WINDOWS_SYSTEM_ROOT = "C:\\Windows"; const WINDOWS_NT_CURRENT_VERSION_KEY = "HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"; const REG_QUERY_TIMEOUT_MS = 5e3; let cachedProcessRoots = null; function locateWindowsRegExe() { const e = path.win32.join(DEFAULT_WINDOWS_SYSTEM_ROOT, "System32", "reg.exe"); return canAccessSync(e, fs.constants.R_OK) ? e : null; } function trimTrailingSeparators(e) { const t = path.win32.parse(e); let n = e; while (n.length > t.root.length && /[\\/]/.test(n.at(-1) ?? "")) n = n.slice(0, -1); return n; } /** * Windows install roots should be local absolute directories, not drive-relative * paths, UNC shares, or PATH-like lists that could widen trust unexpectedly. */ function normalizeWindowsInstallRoot(e) { if (typeof e !== "string") return null; const t = e.trim(); if (!t || t.includes("\0") || t.includes("\r") || t.includes("\n") || t.includes(";")) return null; const n = trimTrailingSeparators(path.win32.normalize(t)); if (!path.win32.isAbsolute(n) || n.startsWith("\\\\")) return null; const r = path.win32.parse(n); if (!/^[A-Za-z]:\\$/.test(r.root)) return null; if (n.length <= r.root.length) return null; return n; } function getEnvValueCaseInsensitive(e, t) { const n = e[t]; if (n !== void 0) return n; const r = t.toUpperCase(); const i = Object.keys(e).find((e) => e.toUpperCase() === r); return i ? e[i] : void 0; } /** Queries one Windows registry string value via reg.exe; null when absent or unreadable. */ function queryWindowsRegistryValue(e, t, n) { const r = locateWindowsRegExe(); if (!r) return null; for (const i of [["/reg:64"], []]) { const a = n === void 0 ? REG_QUERY_TIMEOUT_MS : Math.min(REG_QUERY_TIMEOUT_MS, Math.ceil(n - performance.now())); if (a <= 0) return null; assertAppContainerSpawnSupported(); try { const n = execFileSync(r, [ "query", e, "/v", t, ...i ], { env: resolveDiagnosticProcessEnv(), encoding: "utf8", stdio: [ "ignore", "pipe", "ignore" ], timeout: a, windowsHide: true }); const o = new RegExp(`^\\s*${escapeRegExp(t)}\\s+REG_[A-Z0-9_]+\\s+(.+)$`, "im"); const s = n.match(o)?.[1]?.trim(); if (s) return s; } catch {} } return null; } function resolveSystemRootFromEnv(e) { return normalizeWindowsInstallRoot(getEnvValueCaseInsensitive(e, "SystemRoot")) ?? normalizeWindowsInstallRoot(getEnvValueCaseInsensitive(e, "WINDIR")) ?? DEFAULT_WINDOWS_SYSTEM_ROOT; } function getProcessRoots(e) { if (!cachedProcessRoots) { const t = {}; for (const e of [ "SystemRoot", "WINDIR", "ProgramFiles", "ProgramFiles(x86)", "ProgramW6432" ]) t[e] = getEnvValueCaseInsensitive(process.env, e); const n = { env: t, systemRoot: normalizeWindowsInstallRoot(queryWindowsRegistryValue(WINDOWS_NT_CURRENT_VERSION_KEY, "SystemRoot", e) ?? void 0) ?? resolveSystemRootFromEnv(t) }; if (e !== void 0 && performance.now() >= e) return n; cachedProcessRoots = n; } return cachedProcessRoots; } function getWindowsSystemRoot(e, t) { if (e !== process.env) return resolveSystemRootFromEnv(e); const n = getProcessRoots(t); return n.installRoots?.systemRoot ?? n.systemRoot; } function getWindowsPowerShellExePath(e = process.env, t) { return path.win32.join(getWindowsSystemRoot(e, t), "System32", "WindowsPowerShell", "v1.0", "powershell.exe"); } //#endregion //#region src/infra/windows-user-sid.ts /** The launching token's account, independent of environment usernames or elevation. */ function readWindowsUserSid() { if (process.platform !== "win32") return; try { const e = spawnSync(getWindowsPowerShellExePath(), [ "-NoProfile", "-NonInteractive", "-Command", "[Security.Principal.WindowsIdentity]::GetCurrent().User.Value" ], { encoding: "utf8", windowsHide: true, timeout: 5e3 }); const t = e.stdout?.trim(); return !e.error && e.status === 0 && /^S-1-\d+(?:-\d+)+$/.test(t) ? t : void 0; } catch { return; } } //#endregion //#region src/infra/openclaw-process-census.ts const workerEntrypoints = Object.values(runtimeProcessEntrypoints).flatMap((e) => [path.posix.normalize(`src/infra/${e.sourceWorkerName}.ts`), `dist/${e.distWorkerPath}`]); function isStandardSystemdUserManager(e) { const t = e && "argv" in e ? e.argv : []; return t.length <= 3 && t[1] === "--user" && t.slice(2).every((e) => /^--deserialize=\d+$/u.test(e)) && (t[0] === "/usr/lib/systemd/systemd" || t[0] === "/lib/systemd/systemd"); } function isStandardSystemdLoginProcess(e, t, n) { if (process.platform !== "linux" || n === void 0 || e?.uid !== n || !("argv" in e)) return false; return isStandardSystemdUserManager(e) || e.argv.length === 1 && e.argv[0] === "(sd-pam)" && t?.uid === e.uid && isStandardSystemdUserManager(t); } const gatewayWorkerEntrypoints = [ path.posix.normalize(`src/infra/${runtimeProcessEntrypoints.spawnBroker.sourceWorkerName}.ts`), `dist/${runtimeProcessEntrypoints.spawnBroker.distWorkerPath}`, path.posix.normalize(`src/infra/${runtimeProcessEntrypoints.directoryWatchHost.sourceWorkerName}.ts`), `dist/${runtimeProcessEntrypoints.directoryWatchHost.distWorkerPath}` ]; function isGatewayProcess(e, t) { if (path.basename((e[0] ?? "").replaceAll("\\", "/")).replace(/\.(exe|cmd|bat)$/iu, "") === "openclaw-gateway") return true; if (t.kind !== "openclaw" || t.entryIndex === void 0) return false; const n = (e[t.entryIndex] ?? "").replaceAll("\\", "/"); return gatewayWorkerEntrypoints.some((e) => n.endsWith(`/${e}`)) || getRootOptionAwareCommandPath(rewriteUpdateFlagArgv(["node", ...e.slice(t.entryIndex)]), 1)[0] === "gateway"; } function classifyProcessArtifactCustody(e, t, n) { if (!e) return { kind: "unknown", reason: "process command is unavailable" }; const r = "argv" in e ? e.argv : []; const i = [ ...r.map((e) => e.replace(/^--[^=]+=/u, "").replace(/^-r(?=.)/u, "")), n ?? "", "executable" in e ? e.executable ?? "" : "" ].filter(referencesRetainedArtifact); if ("argvUnavailable" in e || r.length === 0) return i.length ? { kind: "holder" } : { kind: "not-holder" }; const { position: a, operands: o } = resolveRuntimeScriptPosition(r); const s = { pid: t, cwd: n ?? "", serviceMarker: e.serviceMarker, serviceMarkerUnavailable: e.serviceMarkerUnavailable, additionalEntrypoints: workerEntrypoints, inspectPackage: true }; let c; const l = i.flatMap((e) => { const t = classifyOpenClawEntrypointPath(e, s); if (t.kind === "openclaw" && t.artifactPath) return [t.artifactPath]; c ??= t.kind === "unclassified" ? t.reason : "runtime path is unresolved"; return []; }); if (i.length && o.length === 0) return c ? { kind: "unknown", reason: c } : { kind: "holder", paths: l }; const u = classifyOpenClawArgv(r, s); const d = isGatewayProcess(r, u); let f = i.length > 0 || l.length > 0; const unscoped = () => f || !d ? { kind: "holder" } : { kind: "holder", gateway: true }; if (u.kind === "openclaw") { if (!u.artifactPath) return o.some(({ module: e }) => e) ? { kind: "holder" } : unscoped(); l.push(u.artifactPath); f = true; } let p = l.length ? { kind: "holder", paths: l } : void 0; c ??= u.kind === "unclassified" && u.cause !== "runtime-syntax" ? u.reason : void 0; if (!n || !path.isAbsolute(n)) { if (u.kind === "other" && typeof a !== "number" && a.kind === "not-runtime" && i.length === 0) return { kind: "not-holder" }; return { kind: "unknown", reason: c ?? "working directory is unavailable" }; } const m = typeof a !== "number" && a.kind !== "not-runtime" ? readProcessPackageIdentity(n, true) : void 0; if (m?.kind === "package" && m.name === "openclaw") p = unscoped(); const h = m?.kind === "package" ? m.scripts : {}; if (m?.kind === "unknown") c ??= m.reason; for (const { value: e, module: t } of o) { let n = e; if (t) { if (e.startsWith("file:")) try { n = fileURLToPath(e); } catch (e) { c ??= String(e); continue; } else if (!path.isAbsolute(e) && !e.startsWith("./") && !e.startsWith("../")) { c ??= "runtime module package identity is unavailable"; continue; } } else if (isBunRuntime(r[0] ?? "") && !/[\\/]/u.test(e) && !path.extname(e) && typeof h[e] === "string" && h[e].trim()) continue; const i = classifyOpenClawEntrypointPath(n, s); if (i.kind === "unclassified") c ??= i.reason; else if (i.kind === "openclaw") { f ||= i.artifactPath !== void 0; p = i.artifactPath && (!p || p.paths) ? { kind: "holder", paths: [...p?.paths ?? [], i.artifactPath] } : unscoped(); } } return c ? { kind: "unknown", reason: c } : p ?? { kind: "not-holder" }; } function classifyWindowsHandoffAncestry(e, t, n) { const r = e.startIdentity; if (r && n.length && n.every(({ startIdentity: e }) => /^\d+$/.test(e) && BigInt(e) > BigInt(r))) return "unrelated"; const i = /* @__PURE__ */ new Set(); let a = e; while (a.startIdentity && !i.has(a.pid)) { const e = a.startIdentity; i.add(a.pid); if (n.some(({ pid: t, startIdentity: n }) => t === a.pid && n === e || t === a.parentPid && /^\d+$/.test(n) && BigInt(n) <= BigInt(e))) return "descendant"; if (a.parentPid === 0 || a.parentPid === 4) return "unrelated"; const r = t.get(a.parentPid ?? 0); if (!r?.startIdentity || BigInt(r.startIdentity) > BigInt(e)) break; a = r; } return "unknown"; } function inspectOtherOpenClawProcesses(e) { const t = typeof e === "object" ? e : void 0; const n = typeof e === "string" ? e : void 0; const r = []; const i = { matchingPids: [], unverifiedPids: [] }; try { if (process.platform === "linux" && isContainerEnvironment()) throw new Error("Host process visibility cannot be established from this container. Run Doctor on the host after stopping OpenClaw containers that share its temporary directory."); const e = process.platform === "win32"; const a = Date.now() + (t ? 15e3 : 1e3); const o = e && t ? [...readWindowsProcessCensus(15e3)] : void 0; const s = new Map(o?.map((e) => [e.pid, e])); const c = e && t?.windowsUserSid !== void 0 && readWindowsUserSid() === t.windowsUserSid; const l = o?.map(({ pid: e, parentPid: t, commandLine: n }) => { const r = n ? parseWindowsNativeCommandLine(n) : null; return { pid: e, state: "", command: r?.length && t !== void 0 ? { ppid: t, argv: r } : void 0 }; }) ?? [...readProcessGroupMembers(t ? 15e3 : 1e3, { readDarwinCommand: t ? (e, t) => readDarwinProcessCommand(e, t, { serviceMarker: false }) : readDarwinProcessCommand })]; const u = new Map(l.map((e) => [e.pid, e])); const d = u.get(process.pid); if (!d || !t && (!d.command && process.platform !== "darwin" || process.platform === "linux" && l.some((e) => e.command && !("argv" in e.command)))) throw new Error("OpenClaw process census is incomplete."); const f = o ? new Map(o.map(({ pid: e, cwd: t }) => [e, t])) : readProcessWorkingDirectories(l.map(({ pid: e }) => e)); const p = /* @__PURE__ */ new Set(); const m = !t && isUpdateCommandArgv(process.argv); const h = /* @__PURE__ */ new Set([process.pid]); let g = d; let _ = d.command?.ppid ?? d.ppid ?? 0; while (_ > 0) { const n = u.get(_); if (!n?.command || h.has(_)) { if (t || n && !n.command) break; throw new Error("OpenClaw process ancestry is incomplete."); } const r = s.get(_)?.startIdentity; const i = s.get(g.pid)?.startIdentity; if (e && (!r || !i || BigInt(r) >= BigInt(i))) break; h.add(_); if ("argv" in n.command) { const { argv: e, serviceMarker: r, serviceMarkerUnavailable: i } = n.command; const a = classifyOpenClawArgv(e, { pid: _, serviceMarker: r, serviceMarkerUnavailable: i, cwd: f.get(_) ?? "", additionalEntrypoints: workerEntrypoints }); const o = a.kind === "openclaw" && a.entryIndex !== void 0 ? getRootOptionAwareCommandPath(rewriteUpdateFlagArgv(["node", ...e.slice(a.entryIndex)]), 1)[0] : void 0; if (o === (t ? "update" : "doctor") || m && o === "update" && _ === (d.command?.ppid ?? d.ppid)) p.add(_); } g = n; _ = n.command.ppid; } const normalize = (t) => e ? t.replaceAll("\\", "/").replace(/\/{2,}\?\/UNC\//gi, "//").replace(/\/{2,}\?\//g, "").replace(/\/{2,}/g, "/").toLowerCase() : t; const literal = (e) => escapeRegExp(normalize(e)); const referencePattern = (n) => { const r = n.flatMap((t) => [t.replace(/[\\/]+$/, ""), pathToFileURL(t, { windows: e }).href]); return new RegExp(`(?:^|[^\\w-])(?:${t ? literal(t.runId) : "(?!)"}(?=$|[^\\w-])|(?:${r.map(literal).join("|") || "(?!)"})(?=$|[/\\s"'\x60);,\\]]))`); }; const v = t?.artifactPaths ?? (n ? [n] : []); const y = referencePattern(v); const rootKey = (e) => normalize(e.replace(/[\\/]+$/, "")); const b = new Set(t?.sharedRoots?.map(rootKey)); const x = referencePattern(v.filter((e) => !b.has(rootKey(e)))); const S = process.getuid?.(); const outsideHandoffFamily = (e, t) => { let n; try { n = readProcessAncestry(e, { throughPid: process.pid }); } catch { return false; } if (n?.stoppedBy === "through-pid") return true; return t !== void 0 && n?.stoppedBy === "root" && n.chain.every((e) => { const n = u.get(e.pid)?.command; return e.startTimeMicros > t * 1e3 || process.platform === "linux" && n?.uid === S && isStandardSystemdUserManager(n); }); }; const predatesHandoffDrivers = (e) => { if (process.platform !== "linux" || !t?.drivers?.length) return false; const n = readLinuxProcessStat(e)?.startedAt; return n !== void 0 && t.drivers.every(({ startIdentity: e }) => BigInt(e) > BigInt(n)); }; for (const { pid: o, state: d, command: m } of l) { if (t && Date.now() >= a) throw new Error("Process census deadline exceeded"); if (o === process.pid || p.has(o)) continue; if ((d?.startsWith("Z") || t) && isPidDefinitelyDead(o)) continue; const l = m && "argv" in m ? m.argv : void 0; if (t) { if (!e && l?.length === 0) continue; const n = s.get(o); const a = f.get(o); const d = [ ...l ?? [], n?.commandLine ?? "", n?.executable ?? "", a ?? "" ]; const p = classifyOpenClawArgv(l ?? [n?.executable ?? ""], { pid: o, cwd: a ?? "", serviceMarker: m && "argv" in m ? m.serviceMarker : void 0, additionalEntrypoints: workerEntrypoints }); if (d.some((e) => y.test(normalize(e))) || !t.artifactPathsOnly && p.kind === "openclaw") { if (!outsideHandoffFamily(o, d.some((e) => x.test(normalize(e))) ? void 0 : t.familyDeadline)) i.matchingPids.push(o); continue; } const h = t.familyExited ? "unrelated" : n && classifyWindowsHandoffAncestry(n, s, t.drivers ?? []); if (h === "descendant") { i.matchingPids.push(o); continue; } if (h === "unrelated" || c && n?.accessDenied) continue; const g = n?.foreignOwner || m?.owner === "different" || m?.uid !== void 0 && S !== void 0 && m.uid !== S; if ((!l || a === void 0) && !g && !isStandardSystemdLoginProcess(m, u.get(m?.ppid ?? 0)?.command, S) && !outsideHandoffFamily(o) && !predatesHandoffDrivers(o)) { i.unverifiedPids.push(o); const t = n?.executable ?? l?.[0]; r.push(`Could not verify handoff ancestry for PID ${o} (${t ? (e ? path.win32 : path).basename(t) : "image unavailable"}).`); } continue; } const h = classifyProcessArtifactCustody(m, o, f.get(o)); if (h.kind === "not-holder") continue; if (h.kind === "holder" && n && (h.paths ? !h.paths.some((e) => y.test(normalize(e))) : h.gateway)) continue; i.matchingPids.push(o); if (h.kind === "unknown") r.push(`Could not verify runtime custody for PID ${o}: ${h.reason}`); } } catch (e) { const n = /Could not classify PID (\d+):/.exec(e instanceof Error ? e.message : ""); if (t && n) i.unverifiedPids.push(Number(n[1])); i.error = !t ? `Could not inspect OpenClaw processes: ${String(e)}` : isRosettaTranslatedProcess() ? "Host process census is unavailable under Rosetta; run openclaw update repair with native arm64 Node.js." : "Host process census is incomplete; verify process-inspection permissions and retry update repair."; } return t ? { ...i, ...r.length ? { warnings: r } : {} } : i.error ? { error: i.error } : { pids: i.matchingPids, ...r.length ? { warnings: r } : {} }; } //#endregion export { inspectOtherOpenClawProcesses };