UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

957 lines (956 loc) • 31.7 kB
import { $ as isRecord, k as extractErrorCode, q as normalizeLowercaseStringOrEmpty } from "./paths-YAGBztX6.js"; import { n as isNodeRuntime, r as resolveRuntimeScriptPosition, t as isBunRuntime } from "./runtime-binary-Cc9EAiQv.js"; import { createRequire } from "node:module"; import path from "node:path"; import fs, { readFileSync, readdirSync } from "node:fs"; import "@openclaw/fs-safe/durability"; import { createHash, hash } from "node:crypto"; import { readProcessIdentity } from "@openclaw/proc-safe/identity"; import childProcess, { spawnSync } from "node:child_process"; import { ProcSafeError } from "@openclaw/proc-safe/errors"; import { listProcesses, readProcessCommand } from "@openclaw/proc-safe/inspect"; //#region \0@oxc-project+runtime@0.154.0/helpers/esm/usingCtx.js function _usingCtx() { var e = "function" == typeof SuppressedError ? SuppressedError : function(e, t) { var n = Error(); return n.name = "SuppressedError", n.error = e, n.suppressed = t, n; }, t = {}, n = []; function using(e, t) { if (null != t) { if (Object(t) !== t) throw new TypeError("using declarations can only be used with objects, functions, null, or undefined."); if (e) var r = t[Symbol.asyncDispose || Symbol["for"]("Symbol.asyncDispose")]; if (void 0 === r && (r = t[Symbol.dispose || Symbol["for"]("Symbol.dispose")], e)) var i = r; if ("function" != typeof r) throw new TypeError("Object is not disposable."); i && (r = function o() { try { i.call(t); } catch (e) { return Promise.reject(e); } }), n.push({ v: t, d: r, a: e }); } else e && n.push({ d: t, a: e }); return t; } return { e: t, u: using.bind(null, !1), a: using.bind(null, !0), d: function d() { var r, i = this.e, a = 0; function next() { for (; r = n.pop();) try { if (!r.a && 1 === a) return a = 0, n.push(r), Promise.resolve().then(next); if (r.d) { var e = r.d.call(r.v); if (r.a) return a |= 2, Promise.resolve(e).then(next, err); } else a |= 1; } catch (e) { return err(e); } if (1 === a) return i !== t ? Promise.reject(i) : Promise.resolve(); if (i !== t) throw i; } function err(n) { return i = i !== t ? new e(n, i) : n, next(); } return next(); } }; } //#endregion //#region src/infra/process-env.ts /** Read one environment value using the same Windows key precedence as child_process. */ function resolveEnvironmentValue(e, t, n = process.platform) { if (!e) return; if (n !== "win32") return e[t] ?? (t === "PATH" ? e.Path : void 0); const r = t.toUpperCase(); const i = Object.keys(e).toSorted().find((e) => e.toUpperCase() === r); return i === void 0 ? void 0 : e[i]; } /** Merge child environments while preserving Node's platform-specific key semantics. */ function mergeProcessEnv(e, t = process.platform) { const n = Object.create(null); const r = /* @__PURE__ */ new Map(); for (const i of e) { if (!i) continue; const e = Object.keys(i); const a = /* @__PURE__ */ new Set(); for (const s of t === "win32" ? e.toSorted() : e) { const e = t === "win32" ? s.toUpperCase() : void 0; if (e !== void 0) { if (a.has(e)) continue; a.add(e); const t = r.get(e); if (t !== void 0) delete n[t]; r.delete(e); } const c = i[s]; if (c === void 0) delete n[s]; else { n[s] = c; if (e !== void 0 && Object.hasOwn(n, s)) r.set(e, s); } } } return n; } const DIAGNOSTIC_PROCESS_ENV_KEYS = /* @__PURE__ */ new Set([ "PATH", "Path", "HOME", "USER", "LOGNAME", "TMPDIR", "TMP", "TEMP", "LANG", "LANGUAGE", "TZ", "LC_ALL", "LC_COLLATE", "LC_CTYPE", "LC_MESSAGES", "LC_MONETARY", "LC_NUMERIC", "LC_TIME", "LC_ADDRESS", "LC_IDENTIFICATION", "LC_MEASUREMENT", "LC_NAME", "LC_PAPER", "LC_TELEPHONE", "SYSTEMROOT", "WINDIR", "COMSPEC", "PATHEXT", "SYSTEMDRIVE", "USERPROFILE", "HOMEDRIVE", "HOMEPATH", "USERNAME", "USERDOMAIN", "APPDATA", "LOCALAPPDATA", "PROGRAMDATA", "ALLUSERSPROFILE", "PROGRAMFILES", "PROGRAMFILES(X86)", "PROGRAMW6432", "COMMONPROGRAMFILES", "COMMONPROGRAMFILES(X86)", "COMMONPROGRAMW6432", "PSMODULEANALYSISCACHEPATH" ]); /** Project only native port/process diagnostic context; never mutate the parent environment. */ function resolveDiagnosticProcessEnv(e = process.env, t = process.platform) { return Object.fromEntries(Object.entries(mergeProcessEnv([e], t)).filter(([e]) => DIAGNOSTIC_PROCESS_ENV_KEYS.has(t === "win32" ? e.toUpperCase() : e))); } //#endregion //#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, s, c, l, u, f, p, m, h] = i; return Date.UTC(Number(a), Number(s) - 1, Number(c), Number(l), Number(u), Number(f), Math.floor(Number(p) / 1e3)) - Number(h) * 6e4 * (m === "+" ? 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 s = 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 (!s.error && s.status === 0) { const e = parseWindowsProcessStartTime(s.stdout); if (e !== null) return e; } const c = r - Date.now(); if (c <= 0) return null; const l = spawnSync(windowsWmicPath(n), [ "process", "where", `ProcessId=${e}`, "get", "CreationDate", "/value" ], { env: resolveDiagnosticProcessEnv(n, "win32"), timeout: c, windowsHide: true, stdio: [ "ignore", "pipe", "ignore" ] }); return !l.error && l.status === 0 ? parseWindowsProcessStartTime(l.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 = fs.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 = fs.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; } /** 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 //#region src/process/darwin-process-inspection.ts var DarwinProcessInspectionError = class extends Error { constructor(e, t) { super(`Darwin process inspection ${e}`, t); this.reason = e; this.name = "DarwinProcessInspectionError"; this.code = e === "deadline" ? "ETIMEDOUT" : e === "permission" ? "EPERM" : "EIO"; } }; function failure(e) { if (e instanceof DarwinProcessInspectionError) return e; const t = e && typeof e === "object" && "code" in e ? e.code : void 0; return new DarwinProcessInspectionError(t === "ETIMEDOUT" || t === "ABORT_ERR" || t === "timeout" ? "deadline" : [ "EACCES", "EPERM", "ERR_ACCESS_DENIED", "access-denied" ].includes(String(t)) ? "permission" : "unavailable", { cause: e }); } function remaining(e) { const t = Math.floor(e - performance.now()); if (t <= 0) throw new DarwinProcessInspectionError("deadline"); return t; } const states = { running: "R", sleeping: "S", stopped: "T", zombie: "Z", idle: "I", unknown: "?" }; function hasReadableTopology(e) { if (e.parentPid === void 0 || e.processGroupId === void 0 || e.state === void 0) { if (readProcessIdentity(e.pid) === null) return false; throw new DarwinProcessInspectionError("unavailable"); } return true; } function topology(e) { return { pid: e.pid, ppid: e.parentPid, pgid: e.processGroupId, state: states[e.state], owner: e.owner }; } function census(e, t) { try { const n = listProcesses({ timeoutMs: remaining(e), ...t ? { pids: t } : {} }).filter(hasReadableTopology); remaining(e); return n; } catch (t) { remaining(e); throw failure(t); } } /** Synchronous census for the process-group cleanup worker, without spawning ps. */ function* readDarwinProcessCensus(e) { const t = performance.now() + e; const n = census(t).map(topology); for (const e of n) { remaining(t); yield e; } remaining(t); } //#endregion //#region src/process/supervisor/service-child-group-ownership.ts function readLinuxProcessUid(e) { try { const t = readFileSync(`/proc/${e}/status`, "utf8").split("\n").filter((e) => e.startsWith("Uid:")); const n = (t.length === 1 ? /^Uid:[ \t]+(\d+)[ \t]+(\d+)[ \t]+(\d+)[ \t]+(\d+)[ \t]*$/.exec(t[0]) : null)?.slice(1).map(Number); const r = process.getuid?.(); return n?.every((e) => Number.isSafeInteger(e) && e <= 4294967295) ? n.find((e) => e === r) ?? n[0] : void 0; } catch { return; } } /** The caller supplies command inspection; group cleanup only reads native topology. */ function* readProcessGroupMembers(e, t) { const n = t !== void 0; if (process.platform === "linux") { const t = Date.now() + e; for (const e of readdirSync("/proc")) { if (Date.now() >= t) throw new Error("Process group census exceeded its deadline"); if (!/^\d+$/.test(e)) continue; const r = Number(e); let i; let a; let s; let c = false; try { i = readFileSync(`/proc/${e}/stat`, "utf8"); if (n) { s = readLinuxProcessUid(r); try { a = readFileSync(`/proc/${e}/cmdline`, "utf8").split("\0").filter(Boolean); } catch (e) { const t = process.getuid?.(); c = s !== void 0 && t !== void 0 && s !== t && ["EACCES", "EPERM"].includes(extractErrorCode(e) ?? ""); if (!c) throw e; } } } catch (e) { if (r !== process.pid && ["ENOENT", "ESRCH"].includes(extractErrorCode(e) ?? "")) continue; throw new Error(`Could not classify PID ${r}: process command inspection failed (${extractErrorCode(e) ?? "unavailable"}).`, { cause: e }); } const l = /^(\d+) \([\s\S]*\) (\S) (\d+) (-1|\d+)(?:\s|$)/.exec(i); if (!l || Number(l[1]) !== r || Date.now() >= t) throw new Error("Process group census is unavailable"); if (a?.length === 0) { const e = Number(i.slice(i.lastIndexOf(")") + 2).split(/\s+/)[6]); if (!(Number.isInteger(e) && (e & 2097152) !== 0) && !isPidDefinitelyDead(r)) { const e = process.getuid?.(); if (s !== void 0 && e !== void 0 && s !== e) { c = true; a = void 0; } else throw new Error(`Could not classify PID ${r}: live userspace process has no readable arguments.`); } } yield { pid: r, pgid: Number(l[4]), state: l[2], ...a ? { command: { ppid: Number(l[3]), argv: a, ...s === void 0 ? {} : { uid: s } } } : c && s !== void 0 ? { command: { ppid: Number(l[3]), argvUnavailable: true, uid: s } } : {} }; } if (Date.now() >= t) throw new Error("Process group census exceeded its deadline"); return; } if (process.platform === "darwin") { for (const r of readDarwinProcessCensus(e)) { const e = { pid: r.pid, pgid: r.pgid, state: r.state }; let i; try { i = n ? r.state.startsWith("Z") || r.pid === 0 ? { argv: [] } : t?.readDarwinCommand(r.pid, r.owner) : void 0; } catch (t) { if (!(t instanceof ProcSafeError) || t.code !== "incomplete" && t.code !== "layout-mismatch") throw t; yield { ...e, ppid: r.ppid }; continue; } if (n && !i) continue; yield { ...e, ...i ? { command: { ppid: r.ppid, owner: r.owner, ...i } } : {} }; } return; } if (n) throw new Error(`Exact process command census is unavailable on ${process.platform}.`); const r = Date.now() + e; const i = spawnSync("/bin/ps", [ "-A", "-o", "pid=,pgid=,stat=" ], { encoding: "utf8", timeout: e, maxBuffer: 4194304 }); if (i.error || i.status !== 0) throw new Error("Process group census is unavailable"); for (const e of i.stdout.split("\n")) { if (!e.trim()) continue; const t = /^\s*(\d+)\s+(\d+)\s+(\S+)\s*$/.exec(e); if (!t) throw new Error("Process group census is unavailable"); const n = Number(t[1]); if (n !== i.pid) yield { pid: n, pgid: Number(t[2]), state: t[3] }; } if (n && Date.now() >= r) throw new Error("Process group census exceeded its deadline"); } //#endregion //#region cli-root-options.mjs /** CLI token that stops root option scanning and leaves following args positional. */ const FLAG_TERMINATOR = "--"; const ROOT_BOOLEAN_FLAGS = /* @__PURE__ */ new Set(["--dev", "--no-color"]); const ROOT_VALUE_FLAGS = /* @__PURE__ */ new Set([ "--profile", "--log-level", "--container" ]); /** Returns whether a token can be consumed as a root option value. */ function isValueToken(e) { if (!e || e === "--") return false; if (!e.startsWith("-")) return true; return /^-\d+(?:\.\d+)?$/.test(e); } /** Count root-option tokens conservatively for route matching. */ function consumeRootOptionToken(e, t) { const n = e[t]; if (!n) return 0; if (ROOT_BOOLEAN_FLAGS.has(n)) return 1; if (n.startsWith("--profile=") || n.startsWith("--log-level=") || n.startsWith("--container=")) return 1; if (ROOT_VALUE_FLAGS.has(n)) return isValueToken(e[t + 1]) ? 2 : 1; return 0; } /** Consume required root values by their Commander role before startup policy is selected. */ function consumeRootCommandOptionToken(e, t) { return consumeKnownOptionToken(e, t, ROOT_BOOLEAN_FLAGS, ROOT_VALUE_FLAGS, "command-path"); } /** Read positional command tokens while accepting root options at any pre-terminator position. */ function getRootOptionAwareCommandPath(e, t) { const n = e.slice(2); const r = []; let i = false; for (let e = 0; e < n.length; e += 1) { const a = n[e]; if (!a) break; if (!i && a === "--") { if (r.length > 0) break; i = true; continue; } const s = i ? 0 : consumeRootCommandOptionToken(n, e); if (s > 0) { e += s - 1; continue; } if (!i && a.startsWith("-")) continue; r.push(a); if (r.length >= t) break; } return r; } function rewriteUpdateFlagArgv(e) { const t = e.indexOf("--update"); if (t === -1) return e; for (let n = 2; n < e.length; n++) { const r = e[n]; if (!r || r === "--") return e; if (n === t) return [ ...e.slice(0, t), "update", ...e.slice(t + 1) ]; const i = consumeRootOptionToken(e, n); if (i > 0) { n += i - 1; continue; } if (!r.startsWith("-")) return e; } return e; } /** Launchers choose their signal budget before the CLI parses, so accept both spellings. */ function isUpdateCommandArgv(e) { return getRootOptionAwareCommandPath(rewriteUpdateFlagArgv(e), 1)[0] === "update"; } function consumeKnownOptionToken(e, t, n, r, i) { const a = e[t]; if (!a || a === "--" || !a.startsWith("-")) return 0; const s = a.indexOf("="); const c = s === -1 ? a : a.slice(0, s); if (n.has(c)) return s === -1 ? 1 : 0; if (!r.has(c)) return 0; if (s !== -1) return i === "command-path" || a.slice(s + 1).trim() ? 1 : 0; if (i === "command-path") return e[t + 1] !== void 0 ? 2 : 0; return isValueToken(e[t + 1]) ? 2 : 0; } /** Parse command positionals while consuming known root and command options. */ function getCommandPositionalsWithRootOptions(e, t) { return parseCommandArgsWithRootOptions(e, t, false); } function parseCommandArgsWithRootOptions(e, t, n, r = false) { const i = e.slice(2); const a = new Set(t.booleanFlags ?? []); const s = new Set(t.valueFlags ?? []); const c = []; const l = []; const u = []; let f = 0; let p = false; for (let e = 0; e < i.length; e += 1) { const m = i[e]; if (m === void 0) break; if (!p && m === "--") { if (t.mode !== "command-path") break; p = true; continue; } const h = p ? 0 : t.mode === "command-path" ? consumeRootCommandOptionToken(i, e) : consumeRootOptionToken(i, e); if (h > 0) { (f > 0 && a.has(m) ? u : l).push(...i.slice(e, e + h)); e += h - 1; continue; } if (!p && m.startsWith("-")) { const n = consumeKnownOptionToken(i, e, a, s, t.mode); if (n === 0 || f === 0) return null; u.push(m); e += n - 1; continue; } if (f < t.commandPath.length) { if (m !== t.commandPath[f]) return null; f += 1; if (n && f === t.commandPath.length) { const t = i.slice(e + 1); return p ? ["--", ...t] : t; } continue; } c.push(m); if (!r && c.length === t.maxPositionals) return c; } return f < t.commandPath.length ? null : r ? { rootOptions: l, commandOptions: u } : c; } //#endregion //#region src/plugins/plugin-source-capture-path.ts const PLUGIN_SOURCE_CAPTURE_PREFIX = "openclaw-plugin-build-"; function isLegacyPluginSourceCaptureName(e) { return e.startsWith("openclaw-plugin-build-") || e.startsWith("openclaw-model-catalog-"); } //#endregion //#region src/infra/gateway-process-argv.ts function normalizeProcArg(e) { return normalizeLowercaseStringOrEmpty(e.replaceAll("\\", "/")); } const ENTRY_CANDIDATES = [ "openclaw.mjs", "dist/index.js", "dist/entry.js", "scripts/run-node.mjs", "src/entry.ts", "src/index.ts" ]; function referencesRetainedArtifact(e) { return e.split(/[\\/=]/u).some((e) => isLegacyPluginSourceCaptureName(e) || /^openclaw-update-runtime-[A-Za-z0-9]{6}$/u.test(e)); } /** Exhausted lookup proves absence; unreadable identities stay unresolved. */ function readProcessPackageIdentity(e, t = false) { for (let n = e;;) { let e; try { e = JSON.parse(fs.readFileSync(path.join(n, "package.json"), "utf8")); } catch (e) { const r = path.dirname(n); if (t && extractErrorCode(e) === "ENOENT") { if (r === n) return { kind: "absent" }; if (path.basename(n) === "node_modules") return { kind: "unknown", reason: "could not read package identity" }; n = r; continue; } return { kind: "unknown", reason: "could not read package identity" }; } if (!isRecord(e) || typeof e.name !== "string" || !e.name.trim() || e.name !== e.name.trim()) return { kind: "unknown", reason: "package identity has no valid name" }; return { kind: "package", name: e.name, scripts: isRecord(e.scripts) ? e.scripts : {} }; } } function readProcessWorkingDirectories(e) { const t = new Set(e.filter((e) => Number.isSafeInteger(e) && e > 0)); const n = /* @__PURE__ */ new Map(); if (t.size === 0) return n; if (process.platform === "linux") { for (const e of t) try { n.set(e, fs.readlinkSync(`/proc/${e}/cwd`)); } catch {} return n; } try { if (process.platform === "darwin") { const e = spawnSync("/usr/sbin/lsof", [ "-a", "-p", [...t].join(","), "-d", "cwd", "-F0pn" ], { encoding: "utf8", timeout: 5e3, maxBuffer: 4194304, env: resolveDiagnosticProcessEnv() }); if (e.error || e.status !== 0 && e.status !== 1) return n; const r = e.stdout.split("\0"); r.pop(); const i = /* @__PURE__ */ new Set(); let a; for (const e of r) { const r = e.replace(/^\n/, ""); if (r.startsWith("p")) { const e = /^p(\d+)$/.exec(r); a = e && t.has(Number(e[1])) ? Number(e[1]) : void 0; } else if (a !== void 0 && r.startsWith("n") && path.isAbsolute(r.slice(1))) { if (n.delete(a)) i.add(a); else if (!i.has(a)) n.set(a, r.slice(1)); } } } } catch {} return n; } /** Generic script names identify OpenClaw only inside a verified package root. */ function classifyEntrypoint(e, t = {}) { const n = normalizeProcArg(e[0] ?? "").replace(/\.(bat|cmd|exe)$/i, ""); if (!t.requirePackageIdentity && (n.endsWith("/openclaw") || n === "openclaw")) return { kind: "openclaw", entryIndex: 0 }; const r = /(?:^|\/)openclaw\.mjs$/.test(n) ? 0 : resolveRuntimeScriptPosition(e).position; if (typeof r !== "number") return r.kind === "unclassified" ? { kind: "unclassified", cause: "runtime-syntax", reason: r.reason } : { kind: "other" }; const i = e[r]; if (t.inspectPackage && !t.requirePackageIdentity && t.cwd && path.isAbsolute(t.cwd) && isBunRuntime(e[0] ?? "") && !/[\\/]/u.test(i) && !path.extname(i)) { const e = readProcessPackageIdentity(t.cwd, true); if (e.kind === "unknown") return { kind: "unclassified", cause: "package-identity", reason: e.reason }; const n = e.kind === "package" ? e.scripts[i] : void 0; if (typeof n === "string" && n.trim()) return e.kind === "package" && e.name === "openclaw" ? { kind: "openclaw" } : { kind: "other" }; } const a = classifyOpenClawEntrypointPath(i, t); return a.kind === "openclaw" ? { ...a, entryIndex: r } : a; } /** Path evidence is shared with cleanup even when launcher syntax is unfamiliar. */ function classifyOpenClawEntrypointPath(e, t = {}) { const n = normalizeProcArg(e); if (!t.requirePackageIdentity && !t.inspectPackage && /(?:^|\/)openclaw\.mjs$/.test(n)) return { kind: "openclaw" }; const r = [...ENTRY_CANDIDATES, ...t.additionalEntrypoints ?? []]; let i = e; if (!path.isAbsolute(e)) { const n = t.cwd ?? (t.pid === void 0 ? void 0 : readProcessWorkingDirectories([t.pid]).get(t.pid)); if (!n || !path.isAbsolute(n)) return { kind: "unclassified", cause: "cwd", reason: "working directory is unavailable" }; i = path.resolve(n, e); } let a; let s; try { a = fs.realpathSync(i); if (t.inspectPackage && !t.requirePackageIdentity && referencesRetainedArtifact(a)) return { kind: "openclaw", artifactPath: a }; const n = t.requirePackageIdentity || t.inspectPackage ? fs.statSync(a) : void 0; if (t.requirePackageIdentity && !n?.isFile()) return { kind: "unclassified", cause: "script", reason: `entrypoint is not a regular file: ${e}` }; s = n?.isDirectory() ?? false; } catch { return { kind: "unclassified", cause: "script", reason: "could not resolve script" }; } const c = normalizeProcArg(a); if (!t.requirePackageIdentity && /(?:^|\/)openclaw\.mjs$/.test(n)) return { kind: "openclaw" }; const l = s ? void 0 : r.find((e) => c.endsWith(`/${e}`)); if (!l && (!t.inspectPackage || t.requirePackageIdentity)) return { kind: "other" }; const u = l ? a.slice(0, -l.length) : s ? a : path.dirname(a); const f = readProcessPackageIdentity(u, t.inspectPackage && !t.requirePackageIdentity || !l && !s); if (f.kind === "unknown") return { kind: "unclassified", cause: "package-identity", reason: f.reason }; return f.kind === "package" && f.name === "openclaw" ? { kind: "openclaw", ...t.requirePackageIdentity ? { packageIdentity: { root: path.resolve(u), entrypoint: a } } : {} } : { kind: "other" }; } /** One classification for process owners, command consumers, and diagnostics. */ function classifyOpenClawArgv(e, t = {}) { const { command: n, owner: r, pid: i, port: a } = t; if (!t.requirePackageIdentity && n === "gateway" && r?.pid === i && r?.state === "live" && (a === void 0 || r.port === a)) return { kind: "openclaw" }; const s = normalizeProcArg(e[0] ?? "").split("/").at(-1)?.replace(/\.(exe|cmd|bat)$/, "") ?? ""; if (!t.requirePackageIdentity && /^openclaw-[a-z0-9-]+$/.test(s)) return !n || s === `openclaw-${n}` ? { kind: "openclaw" } : { kind: "other" }; const c = classifyEntrypoint(e, t); if (n) return c.kind === "openclaw" && normalizeProcArg(getRootOptionAwareCommandPath(["node", ...e.slice(c.entryIndex)], 1)[0] ?? "") !== n ? { kind: "other" } : c; if (c.kind === "openclaw" || !t.requirePackageIdentity && e.some((e) => e.replaceAll("\\", "/").split("/").some(isLegacyPluginSourceCaptureName))) return c.kind === "openclaw" ? c : { kind: "openclaw" }; if (t.serviceMarkerUnavailable && !t.requirePackageIdentity) return { kind: "unclassified", cause: "service-marker", reason: "process environment is unreadable" }; let l = t.serviceMarker; if (i !== void 0 && process.platform === "linux" && (isNodeRuntime(s) || isBunRuntime(s) || s === "tsx")) try { l = fs.readFileSync(`/proc/${i}/environ`, "utf8").split("\0").find((e) => e.startsWith("OPENCLAW_SERVICE_MARKER="))?.slice(24); } catch (e) { return { kind: "unclassified", cause: "service-marker", reason: `process identity inspection failed (${extractErrorCode(e) ?? "unavailable"})` }; } return !t.requirePackageIdentity && l === "openclaw" ? { kind: "openclaw" } : c; } //#endregion export { _usingCtx as _, referencesRetainedArtifact as a, isUpdateCommandArgv as c, getFileLockProcessStartTime as d, isPidAlive as f, resolveDiagnosticProcessEnv as g, mergeProcessEnv as h, readProcessWorkingDirectories as i, rewriteUpdateFlagArgv as l, readLinuxProcessStat as m, classifyOpenClawEntrypointPath as n, getCommandPositionalsWithRootOptions as o, isPidDefinitelyDead as p, readProcessPackageIdentity as r, getRootOptionAwareCommandPath as s, classifyOpenClawArgv as t, readProcessGroupMembers as u };