UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

191 lines (190 loc) • 7.87 kB
import { a as asOptionalRecord, d as isStringRecord } from "./record-coerce-CVPuDqcc.mjs"; import { t as hasErrnoCode } from "./errno-DFcoqIT9.mjs"; import { i as hasCommandProcessCleanupError } from "./exec-result-DJMhztYN.mjs"; import { n as runExec } from "./exec-aRIvS9s4.mjs"; import { n as escapeXml } from "./xml-CkRZ_Nxa.mjs"; import fs from "node:fs/promises"; //#region src/daemon/launchd-plist.ts const LAUNCH_AGENT_POLICY = { RunAtLoad: true, KeepAlive: true, ExitTimeOut: 330, ProcessType: "Interactive", ThrottleInterval: 10, Umask: 63, StandardInPath: "/dev/null" }; const LAUNCH_AGENT_ENV_WRAPPER_SHELL = "/bin/sh"; function quoteLaunchAgentEnvironmentValue(e) { return `'${e.replaceAll("'", "'\\''")}'`; } function parseGeneratedEnvValue(e) { const t = e.trim(); if (!t.startsWith("'") || !t.endsWith("'")) return t; return t.slice(1, -1).replaceAll("'\\''", "'"); } function resolveSiblingGeneratedEnvFilePath(e, t) { const n = t?.generatedEnvironmentLabel?.trim(); if (!n) return; const r = e.replaceAll("\\", "/").lastIndexOf("/service-env/"); if (r < 0) return; const i = r + 13 - 1; return `${e.slice(0, i)}/${n}.env`; } function isExpectedGeneratedEnvWrapperPair(e, t, n) { if (!e || !t) return false; if (!n) return e.endsWith("-env-wrapper.sh"); if (n.expectedEnvironmentWrapperPath && n.expectedEnvironmentFilePath && e === n.expectedEnvironmentWrapperPath && t === n.expectedEnvironmentFilePath) return true; const r = n.generatedEnvironmentLabel?.trim(); if (!r) return false; const i = e.replaceAll("\\", "/"); const a = t.replaceAll("\\", "/"); return i.includes("/service-env/") && a.includes("/service-env/") && i.includes(`${r}-env-wrapper.sh`) && a.includes(`${r}.env`); } function resolveGeneratedEnvWrapperLayout(e, t) { for (const n of e[0] === "/bin/sh" ? [1, 0] : [0]) { const r = e[n]; const i = e[n + 1]; if (isExpectedGeneratedEnvWrapperPair(r, i, t) && i) return { envFilePath: i, commandStartIndex: n + 2 }; } return null; } async function readLaunchAgentEnvironmentFile(e, t) { if (e === void 0) return {}; let n = ""; const r = t?.requireEffective ? [e] : Array.from(new Set([ e, resolveSiblingGeneratedEnvFilePath(e, t), t?.expectedEnvironmentFilePath ].filter((e) => Boolean(e)))); for (const e of r) try { n = await fs.readFile(e, "utf8"); break; } catch (e) { if (t?.requireEffective) throw e; } if (!n) return {}; const i = {}; const a = n.split("\n"); for (let e = 0; e < a.length; e++) { const n = (a[e] ?? "").trimStart(); if (!n.trim() || n.startsWith("#")) continue; const r = n.match(/^export\s+([A-Za-z_][A-Za-z0-9_]*)=([\s\S]*)$/); if (!r) { if (t?.requireEffective) throw new Error("Unsupported LaunchAgent environment syntax"); continue; } const o = r[1]; let s = r[2]; if (!o || s === void 0) continue; while (/^'(?:[^']|'\\'')*$/.test(s) && e + 1 < a.length) s += `\n${a[++e]}`; const c = parseGeneratedEnvValue(s); if (t?.requireEffective && quoteLaunchAgentEnvironmentValue(c) !== s.trim()) throw new Error("Unsupported LaunchAgent environment value"); i[o] = c; } return i; } const renderEnvDict = (e) => { if (!e) return ""; const t = Object.entries(e).filter(([e, t]) => typeof t === "string" && (t.trim() || e === "NODE_OPTIONS")); if (t.length === 0) return ""; return `\n <key>EnvironmentVariables</key>\n <dict>${t.map(([e, t]) => `\n <key>${escapeXml(e)}</key>\n <string>${escapeXml(t?.trim() ?? "")}</string>`).join("")}\n </dict>`; }; async function normalizeLaunchdPlistXml(e, t = 5e3) { const { stdout: n } = await runExec("/usr/bin/plutil", [ "-convert", "xml1", "-o", "-", "--", "-" ], { input: e, timeoutMs: Math.max(1, Math.min(t, 5e3)), maxBuffer: 1048576, logOutput: false }); return n; } async function decodeLaunchdPlistMetadata(e, t) { const n = performance.now() + Math.min(t ?? 5e3, 5e3); const r = await normalizeLaunchdPlistXml(e, n - performance.now()); const { stdout: i } = await runExec("/usr/bin/plutil", [ "-convert", "json", "-o", "-", "--", "-" ], { input: r.replace(/<(data|date)>[\s\S]*?<\/\1>/g, "<integer>0</integer>"), timeoutMs: Math.max(1, n - performance.now()), maxBuffer: 1048576, logOutput: false }); return asOptionalRecord(JSON.parse(i)); } async function readLaunchAgentProgramArgumentsFromFile(e, t) { try { const n = await fs.readFile(e).catch(async (n) => { if (hasErrnoCode(n, "ENOENT")) { if (t?.requireEffective) { if (!await fs.lstat(e).then(() => false, (e) => hasErrnoCode(e, "ENOENT"))) throw new Error("Unreadable LaunchAgent definition"); } return null; } throw n; }); if (n === null) return null; return await resolveLaunchAgentProgramArguments(await decodeLaunchdPlistMetadata(n, t?.timeoutMs), e, t); } catch (e) { if (hasCommandProcessCleanupError(e)) throw e; if (t?.requireEffective) throw new Error("Effective LaunchAgent service command could not be inspected.", { cause: e }); return null; } } /** Resolve captured plist metadata through the same generated environment owner as file reads. */ async function resolveLaunchAgentProgramArguments(e, t, n) { const r = e?.ProgramArguments; const i = e?.WorkingDirectory; const a = e?.EnvironmentVariables; if (!Array.isArray(r) || !r.every((e) => typeof e === "string") || i !== void 0 && typeof i !== "string" || a !== void 0 && !isStringRecord(a)) throw new Error("Invalid LaunchAgent command fields"); const o = resolveGeneratedEnvWrapperLayout(r, n); const s = await readLaunchAgentEnvironmentFile(o?.envFilePath, n); const c = o ? r.slice(o.commandStartIndex) : r; if (n?.requireEffective && !c[0]) throw new Error("Missing LaunchAgent command"); const l = { ...a, ...s }; const u = {}; for (const e of Object.keys(l)) u[e] = !Object.hasOwn(s, e) ? "inline" : Object.hasOwn(a ?? {}, e) ? "inline-and-file" : "file"; const d = e?.Program === void 0 ? r[0] : e.Program; if (typeof d === "string" && d) { const e = o && d === r[0] ? c[0] : d; if (e) n?.onEffectiveExecutable?.(e); } return { programArguments: c, ...i ? { workingDirectory: i } : {}, ...Object.keys(l).length > 0 ? { environment: l } : {}, ...Object.keys(u).length > 0 ? { environmentValueSources: u } : {}, sourcePath: t }; } function buildLaunchAgentPlist({ label: e, comment: t, programArguments: n, workingDirectory: r, stdoutPath: i, stderrPath: a, environment: o }) { const s = n.map((e) => `\n <string>${escapeXml(e)}</string>`).join(""); const c = r ? `\n <key>WorkingDirectory</key>\n <string>${escapeXml(r)}</string>` : ""; const l = t?.trim() ? `\n <key>Comment</key>\n <string>${escapeXml(t.trim())}</string>` : ""; const u = renderEnvDict(o); const d = Object.entries(LAUNCH_AGENT_POLICY).map(([e, t]) => { const n = typeof t === "number" ? "integer" : "string"; return ` <key>${e}</key>\n ${typeof t === "boolean" ? `<${t}/>` : `<${n}>${escapeXml(String(t))}</${n}>`}`; }).join("\n"); return `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0">\n <dict>\n <key>Label</key>\n <string>${escapeXml(e)}</string>\n ${l}\n${d}\n <key>ProgramArguments</key>\n <array>${s}\n </array>\n ${c}\n <key>StandardOutPath</key>\n <string>${escapeXml(i)}</string>\n <key>StandardErrorPath</key>\n <string>${escapeXml(a)}</string>${u}\n </dict>\n</plist>\n`; } //#endregion export { normalizeLaunchdPlistXml as a, resolveGeneratedEnvWrapperLayout as c, decodeLaunchdPlistMetadata as i, resolveLaunchAgentProgramArguments as l, LAUNCH_AGENT_POLICY as n, quoteLaunchAgentEnvironmentValue as o, buildLaunchAgentPlist as r, readLaunchAgentProgramArgumentsFromFile as s, LAUNCH_AGENT_ENV_WRAPPER_SHELL as t };