UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

250 lines (249 loc) • 10.2 kB
import { d as resolveGatewayLaunchAgentLabel, l as isNodeLaunchAgentLabel } from "./constants-BZisy3jr.mjs"; import { n as sanitizeForLog } from "./ansi-CZa2t0Hf.mjs"; import { r as terminalText } from "./safe-text-C80HAQ2e.mjs"; import { n as resolveLaunchAgentLabel } from "./launchd-label-DdmmL_TH.mjs"; import { b as isLaunchctlNotLoaded, v as execLaunchctl, y as formatLaunchctlResultDetail } from "./launchd-service-files-BgSRMq9s.mjs"; import { g as resolveLaunchAgentGuiDomain, l as parseLaunchctlJob } from "./launchd-runtime-DS9pQoDc.mjs"; import { constants } from "node:fs"; import path from "node:path"; import fs$1 from "node:fs/promises"; //#region src/daemon/launchd-foreign-jobs.ts const MAX_JOBS = 64; const INSPECTION_TIMEOUT_MS = 2e3; const MAX_FILE_BYTES = 65536; const SHELLS = /* @__PURE__ */ new Set([ "sh", "bash", "zsh", "dash", "ksh" ]); const SHELL_EXECUTION_ENV_NAMES = /* @__PURE__ */ new Set([ "SHELLOPTS", "BASHOPTS", "BASH_ENV", "ENV", "ZDOTDIR", "POSIXLY_CORRECT", "IFS", "CDPATH", "PS4", "BASH_XTRACEFD" ]); function hasShellExecutionEnvironment(e) { for (const [, t] of e.matchAll(/^\t\t(.+?) => /gm)) if (t && (SHELL_EXECUTION_ENV_NAMES.has(t) || t.startsWith("BASH_"))) return true; return false; } function isCandidate(e, t) { return /^ai\.openclaw\.[A-Za-z0-9._-]+$/.test(e) && !isNodeLaunchAgentLabel(e) && !(/* @__PURE__ */ new Set([ resolveGatewayLaunchAgentLabel(), resolveGatewayLaunchAgentLabel(t.OPENCLAW_PROFILE), resolveLaunchAgentLabel(t) ])).has(e); } function lifecycleInvocation(e) { if (e.some((e) => [ "--help", "-h", "--version", "-V" ].includes(e))) return; let t = e; if (path.basename(t[0] ?? "") === "env") { t = t.slice(1); while (/^[A-Za-z_][A-Za-z0-9_]*=/.test(t[0] ?? "")) t = t.slice(1); } const n = t[0] ?? ""; if (!path.isAbsolute(n)) return; if (["node", "bun"].includes(path.basename(t[0] ?? ""))) { t = t.slice(1); if (path.basename(t[0] ?? "") !== "openclaw.mjs") return; } if (!path.isAbsolute(t[0] ?? "") || !["openclaw", "openclaw.mjs"].includes(path.basename(t[0] ?? ""))) return; t = t.slice(1); if (t[0] === "--profile" && t[1]) t = t.slice(2); const r = t[1]; return t[0] === "gateway" && (r === "restart" || r === "start" || r === "stop") ? { action: r, program: n } : void 0; } const SCRIPT_HELPER_NAME = /(?:openclaw_|OPENCLAW_)[A-Za-z0-9_]*/; const SCRIPT_LITERAL_EXEC = String.raw`/(?:[A-Za-z0-9_.-]+/)*openclaw(?:\.mjs)?`; const SCRIPT_HELPER_REF = String.raw`\$(?:${SCRIPT_HELPER_NAME.source}|\{${SCRIPT_HELPER_NAME.source}\})`; const SCRIPT_LINE_END = String.raw`$(?![\s\S])`; const SCRIPT_EXECUTABLE = new RegExp(`^${SCRIPT_LITERAL_EXEC}${SCRIPT_LINE_END}`); const SCRIPT_ASSIGNMENT = new RegExp(String.raw`^[ \t]*(?:export[ \t]+)?(${SCRIPT_HELPER_NAME.source})=([A-Za-z0-9_./-]+)[ \t]*${SCRIPT_LINE_END}`); const SCRIPT_INVOCATION = new RegExp(String.raw`^[ \t]*(?:exec[ \t]+)?(${SCRIPT_LITERAL_EXEC}|${SCRIPT_HELPER_REF}|"${SCRIPT_HELPER_REF}")[ \t]+gateway[ \t]+(restart|start|stop)((?:[ \t]+[A-Za-z0-9_.=/:-]+)*)[ \t]*${SCRIPT_LINE_END}`); function scriptActions(e) { if (e.includes("\r") || e.includes("<<") || e.includes("\\\n")) return []; const t = /* @__PURE__ */ new Map(); for (const n of e.split("\n")) { if (/^[ \t]*(?:#.*)?$(?![\s\S])/.test(n)) continue; if (/^[ \t]*set(?:[ \t]+[+-][eux])+[ \t]*$(?![\s\S])/.test(n) || /^[ \t]*set[ \t]+-o[ \t]+pipefail[ \t]*$(?![\s\S])/.test(n)) continue; const e = SCRIPT_ASSIGNMENT.exec(n); if (e?.[1] && e[2]) { t.set(e[1], e[2]); continue; } const r = SCRIPT_INVOCATION.exec(n); const i = r?.[1]; const a = r?.[2]; if (!i || a !== "restart" && a !== "start" && a !== "stop") return []; if (!SCRIPT_EXECUTABLE.test(i)) { const e = i.match(SCRIPT_HELPER_NAME)?.[0]; const n = e && t.get(e); if (!n || !SCRIPT_EXECUTABLE.test(n)) return []; } if (/(?:^|[ \t])(?:-h|--help|-V|--version)(?:[ \t]|$)/.test(r?.[3] ?? "")) return []; return [a]; } return []; } async function readShellScript(e) { for (const [t, n] of e.entries()) { if (n === "--") return await readOwnedText(e[t + 1] ?? ""); if (!n.startsWith("-")) return await readOwnedText(n); if (/^-[elux]*c[elux]*$/.test(n)) return e[t + 1]; if (!/^-[elux]+$/.test(n)) return; } } function hasShellShebang(e) { const t = e.split(/\r?\n/, 1)[0] ?? ""; if (!t.startsWith("#!")) return false; const [n = "", ...r] = t.slice(2).trim().split(/\s+/); if (n === "/usr/bin/env") return r.length === 1 && SHELLS.has(r[0] ?? ""); return path.isAbsolute(n) && SHELLS.has(path.basename(n)) && (r.length === 0 || r.length === 1 && /^-[elux]+$/.test(r[0] ?? "")); } async function readOwnedText(e) { if (!path.isAbsolute(e)) return; const t = await fs$1.open(e, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK).catch(() => null); if (!t) return; try { const e = await t.stat(); if (!e.isFile() || e.size > MAX_FILE_BYTES || e.uid !== process.getuid?.()) return; const n = Buffer.alloc(65537); const { bytesRead: r } = await t.read(n, 0, n.length, 0); return r <= MAX_FILE_BYTES ? n.subarray(0, r).toString("utf8") : void 0; } finally { await t.close(); } } async function inspectJob(e, t) { if (!isCandidate(e, t)) return null; const n = `${resolveLaunchAgentGuiDomain()}/${e}`; const r = await execLaunchctl(["print", n], INSPECTION_TIMEOUT_MS); if (isLaunchctlNotLoaded(r)) return null; if (r.code !== 0) throw new Error(`Cannot inspect launchd job ${e}: ${formatLaunchctlResultDetail(r)}`); const i = parseLaunchctlJob(r.stdout, n); const field = (e) => i.fields.get(e); const a = field("program") ?? "unknown"; const o = field("path"); const s = o?.startsWith("/") ? o : void 0; const c = i.arguments ?? []; const l = i.environment; const u = i.environmentBlocks; const d = s ? await readOwnedText(s) : void 0; const f = /^\t\tOPENCLAW_SERVICE_MARKER => openclaw$/m.test(l) && /^\t\tOPENCLAW_SERVICE_KIND => (gateway|node)$/m.test(l); const p = c.some((t) => t.endsWith(`/service-env/${e}-env-wrapper.sh`)); if (f || p || /<key>Comment<\/key>\s*<string>OpenClaw (Gateway|Node)\b/.test(d ?? "")) return null; let m = []; let h; const g = hasShellExecutionEnvironment(u) ? "Shell environment alters execution; left unchanged." : void 0; const _ = c.length ? [a, ...c.slice(1)] : [a]; const v = path.isAbsolute(a) ? lifecycleInvocation(_) : void 0; const y = path.basename(a); const b = SHELLS.has(y); const x = !b && (g || ![ "openclaw", "openclaw.mjs", "node", "bun", "env" ].includes(y)) ? await readOwnedText(a) : void 0; let S = x !== void 0 && hasShellShebang(x); if (g && v && v.program !== a) { const e = await readOwnedText(v.program); S ||= e !== void 0 && hasShellShebang(e); } if (g && (b || S)) h = g; else if (v) m = [v.action]; else if (b) { const e = await readShellScript(_.slice(1)); m = e ? scriptActions(e) : []; h = m.length ? void 0 : "Shell command could not be verified; left unchanged."; } else if (S && x !== void 0) m = scriptActions(x); return { label: e, program: sanitizeForLog(a), keepAlive: /(?:^|\s|\|)keepalive(?:\s|\||$)/.test(field("properties") ?? ""), gatewayActions: m, safeToRemove: m.length > 0 && (field("type") === "Submitted" || Boolean(d)), ...s ? { plistPath: s } : {}, ...h ? { diagnostic: h } : {} }; } async function findForeignLaunchdJobs(e = process.env) { if (process.platform !== "darwin") return []; const t = await execLaunchctl(["list"], INSPECTION_TIMEOUT_MS); if (t.code !== 0) throw new Error(`Cannot list launchd jobs: ${formatLaunchctlResultDetail(t)}`); const n = [...new Set(t.stdout.split(/\r?\n/).flatMap((t) => { const n = t.trim().match(/^(?:-|\d+)\s+-?\d+\s+(\S+)$/)?.[1]; return n && isCandidate(n, e) ? [n] : []; }))].toSorted(); if (n.length > MAX_JOBS) throw new Error(`Too many OpenClaw launchd jobs to inspect safely (${n.length}; limit ${MAX_JOBS}).`); const r = []; const i = Date.now() + 1e4; for (const t of n) { if (Date.now() >= i) throw new Error("OpenClaw launchd job inspection exceeded its 10-second budget."); const n = await inspectJob(t, e); if (n) r.push(n); } return r; } function formatForeignLaunchdJobs(e) { return e.map((e) => [ terminalText`${e.label}: program=${e.program}, keepalive=${e.keepAlive}, Gateway lifecycle=${e.gatewayActions.join("|") || "not verified"}`, e.safeToRemove ? " Removable with openclaw doctor --fix." : " Report only; left unchanged.", ...e.diagnostic ? [terminalText` ${e.diagnostic}`] : [] ].join("\n")).join("\n"); } async function repairForeignLaunchdJob(e, t = process.env) { if (process.platform !== "darwin" || !isCandidate(e.label, t)) return { removed: false, detail: "Protected or unrelated launchd label; left unchanged." }; const n = await inspectJob(e.label, t); if (!n?.safeToRemove) return { removed: false, detail: "Gateway lifecycle command no longer verified; left unchanged." }; const r = `${resolveLaunchAgentGuiDomain()}/${n.label}`; if (n.plistPath) { const e = await execLaunchctl(["disable", r], INSPECTION_TIMEOUT_MS); if (e.code !== 0) return { removed: false, detail: `Could not disable ${n.label}: ${formatLaunchctlResultDetail(e)}` }; const i = await inspectJob(n.label, t); if (!i?.safeToRemove || i.program !== n.program || i.plistPath !== n.plistPath) return { removed: false, detail: `Disabled ${n.label}, but its definition changed before removal; inspect it manually.` }; } const i = await execLaunchctl(["bootout", r], INSPECTION_TIMEOUT_MS); if (i.code !== 0 && !isLaunchctlNotLoaded(i)) return { removed: false, detail: `Could not remove ${n.label}: ${formatLaunchctlResultDetail(i)}` }; const a = await execLaunchctl(["print", r], INSPECTION_TIMEOUT_MS); return isLaunchctlNotLoaded(a) ? { removed: true, detail: `Removed stray launchd job ${n.label} (${n.program}; Gateway ${n.gatewayActions.join("/")}).${n.plistPath ? " Disabled at login; plist retained." : ""}` } : { removed: false, detail: `Removal of ${n.label} could not be confirmed; inspect launchctl print ${r}.` }; } //#endregion export { formatForeignLaunchdJobs as n, repairForeignLaunchdJob as r, findForeignLaunchdJobs as t };