openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
291 lines (290 loc) • 12.5 kB
JavaScript
import { L as normalizeLowercaseStringOrEmpty, W as resolveGlobalSingleton } from "./path-guards-quCEQx1i.mjs";
import { h as AsyncContext, l as areDiagnosticsEnabledForProcess } from "./subsystem-CeOCPr4l.mjs";
import "./runtime-process-entrypoints-EnWn_nGl.mjs";
import "./host-CAR9TGXT.mjs";
import { AsyncLocalStorage } from "node:async_hooks";
import { spawn } from "node:child_process";
import fsSync from "node:fs";
import path from "node:path";
import os from "node:os";
//#region src/process/spawn-broker/context.ts
const context = new AsyncContext(Symbol("spawnBroker"));
let gatewayStartupDisabled = false;
function getSpawnBroker() {
return gatewayStartupDisabled ? void 0 : context.getStore();
}
//#endregion
//#region src/infra/shell-inline-command.ts
const POSIX_INLINE_COMMAND_FLAGS = /* @__PURE__ */ new Set([
"-lc",
"-c",
"--command",
"--commands",
"--cmdline"
]);
const NUSHELL_INLINE_COMMAND_FLAGS = /* @__PURE__ */ new Set([
...POSIX_INLINE_COMMAND_FLAGS,
"-e",
"--execute"
]);
function expandPowerShellSwitchPrefixForms(e, t) {
const n = [];
for (let r = t.length; r <= e.length; r += 1) {
const t = e.slice(0, r);
n.push(`-${t}`, `--${t}`, `/${t}`);
}
return n;
}
function expandPowerShellSwitchForms(e) {
return e.flatMap((e) => {
const t = normalizeLowercaseStringOrEmpty(e);
return [
`-${t}`,
`--${t}`,
`/${t}`
];
});
}
const POWERSHELL_COMMAND_FLAGS = [
...expandPowerShellSwitchPrefixForms("command", "c"),
...expandPowerShellSwitchPrefixForms("commandwithargs", "cwa"),
...expandPowerShellSwitchForms(["cwa"])
];
const POWERSHELL_FILE_FLAGS = expandPowerShellSwitchPrefixForms("file", "f");
const POWERSHELL_INLINE_FILE_FLAGS = new Set(POWERSHELL_FILE_FLAGS);
const POWERSHELL_NO_PROFILE_FLAGS = new Set(expandPowerShellSwitchPrefixForms("noprofile", "nop"));
const POWERSHELL_UNREVIEWED_STARTUP_FLAGS = /* @__PURE__ */ new Set([
...expandPowerShellSwitchPrefixForms("configurationfile", "conf"),
...expandPowerShellSwitchPrefixForms("configurationname", "config"),
...expandPowerShellSwitchPrefixForms("custompipename", "cus"),
...expandPowerShellSwitchPrefixForms("encodedarguments", "encodeda"),
...expandPowerShellSwitchForms(["ea"]),
...expandPowerShellSwitchPrefixForms("interactive", "i"),
...expandPowerShellSwitchPrefixForms("login", "l"),
...expandPowerShellSwitchPrefixForms("namedpipeservermode", "nam"),
...expandPowerShellSwitchPrefixForms("noexit", "noe"),
...expandPowerShellSwitchPrefixForms("psconsolefile", "pscf"),
...expandPowerShellSwitchForms(["pscf"]),
...expandPowerShellSwitchPrefixForms("servermode", "s"),
...expandPowerShellSwitchPrefixForms("settingsfile", "settings"),
...expandPowerShellSwitchPrefixForms("socketservermode", "so"),
...expandPowerShellSwitchPrefixForms("sshservermode", "ssh"),
...expandPowerShellSwitchPrefixForms("v2socketservermode", "v2so")
]);
const POWERSHELL_INLINE_ENCODED_COMMAND_FLAGS = /* @__PURE__ */ new Set([...expandPowerShellSwitchPrefixForms("encodedcommand", "e"), ...expandPowerShellSwitchPrefixForms("ec", "e")]);
const POWERSHELL_INLINE_COMMAND_FLAGS = /* @__PURE__ */ new Set([
...POWERSHELL_COMMAND_FLAGS,
...POWERSHELL_FILE_FLAGS,
...POWERSHELL_INLINE_ENCODED_COMMAND_FLAGS
]);
const POWERSHELL_INLINE_REST_COMMAND_FLAGS = new Set(POWERSHELL_COMMAND_FLAGS);
const POWERSHELL_OPTIONS_WITH_SEPARATE_VALUES = /* @__PURE__ */ new Set([
...expandPowerShellSwitchPrefixForms("configurationfile", "conf"),
...expandPowerShellSwitchPrefixForms("configurationname", "config"),
...expandPowerShellSwitchPrefixForms("custompipename", "cus"),
...expandPowerShellSwitchPrefixForms("encodedarguments", "encodeda"),
...expandPowerShellSwitchPrefixForms("executionpolicy", "ex"),
...expandPowerShellSwitchPrefixForms("inputformat", "inp"),
...expandPowerShellSwitchPrefixForms("outputformat", "o"),
...expandPowerShellSwitchPrefixForms("psconsolefile", "pscf"),
...expandPowerShellSwitchPrefixForms("settingsfile", "settings"),
...expandPowerShellSwitchPrefixForms("token", "to"),
...expandPowerShellSwitchPrefixForms("utctimestamp", "utc"),
...expandPowerShellSwitchPrefixForms("version", "v"),
...expandPowerShellSwitchPrefixForms("windowstyle", "w"),
...expandPowerShellSwitchPrefixForms("workingdirectory", "w"),
...expandPowerShellSwitchForms([
"ea",
"ep",
"if",
"of",
"pscf",
"wd"
])
]);
const POSIX_SHELL_OPTIONS_WITH_SEPARATE_VALUES = /* @__PURE__ */ new Set([
"--init-file",
"--rcfile",
"-O",
"-o",
"+O",
"+o"
]);
function countSeparateValueOptionChars(e) {
let t = 0;
for (let n = 1; n < e.length; n += 1) {
const r = e[n];
if (r === "o" || r === "O") t += 1;
}
return t;
}
function parseCombinedCommandFlag(e) {
if (e.length < 2 || e[0] !== "-" || e[1] === "-") return null;
const t = e.slice(1);
const n = t.indexOf("c");
if (n === -1 || t.includes("-")) return null;
const r = t.slice(n + 1);
if (r && !/^[A-Za-z]+$/.test(r)) return {
attachedCommand: r,
separateValueCount: 0
};
return {
attachedCommand: null,
separateValueCount: countSeparateValueOptionChars(e)
};
}
function combinedSeparateValueOptionCount(e) {
if (e.length < 2 || e[0] !== "-" && e[0] !== "+" || e[1] === "-" || e.slice(1).includes("-")) return 0;
return countSeparateValueOptionChars(e);
}
/** Return how many argv tokens a POSIX shell option consumes while scanning. */
function advancePosixInlineOptionScan(e) {
const t = combinedSeparateValueOptionCount(e);
if (t > 0) return 1 + t;
if (POSIX_SHELL_OPTIONS_WITH_SEPARATE_VALUES.has(e)) return 2;
return 1;
}
function isPowerShellOptionToken(e) {
return e.startsWith("-") || /^\/[A-Za-z][A-Za-z0-9]*$/.test(e);
}
/** Find the inline command payload for a shell wrapper argv. */
function resolveInlineCommandMatch(e, t, n = {}) {
for (let r = 1; r < e.length;) {
const i = e[r]?.trim();
if (!i) {
r += 1;
continue;
}
const a = normalizeLowercaseStringOrEmpty(i);
if (a === "--") break;
const o = n.allowCombinedC ? i : a;
const s = t.has(o);
const c = !s && n.allowCombinedC ? parseCombinedCommandFlag(i) : null;
if (s || c) {
if (c && c.attachedCommand !== null) return {
command: c.attachedCommand.trim() || null,
valueTokenIndex: r
};
const t = r + 1 + (c?.separateValueCount ?? 0);
const i = !c && t >= e.length ? null : t;
const a = s && n.restValueFlags?.has(o) ? e.slice(r + 1).map((e) => e.trim()).join(" ").trim() : e[t]?.trim();
return {
command: a ? a : null,
valueTokenIndex: i
};
}
if (n.valueOptions?.has(a)) {
r += 2;
continue;
}
const l = n.isOptionToken?.(i) ?? (i.startsWith("-") || i.startsWith("+"));
if (n.stopAtFirstNonOption && !l) break;
if (n.allowCombinedC && !i.startsWith("-") && !i.startsWith("+")) break;
r += n.allowCombinedC ? advancePosixInlineOptionScan(i) : 1;
}
return {
command: null,
valueTokenIndex: null
};
}
/** Find the PowerShell inline command payload and value token index. */
function resolvePowerShellInlineCommandMatch(e) {
return resolveInlineCommandMatch(e, POWERSHELL_INLINE_COMMAND_FLAGS, {
isOptionToken: isPowerShellOptionToken,
restValueFlags: POWERSHELL_INLINE_REST_COMMAND_FLAGS,
stopAtFirstNonOption: true,
valueOptions: POWERSHELL_OPTIONS_WITH_SEPARATE_VALUES
});
}
/** Return true when a PowerShell flag treats the next token as script file text. */
function isPowerShellInlineFileCommandFlag(e) {
return POWERSHELL_INLINE_FILE_FLAGS.has(normalizeLowercaseStringOrEmpty(e));
}
//#endregion
//#region src/process/linux-oom-score-spawn.ts
const OOM_SCORE_WRAP_SHELL = "/bin/sh";
const OOM_SCORE_WRAP_SCRIPT = "echo 1000 > /proc/self/oom_score_adj 2>/dev/null; exec \"$0\" \"$@\"";
const OOM_SCORE_RESTORE_EXEC_ENV_SCRIPT = [
"echo 1000 > /proc/self/oom_score_adj 2>/dev/null; if [ \"${OC_INTERNAL_OOM_EXEC_BASH_ENV+x}\" = x ]; then BASH_ENV=\"$OC_INTERNAL_OOM_EXEC_BASH_ENV\"; export BASH_ENV; fi; unset OC_INTERNAL_OOM_EXEC_BASH_ENV",
"if [ \"${OC_INTERNAL_OOM_EXEC_ENV+x}\" = x ]; then ENV=\"$OC_INTERNAL_OOM_EXEC_ENV\"; export ENV; fi; unset OC_INTERNAL_OOM_EXEC_ENV",
"if [ \"${OC_INTERNAL_OOM_EXEC_CDPATH+x}\" = x ]; then CDPATH=\"$OC_INTERNAL_OOM_EXEC_CDPATH\"; export CDPATH; fi; unset OC_INTERNAL_OOM_EXEC_CDPATH",
"if [ \"${OC_INTERNAL_OOM_EXEC_PS4+x}\" = x ]; then PS4=\"$OC_INTERNAL_OOM_EXEC_PS4\"; export PS4; fi; unset OC_INTERNAL_OOM_EXEC_PS4; exec \"$0\" \"$@\""
].join("; ");
/** Diagnostics attribute the final command without changing the wrapper's execution policy. */
function resolveOomScoreWrappedCommand(e, t) {
return e === "/bin/sh" && t[0] === "-c" && (t[1] === "echo 1000 > /proc/self/oom_score_adj 2>/dev/null; exec \"$0\" \"$@\"" || t[1] === OOM_SCORE_RESTORE_EXEC_ENV_SCRIPT) && t[2] ? t[2] : void 0;
}
//#endregion
//#region src/process/spawn-diagnostics.ts
const spawnCounts = resolveGlobalSingleton(Symbol.for("openclaw.childProcessSpawnCounts"), () => ({
counts: /* @__PURE__ */ new Map(),
sampledAt: performance.now()
}));
const COMMAND_FAMILIES = /^(node|bun|git|ps|pgrep|lsof|sh|bash|zsh|cmd|powershell|pwsh|npm|pnpm|python|python3|uv|ssh|openclaw)$/;
const gitOperation = resolveGlobalSingleton(Symbol.for("openclaw.gitSpawnOperation"), () => new AsyncLocalStorage());
const childOperation = resolveGlobalSingleton(Symbol.for("openclaw.childSpawnOperation"), () => new AsyncLocalStorage());
function unscopedProcessOperation(e, t, n) {
if (n[0] === "--version" || n[0] === "-v" && (e === "node" || e === "bun" || t === "gh")) return "unscoped.version";
if (e === "powershell" || e === "pwsh") {
const e = [t, ...n];
const { command: r, valueTokenIndex: i } = resolvePowerShellInlineCommandMatch(e);
return r !== null && i !== null && !isPowerShellInlineFileCommandFlag(e[i - 1] ?? "") ? "unscoped.shell-command" : "unscoped.shell";
}
if (/^(sh|bash|zsh)$/.test(e)) return resolveInlineCommandMatch([t, ...n], POSIX_INLINE_COMMAND_FLAGS, { allowCombinedC: true }).command !== null ? "unscoped.shell-command" : "unscoped.shell";
if (e === "cmd") return n.some((e) => /^-[a-z]*c$/.test(e) || /^\/(?:c|k)$/i.test(e)) ? "unscoped.shell-command" : "unscoped.shell";
if (e === "node" || e === "bun") return "unscoped.runtime";
if (e === "other" && /^(gh|docker|podman|which|uname|sw_vers|sysctl|curl|tar)$/.test(t)) return `unscoped.${t}`;
return "unscoped.command";
}
function unscopedGitOperation(e) {
let t = 0;
while (t < e.length) {
const n = e[t];
if ([
"-C",
"-c",
"--git-dir",
"--work-tree",
"--namespace",
"--config-env"
].includes(n)) t += 2;
else if (/^--(?:git-dir|work-tree|namespace|config-env|attr-source)=/u.test(n)) t++;
else if ([
"--no-pager",
"--no-optional-locks",
"--no-lazy-fetch",
"--literal-pathspecs",
"--bare"
].includes(n)) t++;
else break;
}
const n = e[t] ?? "";
return /^(config|rev-parse|status|diff|ls-files|rev-list|merge-base|cat-file|symbolic-ref|for-each-ref|show-ref|remote|log|show|hash-object|update-ref|worktree|branch|fetch|clone|init|checkout|read-tree|write-tree|commit-tree|pack-objects|index-pack|maintenance|multi-pack-index|gc|fast-import|add|commit|push|reset|clean|merge|tag|describe|switch|ls-tree|update-index|check-ref-format|diff-tree|diff-index|diff-files|sparse-checkout|checkout-index|check-attr|mktree|var|apply|fsck|ls-remote|rebase|reflog)$/u.test(n) ? `unscoped.${n}` : n === "--version" || n === "version" ? "unscoped.version" : "unscoped.other";
}
/** Capture attribution before native preparation; record only after a successful launch. */
function prepareChildProcessSpawnRecorder(e, t = [], n) {
if (!areDiagnosticsEnabledForProcess()) return;
const r = resolveOomScoreWrappedCommand(e, t);
const i = r ? t.slice(3) : t;
const a = path.win32.basename(r ?? e).toLowerCase().replace(/\.(exe|cmd)$/, "");
const o = COMMAND_FAMILIES.test(a) ? a : "other";
const s = o === "git" ? gitOperation.getStore() ?? childOperation.getStore() ?? unscopedGitOperation(i) : n ?? childOperation.getStore() ?? unscopedProcessOperation(o, a, i);
const c = `${o}:${s}`;
return () => {
if (areDiagnosticsEnabledForProcess()) {
const e = spawnCounts.counts.get(c);
spawnCounts.counts.set(c, {
family: o,
operation: s,
count: (e?.count ?? 0) + 1
});
}
};
}
/** Count admitted local and broker launches, excluding failed spawn attempts. */
function recordChildProcessSpawn(e, t, n, r = []) {
const i = prepareChildProcessSpawnRecorder(e, r, n);
if (i) t.once("spawn", i);
}
//#endregion
export { getSpawnBroker as n, recordChildProcessSpawn as t };