UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

357 lines (356 loc) • 15.7 kB
import { r as resolveRuntimeScriptPosition, t as isBunRuntime } from "./runtime-binary-QwVVJ9cA.mjs"; import { c as isUpdateCommandArgv, s as getRootOptionAwareCommandPath, u as rewriteUpdateFlagArgv } from "./cli-root-options-xlQx6o4R.mjs"; import { t as escapeRegExp } from "./regexp-dj3rRPbj.mjs"; import { n as runtimeProcessEntrypoints } from "./runtime-process-entrypoints-qiyJvDDT.mjs"; import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs"; import { a as isPidDefinitelyDead, o as readLinuxProcessStat } from "./pid-alive-D899x-ak.mjs"; import { a as readProcessWorkingDirectories, i as readProcessPackageIdentity, n as classifyOpenClawEntrypointPath, o as referencesRetainedArtifact, t as classifyOpenClawArgv } from "./gateway-process-argv-DBr2gU61.mjs"; import { a as readProcessGroupMembers } from "./service-child-group-ownership-BSRydAAE.mjs"; import { t as readDarwinProcessCommand } from "./darwin-process-command-DTx7JBYC.mjs"; import { n as parseWindowsNativeCommandLine } from "./windows-command-line-DRjGApuy.mjs"; import { t as isContainerEnvironment } from "./container-environment-BQP66a3c.mjs"; import { t as readWindowsUserSid } from "./windows-user-sid-BVw4jL2R.mjs"; import { fileURLToPath, pathToFileURL } from "node:url"; import path from "node:path"; import os from "node:os"; import { ProcSafeError } from "@openclaw/proc-safe/errors"; import { readProcessAncestry, readProcessIdentity } from "@openclaw/proc-safe/identity"; import { listProcesses } from "@openclaw/proc-safe/inspect"; import { PinnedProcess } from "@openclaw/proc-safe/windows-job"; //#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/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/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 as t };